Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: honour -C in the statusline and in every supplied path (#3567)
Maximilian Roosedcfe5fe0c1a
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 7aa8e7208..4183aa68b 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -76,7 +76,7 @@ use crate::commands::picker::preview_cache;use anyhow::Context;use color_print::cformat;use path_slash::PathExt as _;-use worktrunk::git::{BranchRef, Repository, sha_cache};+use worktrunk::git::{BranchRef, Repository, resolve_input_path, sha_cache};use worktrunk::path::format_path_for_display;use worktrunk::styling::{eprintln, format_heading, format_with_gutter, hint_message, info_message, println,@@ -656,6 +656,8 @@ pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyho(buf, "stdin".to_string())}Some(p) => {+ // A relative trace path resolves against `-C` — see `resolve_input_path`.+ let p = resolve_input_path(p);let content = std::fs::read_to_string(&p).with_context(|| format!("Failed to read trace {}", format_path_for_display(&p)))?;(content, format_path_for_display(&p).to_string())diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex ba775bb7f..93598d552 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -6,17 +6,25 @@//!//! This command reuses the data collection infrastructure from `wt list`,//! avoiding duplication of git operations.+//!+//! Which worktree gets described has one resolution point, in [`run`]:+//! `--format=claude-code` takes the directory Claude Code names on stdin,+//! since that's the session's directory rather than wt's; every other caller+//! (and claude-code mode with no stdin) gets [`Repository::current_worktree`].+//! That accessor resolves against the repository's discovery path, so `-C`+//! selects the worktree — `std::env::current_dir()` would not, because `-C`+//! sets the discovery path without chdir'ing the process.use std::collections::HashMap;use std::env;use std::io::{self, IsTerminal, Read};-use std::path::{Component, Path};+use std::path::{Component, Path, PathBuf};use dunce::canonicalize;use ansi_str::AnsiStr;use anyhow::{Context, Result};-use worktrunk::git::Repository;+use worktrunk::git::{Repository, WorkingTree};use worktrunk::styling::{fix_dim_after_color_reset, terminal_width_for_statusline, truncate_visible,};@@ -728,37 +736,42 @@ pub fn run(format: StatuslineFormat) -> Result<()> {let claude_code = matches!(format, StatuslineFormat::ClaudeCode);- // Get context - either from stdin (claude-code mode) or current directory- let (cwd, model_name, context_used_percentage, rate_limits) = if claude_code {+ // Get context from stdin (claude-code mode only)+ let (workspace_dir, model_name, context_used_percentage, rate_limits) = if claude_code {let ctx = ClaudeCodeContext::from_stdin();- let current_dir = ctx- .as_ref()- .map(|c| c.current_dir.clone())- .unwrap_or_else(|| env::current_dir().unwrap_or_default().display().to_string());+ let dir = ctx.as_ref().map(|c| PathBuf::from(&c.current_dir));let model = ctx.as_ref().and_then(|c| c.model_name.clone());let context_pct = ctx.as_ref().and_then(|c| c.context_used_percentage);let limits = ctx.map(|c| c.rate_limits).unwrap_or_default();- (- Path::new(¤t_dir).to_path_buf(),- model,- context_pct,- limits,- )+ (dir, model, context_pct, limits)} else {- (- env::current_dir().context("Failed to get current directory")?,- None,- None,- Vec::new(),- )+ (None, None, None, Vec::new())};+ let repo = Repository::current().ok();++ // The worktree this statusline describes. Claude Code names its session's+ // directory on stdin, which wins; every other caller is described by the+ // directory `wt` itself was pointed at, which is `current_worktree()` and+ // not `env::current_dir()` — `-C` sets the discovery path without chdir'ing+ // the process, so reading the process cwd would silently drop the flag.+ let worktree = repo.as_ref().map(|repo| match &workspace_dir {+ Some(dir) => repo.worktree_at(dir),+ None => repo.current_worktree(),+ });+// Build segments with prioritieslet mut segments: Vec<StatuslineSegment> = Vec::new();// Directory (claude-code mode only) - priority 0let dir_str = if claude_code {- let formatted = format_directory_fish_style(&cwd);+ // Without stdin the directory falls back to the worktree above, so it+ // honours `-C` too; the process cwd is the last resort for a path that+ // isn't in a repo at all.+ let dir = workspace_dir+ .or_else(|| worktree.as_ref().map(|wt| wt.path().to_path_buf()))+ .unwrap_or_else(|| env::current_dir().unwrap_or_default());+ let formatted = format_directory_fish_style(&dir);// Only push non-empty directory segments (empty can happen if cwd is ".")if !formatted.is_empty() {segments.push(StatuslineSegment::new(@@ -772,10 +785,10 @@ pub fn run(format: StatuslineFormat) -> Result<()> {};// Git status segments- if let Ok(repo) = Repository::current()- && repo.worktree_at(&cwd).git_dir().is_ok()+ if let Some(worktree) = &worktree+ && worktree.git_dir().is_ok(){- let git_segments = git_status_segments(&repo, &cwd)?;+ let git_segments = git_status_segments(worktree)?;// In claude-code mode, skip branch segment if directory matches worktrunk templatelet git_segments = if let Some(ref dir) = dir_str {@@ -840,8 +853,6 @@ pub fn run(format: StatuslineFormat) -> Result<()> {////// Outputs the current worktree as JSON, using the same structure as `wt list --format=json`.fn run_json() -> Result<()> {- let cwd = env::current_dir().context("Failed to get current directory")?;-let repo = Repository::current().context("Not in a git repository")?;// Warnings are suppressed on this surface, so an unset (or invalid) key@@ -889,15 +900,17 @@ fn run_json() -> Result<()> {}};- // Verify we're in a worktree- if repo.worktree_at(&cwd).git_dir().is_err() {+ // Verify the directory this command operates on (`-C`, else the process+ // cwd) is in a worktree+ if repo.current_worktree().git_dir().is_err() {// Not in a worktree - emit an empty result (consistent with wt list)return print_empty();}// Get current worktree info// Use git rev-parse --show-toplevel (via current_worktree().root()) to correctly identify- // the worktree containing cwd, rather than prefix matching which fails for nested worktrees.+ // the worktree containing that directory, rather than prefix matching which fails for+ // nested worktrees.let worktrees = repo.list_worktrees()?;let worktree_root = repo.current_worktree().root()?;let current_worktree = worktrees.iter().find(|wt| {@@ -992,14 +1005,17 @@ fn filter_redundant_branch(segments: Vec<StatuslineSegment>, dir: &str) -> Vec<S/// Get git status as prioritized segments for the current worktree.////// CI status and the dev-server URL render as clickable OSC 8 hyperlinks.-fn git_status_segments(repo: &Repository, cwd: &Path) -> Result<Vec<StatuslineSegment>> {+fn git_status_segments(worktree: &WorkingTree) -> Result<Vec<StatuslineSegment>> {use super::list::columns::ColumnKind;+ let repo = worktree.repo();+// Get current worktree info- // Use git rev-parse --show-toplevel (via worktree_at().root()) to correctly identify- // the worktree containing cwd, rather than prefix matching which fails for nested worktrees.+ // Use git rev-parse --show-toplevel (via WorkingTree::root()) to correctly identify+ // the worktree containing the path, rather than prefix matching which fails for+ // nested worktrees.let worktrees = repo.list_worktrees()?;- let worktree_root = repo.worktree_at(cwd).root()?;+ let worktree_root = worktree.root()?;let current_worktree = worktrees.iter().find(|wt| {canonicalize(&wt.path).map(|p| p == worktree_root)@@ -1008,7 +1024,7 @@ fn git_status_segments(repo: &Repository, cwd: &Path) -> Result<Vec<StatuslineSelet Some(wt) = current_worktree else {// Not in a worktree - just show branch name as a segment- if let Ok(Some(branch)) = repo.current_worktree().branch() {+ if let Ok(Some(branch)) = worktree.branch() {return Ok(vec![StatuslineSegment::from_column(branch.to_string(),ColumnKind::Branch,diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 05ca3a4da..da82feac7 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -3,13 +3,12 @@//! Functions for resolving worktree arguments and computing expected paths.use std::io::IsTerminal;-use std::path::{Path, PathBuf};+use std::path::PathBuf;-use anyhow::Context;use color_print::cformat;use normalize_path::NormalizePath;use worktrunk::config::UserConfig;-use worktrunk::git::{Repository, ResolvedWorktree};+use worktrunk::git::{Repository, ResolvedWorktree, resolve_input_path};use worktrunk::path::{format_path_for_display, paths_match};use worktrunk::styling::{eprintln, format_toml, hint_message, info_message, success_message, warning_message,@@ -27,8 +26,9 @@ use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};/// 5. Otherwise, return branch-only (no worktree)////// If branch lookup fails to find a worktree, the argument is tried as a-/// filesystem path (absolute or relative to CWD). This supports removing-/// detached HEAD worktrees which have no branch name.+/// filesystem path — absolute, or relative to the directory wt was pointed at+/// (`-C`, else the process cwd). This supports removing detached HEAD worktrees+/// which have no branch name.pub fn resolve_worktree_arg(repo: &Repository, name: &str) -> anyhow::Result<ResolvedWorktree> {// Special symbols - delegate to Repository for consistent error handlingmatch name {@@ -49,16 +49,10 @@ pub fn resolve_worktree_arg(repo: &Repository, name: &str) -> anyhow::Result<Res});}- // No worktree for branch - fall back to path-based lookup (supports detached worktrees)- let candidate = Path::new(name);- // Try as absolute path, or resolve relative to CWD- let abs_path = if candidate.is_absolute() {- candidate.to_path_buf()- } else {- std::env::current_dir()- .context("Failed to determine current directory")?- .join(candidate)- };+ // No worktree for branch - fall back to path-based lookup (supports detached+ // worktrees). A relative path resolves against `-C`, like git's own path+ // arguments — see `resolve_input_path`.+ let abs_path = resolve_input_path(name);if let Some((path, wt_branch)) = repo.worktree_at_path(&abs_path)? {return Ok(ResolvedWorktree::Worktree {path,diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 3048cd73e..c419fb8c3 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -22,7 +22,7 @@ use worktrunk::git::remote_ref::{};use worktrunk::git::{GitError, GitRemoteUrl, RefContext, RefType, Repository, SwitchSuggestionCtx,- current_or_recover,+ current_or_recover, resolve_input_path,};use worktrunk::shell_exec::{ShellEscapeMode, directive_shell_escape_mode, shell_escape_for};use worktrunk::styling::{@@ -855,15 +855,12 @@ fn plan_switch(// If the argument looks like a path (not a branch name), try to find a worktree there.if !create {let candidate = Path::new(branch);- let abs_path = if candidate.is_absolute() {- Some(candidate.to_path_buf())- } else if candidate.components().count() > 1 {- // Relative path with directory separators (e.g., "../repo.feature").- // Single-component names are ambiguous with branch names (already tried in Phase 2).- std::env::current_dir().ok().map(|cwd| cwd.join(candidate))- } else {- None- };+ // Absolute, or relative with directory separators (e.g. "../repo.feature");+ // a single-component name is ambiguous with a branch name (already tried in+ // Phase 2), so it stays branch-only. A relative path resolves against `-C`,+ // like git's own path arguments — see `resolve_input_path`.+ let looks_like_path = candidate.is_absolute() || candidate.components().count() > 1;+ let abs_path = looks_like_path.then(|| resolve_input_path(candidate));if let Some(abs_path) = abs_path&& let Some((path, wt_branch)) = repo.worktree_at_path(&abs_path)?{diff --git a/src/config/user/path.rs b/src/config/user/path.rsindex 4edfedcac..1c9ea6633 100644--- a/src/config/user/path.rs+++ b/src/config/user/path.rs@@ -9,6 +9,7 @@ use std::sync::OnceLock;use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};use crate::config::ConfigError;+use crate::git::resolve_input_path;/// Override for user config path, set via --config CLI flagstatic CONFIG_PATH: OnceLock<PathBuf> = OnceLock::new();@@ -33,15 +34,18 @@ pub fn is_config_path_explicit() -> bool {/// 1. CLI --config flag (set via `set_config_path`)/// 2. WORKTRUNK_CONFIG_PATH environment variable/// 3. Platform-specific default location (via `default_config_path`)+///+/// The first two are supplied by the user, so a relative one resolves against+/// `-C` (see [`resolve_input_path`]). The third is an absolute XDG location.pub fn config_path() -> Option<PathBuf> {// Priority 1: CLI --config flagif let Some(path) = CONFIG_PATH.get() {- return Some(path.clone());+ return Some(resolve_input_path(path));}// Priority 2: Environment variable (also used by tests for isolation)if let Ok(path) = std::env::var("WORKTRUNK_CONFIG_PATH") {- return Some(PathBuf::from(path));+ return Some(resolve_input_path(path));}// Priority 3: Platform-specific default location@@ -104,7 +108,7 @@ pub fn default_config_path() -> Option<PathBuf> {pub fn system_config_path() -> Option<PathBuf> {// Priority 1: Explicit environment variable overrideif let Ok(path) = std::env::var("WORKTRUNK_SYSTEM_CONFIG_PATH") {- let path = PathBuf::from(path);+ let path = resolve_input_path(path);if path.exists() {return Some(path);}@@ -131,7 +135,7 @@ pub fn system_config_path() -> Option<PathBuf> {/// path matches where the tool actually looks.pub fn default_system_config_path() -> Option<PathBuf> {if let Ok(path) = std::env::var("WORKTRUNK_SYSTEM_CONFIG_PATH") {- return Some(PathBuf::from(path));+ return Some(resolve_input_path(path));}system_config_dirs()diff --git a/src/git/mod.rs b/src/git/mod.rsindex 97db43339..4213eface 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -79,8 +79,8 @@ pub use remove::{pub use repository::sha_cache;pub use repository::{Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,- RefSnapshot, Repository, ResolvedWorktree, TempIndex, WorkingTree, select_comparison_base,- set_base_path,+ RefSnapshot, Repository, ResolvedWorktree, TempIndex, WorkingTree, resolve_input_path,+ select_comparison_base, set_base_path,};pub use url::parse_owner_repo;pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4d7d81d2f..58a224083 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -462,6 +462,14 @@ pub(super) static WORKTRUNK_USER_CONFIG_PRELOAD: OnceLock<UserConfig> = OnceLock////// This should be called once at program startup from main()./// If not called, defaults to "." (current directory).+///+/// `-C` sets this path without chdir'ing the process, so it is the base for the+/// two things git gets from its own chdir: the repository [`Repository::current`]+/// discovers, and every path the user supplies, which resolves through+/// [`resolve_input_path`]. The process cwd answers a different question — where+/// the user's shell physically is (the `cd` target after a switch, the+/// cwd-removed recovery check) — so `std::env::current_dir()` substitutes for+/// neither.pub fn set_base_path(path: PathBuf) {BASE_PATH.set(path).ok();}@@ -471,6 +479,34 @@ fn base_path() -> &'static PathBuf {BASE_PATH.get().unwrap_or(&DEFAULT_BASE_PATH)}+/// Resolve a path the user supplied, against the directory wt was pointed at.+///+/// Git resolves the paths in its command line against its own `-C`, because it+/// chdir's there first. wt's `-C` sets [`set_base_path`] instead, so the same+/// semantics come from joining onto that path. An absolute path passes through,+/// as does every path when `-C` was not given — the process cwd already resolves+/// those, and joining `.` onto them would surface as a stray `./` in output.+///+/// This is the one resolution point for those paths, so they cannot drift+/// apart: worktree path arguments (`wt switch ../repo.feature`), `--config`,+/// `WORKTRUNK_CONFIG_PATH`, `WORKTRUNK_SYSTEM_CONFIG_PATH`, and the trace file+/// of `wt config state logs profile`. The rule is "the user named a file for wt+/// to open" — three neighbours look similar and are deliberately outside it:+///+/// - Paths wt derives itself (a worktree root from `git worktree list`, an XDG+/// config directory) are already absolute.+/// - `WORKTRUNK_PROJECT_CONFIG_PATH` resolves from the worktree root, its+/// documented base, because the project config is per-worktree.+/// - `WORKTRUNK_BIN` and `XDG_CONFIG_DIRS` are never opened by wt: the first is+/// expanded by the generated shell wrapper, and the XDG spec already requires+/// the second to be absolute.+pub fn resolve_input_path(path: impl AsRef<Path>) -> PathBuf {+ match BASE_PATH.get() {+ Some(base) => base.join(path),+ None => path.as_ref().to_path_buf(),+ }+}+/// Repository state for git operations.////// Represents the shared state of a git repository (the `.git` directory).diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex a174c0fb5..80c2d1f88 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -3726,6 +3726,41 @@ approved-commands = ["npm install", "npm test"]assert!(approvals.contains("npm test"));}+/// A relative `--config` resolves against `-C`, the way git resolves the path+/// options in its own command line.+///+/// Run from outside the repo, so the process cwd and the `-C` directory+/// disagree: the file is only reachable from the latter.+#[rstest]+fn test_explicit_config_path_honors_directory_flag(repo: TestRepo) {+ fs::write(+ repo.root_path().join("side-config.toml"),+ "[list]\nfull = true\n",+ )+ .unwrap();+ let outside = repo.root_path().parent().unwrap().to_path_buf();+ let root = repo.root_path().to_string_lossy().to_string();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args([+ "-C",+ &root,+ "--config",+ "side-config.toml",+ "config",+ "show",+ ])+ .current_dir(&outside);+ let output = cmd.output().unwrap();++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("full = true"),+ "config show should report the config named relative to -C:\n{stdout}"+ );+}+/// Test that explicitly specified --config path that doesn't exist shows a warning#[rstest]fn test_explicit_config_path_not_found_shows_warning(repo: TestRepo) {diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 6d197cd05..714a24eee 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -567,6 +567,40 @@ fn test_logs_profile_from_file(repo: TestRepo) {assert!(stdout.contains("PERFORMANCE PROFILE"), "stdout: {stdout}");}+/// A relative trace path resolves against `-C`, the way git resolves the path+/// arguments in its own command line.+///+/// Run from outside the repo, so the process cwd and the `-C` directory+/// disagree: the trace is only reachable from the latter.+#[rstest]+fn test_logs_profile_from_file_honors_directory_flag(repo: TestRepo) {+ std::fs::write(repo.root_path().join("captured.log"), PROFILE_FIXTURE_TRACE).unwrap();+ let outside = repo.root_path().parent().unwrap().to_path_buf();+ let root = repo.root_path().to_string_lossy().to_string();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ cmd.args([+ "-C",+ &root,+ "config",+ "state",+ "logs",+ "profile",+ "captured.log",+ ]);+ cmd.current_dir(&outside);+ let output = cmd.output().unwrap();++ assert!(+ output.status.success(),+ "profile should read the trace named relative to -C: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("PERFORMANCE PROFILE"), "stdout: {stdout}");+}+/// A missing path argument fails, naming the file it could not read.#[rstest]fn test_logs_profile_file_missing(repo: TestRepo) {diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex cc0046fb2..2afd9c390 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -2545,13 +2545,14 @@ fn test_remove_detached_worktree_by_path(mut repo: TestRepo) {}/// Verify that detached worktrees can be removed by relative path.-/// This tests resolve_worktree_arg's CWD-relative path resolution.+/// This tests `resolve_worktree_arg`'s path resolution, which here runs from a+/// cwd inside the repo.#[rstest]fn test_remove_detached_worktree_by_relative_path(mut repo: TestRepo) {repo.add_worktree("feature-detached");repo.detach_head_in_worktree("feature-detached");- // From the main worktree (repo/), the relative path resolves against CWD+ // From the main worktree (repo/), the detached worktree is at ../repo.feature-detachedlet relative_path = "../repo.feature-detached";assert_cmd_snapshot!(make_snapshot_cmd(&repo,@@ -2561,6 +2562,46 @@ fn test_remove_detached_worktree_by_relative_path(mut repo: TestRepo) {));}+/// A relative path resolves against `-C`, not the process cwd — git's own rule+/// for path arguments under `-C`.+///+/// The test above reaches the worktree from a cwd inside the repo, the route+/// that works under either rule. Running from outside the repo is what tells+/// the two resolution bases apart: `../repo.feature-detached` names the+/// worktree only when it is resolved from the `-C` directory.+#[rstest]+fn test_remove_detached_worktree_by_relative_path_honors_directory_flag(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature-detached");+ repo.detach_head_in_worktree("feature-detached");++ let outside = repo.root_path().parent().unwrap().to_path_buf();+ let root = repo.root_path().to_string_lossy().to_string();+ let output = repo+ .wt_command()+ .current_dir(&outside)+ .args([+ "-C",+ &root,+ "remove",+ "../repo.feature-detached",+ "--foreground",+ "--yes",+ ])+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "remove should resolve the relative path against -C:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ !worktree_path.exists(),+ "the worktree the path names relative to -C should be gone"+ );+}+/// Test that resolve_worktree("@") works when the worktree is accessed via a symlink.////// This tests the path normalization fix where:diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rsindex 50b5e5ad1..82096dce6 100644--- a/tests/integration_tests/statusline.rs+++ b/tests/integration_tests/statusline.rs@@ -136,6 +136,112 @@ fn test_statusline_commits_ahead(mut repo: TestRepo) {assert_snapshot!(output, @"[0m feature [2m↑[22m [32m↑2[0m ^[32m+2[0m");}+/// `-C` selects the worktree, not the process cwd.+///+/// Every other test here sets the child's cwd, which reaches the worktree by a+/// different route: `-C` sets wt's discovery path without chdir'ing, so a+/// statusline built from `std::env::current_dir()` would describe the cwd's+/// worktree (`main`) and pass those tests while ignoring the flag.+#[rstest]+fn test_statusline_directory_flag(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // cwd is the main worktree; only `-C` points at `feature`+ let output = run_statusline_from_dir(+ &repo,+ &["-C", feature_path.to_str().unwrap()],+ None,+ repo.root_path(),+ );+ assert_snapshot!(output, @"[0m feature [2m_[22m");+}++/// With no stdin JSON, claude-code mode falls back to the same worktree the+/// table format uses, so it honours `-C` too. A directory on stdin still wins:+/// it names the session's directory rather than the one wt was pointed at.+#[rstest]+fn test_statusline_claude_code_directory_flag(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ let output = run_statusline_from_dir(+ &repo,+ &["--format=claude-code", "-C", feature_path.to_str().unwrap()],+ None,+ repo.root_path(),+ );+ claude_code_snapshot_settings().bind(|| {+ assert_snapshot!(output, @"[0m [PATH].feature [2m_[22m");+ });++ // stdin's directory outranks `-C`+ let json = format!(+ r#"{{"workspace": {{"current_dir": "{}"}}}}"#,+ escape_path_for_json(repo.root_path())+ );+ let output = run_statusline_from_dir(+ &repo,+ &["--format=claude-code", "-C", feature_path.to_str().unwrap()],+ Some(&json),+ repo.root_path(),+ );+ claude_code_snapshot_settings().bind(|| {+ assert_snapshot!(output, @"[0m [PATH] main [2m^[22m[2m|[22m");+ });+}++/// A stdin directory in a *different* repository than the one wt discovered.+///+/// The worktree comes from stdin while `list_worktrees` comes from the+/// discovered repo, so the stdin directory matches none of them and only its+/// branch can be reported. That split is the known limit of taking the+/// directory from stdin: everything repo-wide still comes from wt's own+/// discovery path.+#[rstest]+fn test_statusline_claude_code_foreign_repo_on_stdin(repo: TestRepo) {+ let foreign = repo.root_path().join("foreign");+ std::fs::create_dir(&foreign).unwrap();+ repo.git_command()+ .args(["init", "--initial-branch=elsewhere"])+ .current_dir(&foreign)+ .run()+ .unwrap();+ repo.git_command()+ .args(["commit", "-m", "init", "--allow-empty"])+ .current_dir(&foreign)+ .run()+ .unwrap();++ let json = format!(+ r#"{{"workspace": {{"current_dir": "{}"}}}}"#,+ escape_path_for_json(&foreign)+ );+ let output = run_statusline(&repo, &["--format=claude-code"], Some(&json));+ let mut settings = claude_code_snapshot_settings();+ // A nested directory renders home-relative, which the platform-specific+ // `[PATH]` filters don't reach; the branch is this test's subject.+ settings.add_filter(r"[^ ]*foreign", "[FOREIGN]");+ settings.bind(|| {+ assert_snapshot!(output, @"[0m [FOREIGN] elsewhere");+ });+}++#[rstest]+fn test_statusline_json_directory_flag(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // cwd is the main worktree; only `-C` points at `feature`+ let output = run_statusline_from_dir(+ &repo,+ &["--format=json", "-C", feature_path.to_str().unwrap()],+ None,+ repo.root_path(),+ );+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");+ let items = parsed.as_array().expect("should be an array");+ assert_eq!(items.len(), 1, "should describe just the -C worktree");+ assert_eq!(items[0]["branch"], "feature");+}+#[rstest]fn test_statusline_does_not_run_repo_wide_ahead_behind_scan(repo: TestRepo) {for i in 0..12 {diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 8f680b1e2..29de12a15 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1704,7 +1704,8 @@ fn test_switch_worktree_by_symlinked_path(mut repo: TestRepo) {}/// Switch to a detached worktree by relative path (#1661).-/// Relative paths with directory separators (e.g., "../repo.feature") are resolved against CWD.+/// Relative paths with directory separators (e.g., "../repo.feature") resolve+/// against the directory wt was pointed at, which here is the process cwd.#[rstest]fn test_switch_detached_worktree_by_relative_path(mut repo: TestRepo) {repo.add_worktree("feature-detached");@@ -1720,6 +1721,40 @@ fn test_switch_detached_worktree_by_relative_path(mut repo: TestRepo) {);}+/// A relative path resolves against `-C`, not the process cwd — git's own rule+/// for path arguments under `-C`.+///+/// The test above reaches the worktree from a cwd inside the repo, the route+/// that works under either rule. Running from outside the repo is what tells+/// the two resolution bases apart: `../repo.feature-detached` names the+/// worktree only when it is resolved from the `-C` directory.+#[rstest]+fn test_switch_detached_worktree_by_relative_path_honors_directory_flag(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature-detached");+ repo.detach_head_in_worktree("feature-detached");++ let outside = repo.root_path().parent().unwrap().to_path_buf();+ let root = repo.root_path().to_string_lossy().to_string();+ let (cd_path, exec_path, _guard) = directive_files();+ let mut cmd = repo.wt_command();+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ cmd.current_dir(&outside)+ .args(["-C", &root, "switch", "../repo.feature-detached"]);++ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "switch should resolve the relative path against -C:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(+ fs::read_to_string(&cd_path).unwrap().trim(),+ worktree_path.to_string_lossy(),+ "switch should land in the worktree the path names relative to -C"+ );+}+////// When the main worktree (repo root) has been switched to a feature branch via/// `git checkout feature`, `wt switch main` should error with a helpful message