Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(git): bound the default-branch remote query, and make the bound bound (#3603)
Maximilian Roos8865f20ab82a
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2af8f3a2f..f3611f46c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -98,7 +98,7 @@ When no structured alternative exists, document the fragility inline.### Network Access-worktrunk is local-first: the network is touched only when the user asked for it, and only where reaching the wire directly serves that request. **One detection helper is exempt:** the *first* `Repository::default_branch()` per repo may fall through to `git ls-remote`; the result caches in `worktrunk.default-branch` and every later call is local. No other detection helper may add a similar fallback.+worktrunk is local-first: the network is touched only when the user asked for it, and only where reaching the wire directly serves that request. **One detection helper is exempt:** the *first* `Repository::default_branch()` per repo may fall through to `git ls-remote`; the result caches in `worktrunk.default-branch` and every later call is local. The query is bounded by `REMOTE_DETECTION_TIMEOUT` — nothing in git bounds it, and an unreachable host costs ~127 s per address on Linux — and a query that hits the bound falls back to local inference *without* caching it, so an outage can't make a guess permanent. No other detection helper may add a similar fallback.Why: silent "lookup" paths that walk to the wire (alias dispatch, hook context build, recovery) stall commands the user wouldn't expect to do network work, worst on a fresh clone. The `default_branch()` bootstrap keeps a fresh clone usable while bounding the exception to one helper firing at most once per repo.@@ -125,7 +125,7 @@ Why: wt installs a `signal_hook` SIGINT/SIGTERM handler so it can forward signal- Signal-derived child exits surface structurally: stream mode (`Cmd::stream`) as `WorktrunkError::ChildProcessExited { signal: Some(sig), .. }`, capture mode (`Cmd::run`) as `CommandError { signal: Some(sig), .. }`. These fields are the structured channel — never sniff `code >= 128` or parse error messages.- Detect via `err.interrupt_signal()` (the `worktrunk::git::ErrorExt` trait). When it returns `Some(signal)`, propagate as `WorktrunkError::Interrupted { signal, hint }` and break the loop. `Interrupted` exits `128 + signal` (130 SIGINT, 143 SIGTERM) and renders once, at exit, per shell convention: silent for SIGINT (the terminal echoed `^C`), `Terminated` for SIGTERM — the line the shell would print if wt weren't trapping the signal. `hint` carries an optional recovery line for state the interrupt left behind (e.g. a mid-rebase worktree).-- In capture mode only SIGINT/SIGTERM classify as interrupts. Capture children get no forwarding or escalation, and their captured output would be discarded by the silent exit — so a child killed by any other signal (a crash, an OOM kill) surfaces as a visible error instead. Stream mode counts any signal: output already streamed to the terminal, and user-initiated kills are normalized upstream to the originating SIGINT/SIGTERM (`seen_signal` in `shell_exec`, the concurrent runner's originating-signal override).+- In capture mode only SIGINT/SIGTERM classify as interrupts. Capture children get no forwarding or escalation, and their captured output would be discarded by the silent exit — so a child killed by any other signal (a crash, an OOM kill) surfaces as a visible error instead. A capture child with a `Cmd::timeout` is the one the tty broadcast doesn't reach: it runs in its own process group so expiry can tear down its whole tree (`run_with_timeout_impl`), which is what makes the bound bound anything, so a Ctrl-C during one waits out the remaining timeout. Stream mode counts any signal: output already streamed to the terminal, and user-initiated kills are normalized upstream to the originating SIGINT/SIGTERM (`seen_signal` in `shell_exec`, the concurrent runner's originating-signal override).- The check happens **before** any `FailureStrategy` branch — Warn must NOT swallow signal-derived errors.- `handle_command_error` in `src/commands/command_executor.rs` enforces this for hook and alias pipelines (foreground and concurrent groups); `for_each.rs` enforces it for the worktree loop. New code that loops over child processes calls `.interrupt_signal()` on per-iteration errors and breaks.diff --git a/docs/content/config.md b/docs/content/config.mdindex d041cef33..4aaa63c29 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -1026,11 +1026,13 @@ Worktrunk detects the default branch automatically:1. **Worktrunk cache** — Checks `git config worktrunk.default-branch`2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)-3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s-4. **Local inference** — If no remote, infers from local branches+3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s, abandoned after 10s+4. **Local inference** — If no remote, or the query was abandoned, infers from local branchesOnce detected, the result is cached in `worktrunk.default-branch` for fast access. The cache isn't re-validated on every command, so a later change to `origin/HEAD` — a renamed default branch followed by `git remote set-head origin -a` — isn't picked up automatically. `wt config state` flags the drift when the cached value differs from the remote's local HEAD; `set` adopts the new branch and `clear` re-detects.+An abandoned remote query is the one case that isn't cached: the branch it inferred locally answers that command, but a value guessed while the remote was unreachable would otherwise become permanent, so the next command queries again.+The local inference fallback uses these heuristics in order:- If only one local branch exists, uses it- For bare repos or empty repos, checks `symbolic-ref HEAD`diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex 96a21dd55..5116d8a0f 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -1065,11 +1065,13 @@ Worktrunk detects the default branch automatically:1. **Worktrunk cache** — Checks `git config worktrunk.default-branch`2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)-3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s-4. **Local inference** — If no remote, infers from local branches+3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s, abandoned after 10s+4. **Local inference** — If no remote, or the query was abandoned, infers from local branchesOnce detected, the result is cached in `worktrunk.default-branch` for fast access. The cache isn't re-validated on every command, so a later change to `origin/HEAD` — a renamed default branch followed by `git remote set-head origin -a` — isn't picked up automatically. `wt config state` flags the drift when the cached value differs from the remote's local HEAD; `set` adopts the new branch and `clear` re-detects.+An abandoned remote query is the one case that isn't cached: the branch it inferred locally answers that command, but a value guessed while the remote was unreachable would otherwise become permanent, so the next command queries again.+The local inference fallback uses these heuristics in order:- If only one local branch exists, uses it- For bare repos or empty repos, checks `symbolic-ref HEAD`diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex 96a21dd55..5116d8a0f 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -1065,11 +1065,13 @@ Worktrunk detects the default branch automatically:1. **Worktrunk cache** — Checks `git config worktrunk.default-branch`2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)-3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s-4. **Local inference** — If no remote, infers from local branches+3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s, abandoned after 10s+4. **Local inference** — If no remote, or the query was abandoned, infers from local branchesOnce detected, the result is cached in `worktrunk.default-branch` for fast access. The cache isn't re-validated on every command, so a later change to `origin/HEAD` — a renamed default branch followed by `git remote set-head origin -a` — isn't picked up automatically. `wt config state` flags the drift when the cached value differs from the remote's local HEAD; `set` adopts the new branch and `clear` re-detects.+An abandoned remote query is the one case that isn't cached: the branch it inferred locally answers that command, but a value guessed while the remote was unreachable would otherwise become permanent, so the next command queries again.+The local inference fallback uses these heuristics in order:- If only one local branch exists, uses it- For bare repos or empty repos, checks `symbolic-ref HEAD`diff --git a/src/cli/config.rs b/src/cli/config.rsindex a881e640a..8e71919e4 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -807,11 +807,13 @@ Worktrunk detects the default branch automatically:1. **Worktrunk cache** — Checks `git config worktrunk.default-branch`2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)-3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s-4. **Local inference** — If no remote, infers from local branches+3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s, abandoned after 10s+4. **Local inference** — If no remote, or the query was abandoned, infers from local branchesOnce detected, the result is cached in `worktrunk.default-branch` for fast access. The cache isn't re-validated on every command, so a later change to `origin/HEAD` — a renamed default branch followed by `git remote set-head origin -a` — isn't picked up automatically. `wt config state` flags the drift when the cached value differs from the remote's local HEAD; `set` adopts the new branch and `clear` re-detects.+An abandoned remote query is the one case that isn't cached: the branch it inferred locally answers that command, but a value guessed while the remote was unreachable would otherwise become permanent, so the next command queries again.+The local inference fallback uses these heuristics in order:- If only one local branch exists, uses it- For bare repos or empty repos, checks `symbolic-ref HEAD`diff --git a/src/git/remove.rs b/src/git/remove.rsindex ca33810bc..8aadfbcae 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -755,10 +755,7 @@ mod tests {).unwrap();let git = |dir: &Path| {- Cmd::new("git")- .current_dir(dir)- .env("GIT_CONFIG_GLOBAL", &gitconfig)- .env("GIT_CONFIG_SYSTEM", "/dev/null")+ crate::testing::configure_git_env(Cmd::new("git"), &gitconfig).current_dir(dir)};let main = tmp.path().join("repo");@@ -817,10 +814,8 @@ mod tests {.unwrap();let main = tmp.path().join("repo");std::fs::create_dir(&main).unwrap();- Cmd::new("git")+ crate::testing::configure_git_env(Cmd::new("git"), &gitconfig).current_dir(&main)- .env("GIT_CONFIG_GLOBAL", &gitconfig)- .env("GIT_CONFIG_SYSTEM", "/dev/null").args(["init", "-b", "main"]).run().unwrap();@@ -854,10 +849,8 @@ mod tests {.unwrap();let main = tmp.path().join("repo");std::fs::create_dir(&main).unwrap();- Cmd::new("git")+ crate::testing::configure_git_env(Cmd::new("git"), &gitconfig).current_dir(&main)- .env("GIT_CONFIG_GLOBAL", &gitconfig)- .env("GIT_CONFIG_SYSTEM", "/dev/null").args(["init", "-b", "main"]).run().unwrap();diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex 91e42aa1f..e7b051087 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -1,6 +1,7 @@//! Git config, hints, marker, and default branch operations for Repository.use std::path::PathBuf;+use std::time::Duration;use anyhow::Context;use color_print::cformat;@@ -11,6 +12,46 @@ use crate::git::CommandError;use super::{DefaultBranchName, GitError, Repository};+/// How long `git ls-remote` may run before default-branch detection gives up.+///+/// The query normally answers in 100 ms–2 s, and until this bound nothing+/// limited how long it could take *not* to answer: an unanswered SYN costs+/// ~127 s per address on Linux (`tcp_syn_retries=6`) and git tries each of a+/// host's addresses in turn, so a remote behind a dropped VPN or a dead host+/// stalled `wt list --full` and `wt switch` for minutes. The bound is far+/// above a slow-but-working handshake and far below that, so it separates the+/// two cases without a judgement call.+const REMOTE_DETECTION_TIMEOUT: Duration = Duration::from_secs(10);++/// Outcome of the remote half of default-branch detection.+enum RemoteDetection {+ /// The remote — or git's local `<remote>/HEAD` cache for it — named a branch.+ Found(String),+ /// There is no remote, or the query failed — no HEAD, no such repository,+ /// an offline laptop. Whatever the local branches say stands in, and it is+ /// cached: `ls-remote` exits 128 for all of those alike, so telling a+ /// down network from a remote that simply has no HEAD would mean reading+ /// git's error text, and re-querying on every command is the cost the+ /// cache exists to avoid. Only a timeout separates cleanly, via+ /// `ErrorKind::TimedOut`.+ Unavailable,+ /// The query hit [`REMOTE_DETECTION_TIMEOUT`]. The default branch is+ /// unknown rather than absent, so local inference answers this invocation+ /// but is not written to `worktrunk.default-branch`: a guess made while+ /// the network was down would otherwise outlive the outage, and the+ /// persisted cache is exactly what stops later calls from re-detecting.+ TimedOut,+}++/// Whether a command failed by exceeding its [`crate::shell_exec::Cmd::timeout`].+///+/// `Cmd::run` reports the kill as an [`std::io::Error`], which `anyhow`+/// context wraps but preserves in the chain.+fn timed_out(err: &anyhow::Error) -> bool {+ err.downcast_ref::<std::io::Error>()+ .is_some_and(|e| e.kind() == std::io::ErrorKind::TimedOut)+}+impl Repository {/// Get a git config value. Returns None if the key doesn't exist.///@@ -367,12 +408,15 @@ impl Repository {/// Detection strategy:/// 1. Check worktrunk cache (`git config worktrunk.default-branch`)/// 2. Try primary remote's local cache (e.g., `origin/HEAD`)- /// 3. Query remote (`git ls-remote`) — may take 100 ms–2 s (sole wire fallback)+ /// 3. Query remote (`git ls-remote`) — may take 100 ms–2 s (sole wire+ /// fallback), bounded by `REMOTE_DETECTION_TIMEOUT`/// 4. Infer from local branches if no remote////// Detection results are cached to `worktrunk.default-branch` for future- /// calls. Result is also cached in the shared repo cache (shared across- /// all worktrees).+ /// calls, except when step 3 timed out — see `RemoteDetection::TimedOut`.+ /// Result is also cached in the shared repo cache (shared across all+ /// worktrees), timeouts included: one invocation waits out the bound once,+ /// not once per caller.////// To minimize latency on the rare cold-clone case:/// - Defer calling this until after fast, local checks (see e497f0f for an example).@@ -400,14 +444,19 @@ impl Repository {}// Detect: try remote, then local inference- let detected = self.detect_from_remote().or_else(|| {- self.infer_default_branch_locally()+ let remote = self.detect_from_remote();+ let persist = !matches!(remote, RemoteDetection::TimedOut);+ let detected = match remote {+ RemoteDetection::Found(branch) => Some(branch),+ RemoteDetection::Unavailable | RemoteDetection::TimedOut => self+ .infer_default_branch_locally().inspect_err(|e| tracing::debug!(error = %e, "Local inference failed: {e}"))- .ok()- });+ .ok(),+ };// Cache detected result to git config for future runs- if let Some(ref branch) = detected+ if persist+ && let Some(ref branch) = detected&& let Err(e) = self.set_config_value("worktrunk.default-branch", branch){tracing::debug!(error = %e, "Failed to persist default-branch cache: {e}");@@ -419,16 +468,31 @@ impl Repository {}/// Try to detect default branch from remote.- fn detect_from_remote(&self) -> Option<String> {- let remote = self.primary_remote().ok()?;+ fn detect_from_remote(&self) -> RemoteDetection {+ let Ok(remote) = self.primary_remote() else {+ return RemoteDetection::Unavailable;+ };// Try git's local cache for this remote (e.g., origin/HEAD)if let Ok(branch) = self.local_default_branch(&remote) {- return Some(branch);+ return RemoteDetection::Found(branch);}// Query remote directly (may be slow)- self.query_remote_default_branch(&remote).ok()+ match self.query_remote_default_branch(&remote) {+ Ok(branch) => RemoteDetection::Found(branch),+ Err(e) if timed_out(&e) => {+ tracing::debug!(+ "Remote default-branch query exceeded {REMOTE_DETECTION_TIMEOUT:?}; \+ falling back to local inference without caching it"+ );+ RemoteDetection::TimedOut+ }+ Err(e) => {+ tracing::debug!(error = %e, "Remote default-branch query failed: {e}");+ RemoteDetection::Unavailable+ }+ }}/// Resolve a target branch from an optional override@@ -584,7 +648,10 @@ impl Repository {}pub(super) fn query_remote_default_branch(&self, remote: &str) -> anyhow::Result<String> {- let stdout = self.run_command(&["ls-remote", "--symref", remote, "HEAD"])?;+ let stdout = self.run_command_bounded(+ &["ls-remote", "--symref", remote, "HEAD"],+ Some(REMOTE_DETECTION_TIMEOUT),+ )?;DefaultBranchName::from_remote(&stdout).map(DefaultBranchName::into_string)}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 63a8006d3..44c86b61a 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1570,13 +1570,35 @@ impl Repository {/// # Ok::<(), anyhow::Error>(())/// ```pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {- let output = self- .with_object_store_env(- Cmd::new("git")- .args(args.iter().copied())- .current_dir(&self.discovery_path)- .context(self.logging_context()),- )+ self.run_command_bounded(args, None)+ }++ /// [`run_command`](Self::run_command) with an optional wall-clock bound.+ ///+ /// A child still running when `timeout` expires is killed and the call+ /// fails with [`std::io::ErrorKind::TimedOut`].+ ///+ /// Local git commands pass `None`: they finish or fail on their own, so a+ /// bound would only turn machine load into a spurious failure. The bound+ /// is for the one git command in worktrunk that can reach the wire —+ /// `ls-remote` in [`default_branch`](Self::default_branch), where nothing+ /// else limits how long an unreachable host takes to not answer.+ pub(super) fn run_command_bounded(+ &self,+ args: &[&str],+ timeout: Option<std::time::Duration>,+ ) -> anyhow::Result<String> {+ let mut cmd = self.with_object_store_env(+ Cmd::new("git")+ .args(args.iter().copied())+ .current_dir(&self.discovery_path)+ .context(self.logging_context()),+ );+ if let Some(timeout) = timeout {+ cmd = cmd.timeout(timeout);+ }++ let output = cmd.run().with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex a4f00df29..1f12cf79d 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -1145,10 +1145,7 @@ fn prewarm_still_caches_preload_when_worktree_config_disabled() {let gitconfig = tmp.path().join("test-gitconfig");std::fs::write(&gitconfig, "[init]\n\tdefaultBranch = main\n").unwrap();- let out = Cmd::new("git")- .env("GIT_CONFIG_GLOBAL", &gitconfig)- .env("GIT_CONFIG_SYSTEM", "/dev/null")- .env("LC_ALL", "C")+ let out = crate::testing::configure_git_env(Cmd::new("git"), &gitconfig).args(["init", "-b", "main", root.to_str().unwrap()]).run().unwrap();diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex c5b722be5..2567e2a32 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -853,12 +853,34 @@ fn format_stream_bounded(bytes: &[u8], prefix: &str) -> Vec<String> {/// Implementation of timeout-based command execution.////// Spawns reader threads to drain stdout/stderr concurrently (preventing deadlock when-/// output exceeds the OS pipe buffer), then waits with timeout. On timeout, kills the-/// child; scoped threads see EOF and join automatically before the function returns.+/// output exceeds the OS pipe buffer), then waits with timeout. On timeout, tears down+/// the child's whole process tree; scoped threads see EOF and join automatically before+/// the function returns.+///+/// **The teardown reaches the tree, not just the child, because otherwise the timeout+/// doesn't bound anything.** A grandchild inherits the child's stderr pipe, so a+/// surviving one holds the write end open and `read_to_end` blocks until it exits —+/// making this function return `TimedOut` only after the *grandchild's* full runtime.+/// The case that matters is the one this timeout exists for: `git ls-remote` against an+/// unreachable host spawns `git-remote-https`, which sits in `connect()` for ~127 s per+/// address on Linux and does not notice that git died. So the child is spawned into its+/// own process group and [`kill_timed_out_tree`] signals the group.+///+/// Isolating the group costs the kernel's tty broadcast: a Ctrl-C no longer reaches a+/// timed child directly, so the user waits out the remaining timeout instead of+/// interrupting it. That is bounded by the timeout the caller chose (seconds), whereas+/// the orphan the alternative leaves behind — kill the child, stop waiting on the+/// readers — holds a pipe for as long as its own operation takes, once per spawn.fn run_with_timeout_impl(cmd: &mut Command,timeout: std::time::Duration,) -> std::io::Result<std::process::Output> {+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ cmd.process_group(0);+ }+let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped())@@ -898,6 +920,7 @@ fn run_with_timeout_impl(})}None => {+ kill_timed_out_tree(child.id());let _ = child.kill();let _ = child.wait();Err(std::io::Error::new(@@ -909,6 +932,29 @@ fn run_with_timeout_impl(})}+/// Tear down the process tree of a child that outlived its timeout.+///+/// `run_with_timeout_impl` made the child its own process-group leader, so its+/// pid is the pgid and the TERM → KILL escalation reaches every member. SIGTERM+/// first for the same reason [`signal_background_pid`] uses it: git's lockfile+/// handlers run on TERM, so an interrupted git cleans up after itself.+#[cfg(unix)]+fn kill_timed_out_tree(pid: u32) {+ forward_signal_with_escalation(pid as i32, signal_hook::consts::SIGTERM);+}++/// `taskkill /T` walks the child tree Windows has no process group for; `/F`+/// forces. Best-effort — the pid may already be gone, or have left children+/// that detached from it.+#[cfg(windows)]+fn kill_timed_out_tree(pid: u32) {+ let _ = Command::new("taskkill")+ .args(["/T", "/F", "/PID", &pid.to_string()])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+}+// ============================================================================// Builder-style command execution// ============================================================================@@ -1274,6 +1320,10 @@ impl Cmd {////// Note: Timeout is not supported by `.stream()` since streaming commands/// are interactive and should not be time-limited.+ ///+ /// A timed command runs in its own process group so expiry can tear down+ /// its whole tree, which also means Ctrl-C no longer reaches it — see+ /// `run_with_timeout_impl` for both halves of that.pub fn timeout(mut self, duration: std::time::Duration) -> Self {self.timeout = Some(duration);self@@ -2470,6 +2520,31 @@ mod tests {assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);}+ /// The timeout has to bound wall-clock, not just signal the direct child.+ /// A grandchild inherits the child's stderr pipe, so one that survives the+ /// kill holds the write end open and the output readers block on it — which+ /// used to make `run()` return `TimedOut` only once the *grandchild* exited+ /// (30 s here, ~127 s for the `git-remote-https` case this bound exists+ /// for). `; :` keeps the shell from `exec`ing sleep, so there really is a+ /// grandchild to leave behind.+ #[test]+ #[cfg(unix)]+ fn test_cmd_timeout_bounds_wall_clock_with_surviving_grandchild() {+ let start = std::time::Instant::now();+ let err = Cmd::new("sh")+ .args(["-c", "sleep 30; :"])+ .timeout(Duration::from_millis(200))+ .run()+ .unwrap_err();+ let elapsed = start.elapsed();++ assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);+ assert!(+ elapsed < Duration::from_secs(10),+ "timeout waited on the grandchild: {elapsed:?}"+ );+ }+#[test]fn test_cmd_without_timeout_completes() {let result = Cmd::new("echo").arg("no timeout").run();diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex 7ddae5834..deb822522 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -2096,10 +2096,9 @@ mod bare_repo_prompt_pty {// Declining records the opt-out as a hint (count 1), not under the legacy// top-level key — so it participates in `wt config state`.- let hint_value = Cmd::new("git")+ let hint_value = configure_git_env(Cmd::new("git"), test.git_config_path()).args(["config", "worktrunk.hints.skip-bare-repo-prompt"]).current_dir(&main_worktree)- .env("GIT_CONFIG_GLOBAL", test.git_config_path()).run().unwrap();assert_eq!(@@ -2109,10 +2108,9 @@ mod bare_repo_prompt_pty {);// The legacy top-level key must not be written anymore.- let legacy_key = Cmd::new("git")+ let legacy_key = configure_git_env(Cmd::new("git"), test.git_config_path()).args(["config", "worktrunk.skip-bare-repo-prompt"]).current_dir(&main_worktree)- .env("GIT_CONFIG_GLOBAL", test.git_config_path()).run().unwrap();assert!(diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rsindex 4d224b67b..09a973fdc 100644--- a/tests/integration_tests/default_branch.rs+++ b/tests/integration_tests/default_branch.rs@@ -67,6 +67,85 @@ fn test_get_default_branch_caches_result(#[from(repo_with_remote)] repo: TestRepassert_eq!(branch, "main");}+/// A remote that never answers is bounded, and the fallback it forces is not+/// persisted. `ls-remote` has no timeout of its own — an unreachable host costs+/// ~127 s per address on Linux — so detection gives up after+/// `REMOTE_DETECTION_TIMEOUT` and infers from local branches instead. It must+/// not write that inference to `worktrunk.default-branch`: the persisted cache+/// is what stops later calls from re-detecting, so a guess made during an+/// outage would become the repo's permanent answer.+///+/// The stall is reproduced without touching the network — `origin` is a local+/// path whose `uploadpack` command never returns. The bound under test is+/// platform-independent; only this vehicle needs a POSIX `sleep`.+#[rstest]+#[cfg(unix)]+fn test_default_branch_unreachable_remote_is_bounded_and_not_cached(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ repo.clear_origin_head();+ let _ = repo+ .git_command()+ .args(["config", "--unset", "worktrunk.default-branch"])+ .run();+ // `sh -c '…'` rather than a bare `sleep`: git appends the repository path,+ // which `sleep` would reject as a second interval but `sh` takes as `$0`.+ repo.run_git(&["config", "remote.origin.uploadpack", "sh -c 'sleep 120'"]);++ let start = std::time::Instant::now();+ let branch = Repository::at(repo.root_path()).unwrap().default_branch();+ let elapsed = start.elapsed();++ assert_eq!(+ branch.as_deref(),+ Some("main"),+ "local inference must still answer while the remote hangs"+ );+ assert!(+ elapsed < std::time::Duration::from_secs(60),+ "ls-remote was not bounded: took {elapsed:?}"+ );++ let cached = repo+ .git_command()+ .args(["config", "--get", "worktrunk.default-branch"])+ .run()+ .unwrap();+ assert!(+ !cached.status.success(),+ "a timed-out detection must not be cached, got {:?}",+ String::from_utf8_lossy(&cached.stdout).trim()+ );+}++/// A remote that fails fast — a deleted upstream, an offline laptop — falls+/// back to local inference too, and that answer *is* cached. `ls-remote` exits+/// 128 whether the network is down or the remote simply has no HEAD, so the+/// two aren't separable without reading git's error text, and re-querying on+/// every command is what the cache exists to avoid.+#[rstest]+fn test_default_branch_unresolvable_remote_falls_back_and_caches(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ repo.clear_origin_head();+ let _ = repo+ .git_command()+ .args(["config", "--unset", "worktrunk.default-branch"])+ .run();+ let gone = repo.root_path().join("no-such-remote");+ repo.run_git(&["config", "remote.origin.url", &gone.to_string_lossy()]);++ let branch = Repository::at(repo.root_path()).unwrap().default_branch();+ assert_eq!(branch.as_deref(), Some("main"));++ let cached = repo+ .git_command()+ .args(["config", "--get", "worktrunk.default-branch"])+ .run()+ .unwrap();+ assert_eq!(String::from_utf8_lossy(&cached.stdout).trim(), "main");+}+#[rstest]fn test_get_default_branch_no_remote(repo: TestRepo) {// Remove origin (fixture has it) for this no-remote testdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snapindex 71b1bd083..8eeedd65e 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_default_branch.snap@@ -10,6 +10,7 @@ info:env:CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileLANG: CLC_ALL: CLLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"@@ -80,11 +81,13 @@ Worktrunk detects the default branch automatically:1. [1mWorktrunk cache[0m — Checks [2mgit config worktrunk.default-branch[0m2. [1mGit cache[0m — Detects primary remote and checks its HEAD (e.g., [2morigin/HEAD[0m)-3. [1mRemote query[0m — If not cached, queries [2mgit ls-remote[0m — typically 100ms–2s-4. [1mLocal inference[0m — If no remote, infers from local branches+3. [1mRemote query[0m — If not cached, queries [2mgit ls-remote[0m — typically 100ms–2s, abandoned after 10s+4. [1mLocal inference[0m — If no remote, or the query was abandoned, infers from local branchesOnce detected, the result is cached in [2mworktrunk.default-branch[0m for fast access. The cache isn't re-validated on every command, so a later change to [2morigin/HEAD[0m — a renamed default branch followed by [2mgit remote set-head origin -a[0m — isn't picked up automatically. [2mwt config state[0m flags the drift when the cached value differs from the remote's local HEAD; [2mset[0m adopts the new branch and [2mclear[0m re-detects.+An abandoned remote query is the one case that isn't cached: the branch it inferred locally answers that command, but a value guessed while the remote was unreachable would otherwise become permanent, so the next command queries again.+The local inference fallback uses these heuristics in order:- If only one local branch exists, uses it- For bare repos or empty repos, checks [2msymbolic-ref HEAD[0m