Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Revert "feat: add jj (Jujutsu) support alongside git"
Maximilian Roos7ed8cdb421ee
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.mdindex b00bbf769..17770f604 100644--- a/.claude/skills/writing-user-outputs/SKILL.md+++ b/.claude/skills/writing-user-outputs/SKILL.md@@ -156,27 +156,6 @@ information, not restate what's already said."Committing with default message... (3 files, +45, -12)"```-**VCS-neutral messaging:** Don't mention specific VCS backends (git, jj) in-messages unless the context is already VCS-specific. Generic messages should work-for any backend. Only name a backend when the user is already in that backend's-context (e.g., a jj-specific limitation) or when contrasting backends.--```rust-// GOOD - generic, works for any VCS-"Not in a repository"-"Branch not found"-"Uncommitted changes"--// BAD - unnecessarily names backends the user may not be using-"Not in a git or jj repository"-"Not a git repository" // (unless in git-specific code path)--// OK - already in jj context, naming the limitation-"--show-prompt is not yet supported for jj squash"-// OK - command only works in git, telling user why-"`wt {command}` is not yet supported for jj repositories"-```-**Two types of parenthesized content with different styling:**1. **Stats parentheses → Gray** (`[90m` bright-black): Supplementary numericaldiff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex 44b2e37d3..63cf8efcf 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -73,16 +73,10 @@ jobs:packages: zsh fishversion: 1.0- - name: Install jj (Jujutsu) - Linux- if: runner.os == 'Linux'- uses: baptiste0928/cargo-install@v3- with:- crate: jj-cli-- - name: Install shells and jj (Jujutsu) - macOS+ - name: Install shells (fish) - macOSif: runner.os == 'macOS'run: |- brew install fish jj+ brew install fish# bash and zsh are pre-installed on macOS- name: Install nushell@@ -251,11 +245,6 @@ jobs:packages: zsh fishversion: 1.0- - name: Install jj (Jujutsu)- uses: baptiste0928/cargo-install@v3- with:- crate: jj-cli-- name: Install nushelluses: hustcer/setup-nu@v3with:diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 18bf2cc6f..f87d45cb3 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -76,9 +76,7 @@ repos:# src/config/{test,expansion,mod}.rs: TestRepo test fixtures use git init directly# src/config/user/tests.rs: TestRepo test fixtures use git init directly# src/styling/mod.rs: terminal width detection probes should be silent/quick- # src/workspace/git.rs: #[cfg(test)] fixtures use git init/commit directly- # src/commands/command_executor.rs: #[cfg(test)] fixtures use git init/commit directly- exclude: '^(src/shell_exec\.rs|src/commands/(select/|command_executor\.rs)|src/config/(test|expansion|mod)\.rs|src/config/user/tests\.rs|src/styling/mod\.rs|src/workspace/git\.rs|tests/|benches/)'+ exclude: '^(src/shell_exec\.rs|src/commands/select/|src/config/(test|expansion|mod)\.rs|src/config/user/tests\.rs|src/styling/mod\.rs|tests/|benches/)'ci:# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.diff --git a/CLAUDE.md b/CLAUDE.mdindex 1cb72d4b4..5c5639642 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -279,10 +279,6 @@ Real repo benchmarks clone rust-lang/rust (~2-5 min first run, cached thereafterUse `wt list --format=json` for structured data access. See `wt list --help` for complete field documentation, status variants, and query examples.-## VCS Support--Worktrunk supports **git and jj** (Jujutsu). The `Workspace` trait abstracts over both, but don't design for hypothetical third backends — keep trait signatures as simple as the two real implementations require. For example, if both git and jj implementations are infallible, the trait method should return a plain value, not `Result`.-## Worktree Model- Worktrees are **addressed by branch name**, not by filesystem path.diff --git a/Cargo.toml b/Cargo.tomlindex c1a1d2173..c3ce74b60 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -35,8 +35,8 @@ normal = ["which"]# This is optional to avoid C compilation issues on some platformsdefault = ["syntax-highlighting"]syntax-highlighting = ["dep:tree-sitter", "dep:tree-sitter-bash", "dep:tree-sitter-highlight"]-# Enable shell/PTY integration tests (requires bash, zsh, fish, jj installed on system)-# Includes: shell wrapper tests, PTY-based approval prompts, TUI select, progressive rendering, jj tests+# Enable shell/PTY integration tests (requires bash, zsh, fish installed on system)+# Includes: shell wrapper tests, PTY-based approval prompts, TUI select, progressive rendering# These tests can cause nextest to suspend due to terminal foreground pgrp issues.# When enabled, run with NEXTEST_NO_INPUT_HANDLER=1 to avoid suspension.# See CLAUDE.md "Nextest Terminal Suspension" section for details.diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 98d1d8ea3..4a9d27949 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -210,7 +210,7 @@ pub fn approve_hooks_filtered(return Ok(true);}- let project_config = match ctx.workspace.load_project_config()? {+ let project_config = match ctx.repo.load_project_config()? {Some(cfg) => cfg,None => return Ok(true), // No project config = no commands to approve};@@ -230,6 +230,6 @@ pub fn approve_hooks_filtered(return Ok(true);}- let project_id = ctx.workspace.project_identifier()?;+ let project_id = ctx.repo.project_identifier()?;approve_command_batch(&commands, &project_id, ctx.config, ctx.yes, false)}diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 0dc5e755d..7df8066d8 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -4,7 +4,6 @@ use worktrunk::HookType;use worktrunk::config::{Command, CommandConfig, UserConfig, expand_template};use worktrunk::git::Repository;use worktrunk::path::to_posix_path;-use worktrunk::workspace::{Workspace, build_worktree_map};use super::hook_filter::HookSource;@@ -15,9 +14,9 @@ pub struct PreparedCommand {pub context_json: String,}-#[derive(Clone, Copy)]+#[derive(Clone, Copy, Debug)]pub struct CommandContext<'a> {- pub workspace: &'a dyn Workspace,+ pub repo: &'a Repository,pub config: &'a UserConfig,/// Current branch name, if on a branch (None in detached HEAD state).pub branch: Option<&'a str>,@@ -25,27 +24,16 @@ pub struct CommandContext<'a> {pub yes: bool,}-impl std::fmt::Debug for CommandContext<'_> {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("CommandContext")- .field("workspace_kind", &self.workspace.kind())- .field("branch", &self.branch)- .field("worktree_path", &self.worktree_path)- .field("yes", &self.yes)- .finish()- }-}-impl<'a> CommandContext<'a> {pub fn new(- workspace: &'a dyn Workspace,+ repo: &'a Repository,config: &'a UserConfig,branch: Option<&'a str>,worktree_path: &'a Path,yes: bool,) -> Self {Self {- workspace,+ repo,config,branch,worktree_path,@@ -53,11 +41,6 @@ impl<'a> CommandContext<'a> {}}- /// Downcast to git Repository. Returns None for jj workspaces.- pub fn repo(&self) -> Option<&Repository> {- self.workspace.as_any().downcast_ref::<Repository>()- }-/// Get branch name, using "HEAD" as fallback for detached HEAD state.pub fn branch_or_head(&self) -> &str {self.branch.unwrap_or("HEAD")@@ -68,7 +51,7 @@ impl<'a> CommandContext<'a> {/// Uses the remote URL if available, otherwise the canonical repository path./// Returns None only if the path is not valid UTF-8.pub fn project_id(&self) -> Option<String> {- self.workspace.project_identifier().ok()+ self.repo.project_identifier().ok()}/// Get the commit generation config, merging project-specific settings.@@ -85,7 +68,7 @@ pub fn build_hook_context(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],) -> HashMap<String, String> {- let repo_root = ctx.workspace.root_path().unwrap_or_default();+ let repo_root = ctx.repo.repo_path();let repo_name = repo_root.file_name().and_then(|n| n.to_str())@@ -117,38 +100,36 @@ pub fn build_hook_context(map.insert("worktree".into(), worktree);// Default branch- if let Some(default_branch) = ctx.workspace.default_branch_name() {+ if let Some(default_branch) = ctx.repo.default_branch() {map.insert("default_branch".into(), default_branch);}// Primary worktree path (where established files live)- if let Ok(Some(path)) = ctx.workspace.default_workspace_path() {+ if let Ok(Some(path)) = ctx.repo.primary_worktree() {let path_str = to_posix_path(&path.to_string_lossy());map.insert("primary_worktree_path".into(), path_str.clone());// Deprecated aliasmap.insert("main_worktree_path".into(), path_str);}- // Git-specific context (commit SHA, remote, upstream)- if let Some(repo) = ctx.repo() {- if let Ok(commit) = repo.run_command(&["rev-parse", "HEAD"]) {- let commit = commit.trim();- map.insert("commit".into(), commit.into());- if commit.len() >= 7 {- map.insert("short_commit".into(), commit[..7].into());- }+ if let Ok(commit) = ctx.repo.run_command(&["rev-parse", "HEAD"]) {+ let commit = commit.trim();+ map.insert("commit".into(), commit.into());+ if commit.len() >= 7 {+ map.insert("short_commit".into(), commit[..7].into());}+ }- if let Ok(remote) = repo.primary_remote() {- map.insert("remote".into(), remote.to_string());- if let Some(url) = repo.remote_url(&remote) {- map.insert("remote_url".into(), url);- }- if let Some(branch) = ctx.branch- && let Ok(Some(upstream)) = repo.branch(branch).upstream()- {- map.insert("upstream".into(), upstream);- }+ if let Ok(remote) = ctx.repo.primary_remote() {+ map.insert("remote".into(), remote.to_string());+ // Add remote URL for conditional hook execution (e.g., GitLab vs GitHub)+ if let Some(url) = ctx.repo.remote_url(&remote) {+ map.insert("remote_url".into(), url);+ }+ if let Some(branch) = ctx.branch+ && let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream()+ {+ map.insert("upstream".into(), upstream);}}@@ -176,7 +157,6 @@ fn expand_commands(}let base_context = build_hook_context(ctx, extra_vars);- let worktree_map = build_worktree_map(ctx.workspace);// Convert to &str references for expand_templatelet vars: HashMap<&str, &str> = base_context@@ -191,16 +171,14 @@ fn expand_commands(Some(name) => format!("{}:{}", source, name),None => format!("{} {} hook", source, hook_type),};- let expanded_str =- expand_template(&cmd.template, &vars, true, &worktree_map, &template_name).map_err(- |e| {- anyhow::anyhow!(- "Failed to expand command template '{}': {}",- cmd.template,- e- )- },- )?;+ let expanded_str = expand_template(&cmd.template, &vars, true, ctx.repo, &template_name)+ .map_err(|e| {+ anyhow::anyhow!(+ "Failed to expand command template '{}': {}",+ cmd.template,+ e+ )+ })?;// Build per-command JSON with hook_type and hook_namelet mut cmd_context = base_context.clone();@@ -251,248 +229,3 @@ pub fn prepare_commands(}).collect())}--#[cfg(test)]-mod tests {- use super::*;- use worktrunk::config::UserConfig;- use worktrunk::git::Repository;-- /// Helper to init a git repo and return (temp_dir, repo_path).- fn init_test_repo() -> (tempfile::TempDir, std::path::PathBuf) {- let temp = tempfile::tempdir().unwrap();- let repo_path = temp.path().join("repo");- std::fs::create_dir(&repo_path).unwrap();- let out = std::process::Command::new("git")- .args(["init", "-b", "main"])- .current_dir(&repo_path)- .output()- .unwrap();- assert!(out.status.success());- let out = std::process::Command::new("git")- .args(["commit", "--allow-empty", "-m", "init"])- .current_dir(&repo_path)- .env("GIT_AUTHOR_NAME", "Test")- .env("GIT_AUTHOR_EMAIL", "[email protected]")- .env("GIT_COMMITTER_NAME", "Test")- .env("GIT_COMMITTER_EMAIL", "[email protected]")- .output()- .unwrap();- assert!(out.status.success());- (temp, repo_path)- }-- #[test]- fn test_command_context_debug_format() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let debug = format!("{ctx:?}");- assert!(debug.contains("CommandContext"));- assert!(debug.contains("Git"));- }-- #[test]- fn test_command_context_repo_downcast() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- // repo() should succeed for git repositories- assert!(ctx.repo().is_some());- }-- #[test]- fn test_command_context_branch_or_head() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();-- // With a branch set- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- assert_eq!(ctx.branch_or_head(), "main");-- // Without a branch (detached HEAD)- let ctx = CommandContext::new(&repo, &config, None, &repo_path, false);- assert_eq!(ctx.branch_or_head(), "HEAD");- }-- #[test]- fn test_command_context_project_id() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- // project_id should return Some (path-based, since no remote)- assert!(ctx.project_id().is_some());- }-- #[test]- fn test_command_context_commit_generation() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- // commit_generation returns default config (no command set)- let cg = ctx.commit_generation();- assert!(cg.command.is_none());- }-- #[test]- fn test_build_hook_context() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let context = build_hook_context(&ctx, &[("extra_key", "extra_val")]);- assert_eq!(context.get("branch").map(|s| s.as_str()), Some("main"));- assert_eq!(context.get("repo").map(|s| s.as_str()), Some("repo"));- assert!(context.contains_key("worktree_path"));- assert!(context.contains_key("repo_path"));- assert_eq!(- context.get("extra_key").map(|s| s.as_str()),- Some("extra_val")- );- }-- #[test]- fn test_build_hook_context_detached_head() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- // Detached HEAD: branch is None, branch_or_head returns "HEAD"- let ctx = CommandContext::new(&repo, &config, None, &repo_path, false);- let context = build_hook_context(&ctx, &[]);- assert_eq!(context.get("branch").map(|s| s.as_str()), Some("HEAD"));- }-- #[test]- fn test_build_hook_context_includes_git_specifics() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let context = build_hook_context(&ctx, &[]);- // Git-specific: commit and short_commit should be present- assert!(context.contains_key("commit"));- assert!(context.contains_key("short_commit"));- // Deprecated aliases should still be present- assert!(context.contains_key("main_worktree"));- assert!(context.contains_key("repo_root"));- assert!(context.contains_key("worktree"));- }-- /// Deserialize a CommandConfig from a TOML string command.- fn make_command_config(toml_value: &str) -> worktrunk::config::CommandConfig {- #[derive(serde::Deserialize)]- struct W {- cmd: worktrunk::config::CommandConfig,- }- let toml_str = format!("cmd = {toml_value}");- toml::from_str::<W>(&toml_str).unwrap().cmd- }-- #[test]- fn test_prepare_commands_empty_template() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let cmd_config = make_command_config("\"\"");- // Empty template still counts as one command- let result = prepare_commands(- &cmd_config,- &ctx,- &[],- HookType::PreCommit,- HookSource::User,- )- .unwrap();- assert_eq!(result.len(), 1);- }-- #[test]- fn test_prepare_commands_single() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let cmd_config = make_command_config("\"echo hello\"");- let result = prepare_commands(- &cmd_config,- &ctx,- &[],- HookType::PreCommit,- HookSource::User,- )- .unwrap();- assert_eq!(result.len(), 1);- assert_eq!(result[0].expanded, "echo hello");- assert!(result[0].name.is_none());- // context_json should contain hook_type- assert!(result[0].context_json.contains("pre-commit"));- }-- #[test]- fn test_prepare_commands_with_template_vars() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let cmd_config = make_command_config("\"echo {{ branch }}\"");- let result = prepare_commands(- &cmd_config,- &ctx,- &[],- HookType::PostCreate,- HookSource::User,- )- .unwrap();- assert_eq!(result.len(), 1);- assert_eq!(result[0].expanded, "echo main");- }-- #[test]- fn test_prepare_commands_named() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let cmd_config = make_command_config("{ build = \"cargo build\", test = \"cargo test\" }");- let result = prepare_commands(- &cmd_config,- &ctx,- &[],- HookType::PreMerge,- HookSource::Project,- )- .unwrap();- assert_eq!(result.len(), 2);- assert_eq!(result[0].name.as_deref(), Some("build"));- assert_eq!(result[0].expanded, "cargo build");- assert_eq!(result[1].name.as_deref(), Some("test"));- assert_eq!(result[1].expanded, "cargo test");- // Named commands should have hook_name in JSON context- assert!(result[0].context_json.contains("hook_name"));- assert!(result[0].context_json.contains("build"));- }-- #[test]- fn test_prepare_commands_with_extra_vars() {- let (_temp, repo_path) = init_test_repo();- let repo = Repository::at(&repo_path).unwrap();- let config = UserConfig::default();- let ctx = CommandContext::new(&repo, &config, Some("main"), &repo_path, false);- let cmd_config = make_command_config("\"echo {{ target }}\"");- let result = prepare_commands(- &cmd_config,- &ctx,- &[("target", "develop")],- HookType::PreMerge,- HookSource::User,- )- .unwrap();- assert_eq!(result[0].expanded, "echo develop");- }-}diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 41906ed91..4c7028a9d 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -5,7 +5,6 @@ use worktrunk::config::CommitGenerationConfig;use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,};-use worktrunk::workspace::Workspace;use super::command_executor::CommandContext;use super::hooks::HookFailureStrategy;@@ -131,27 +130,7 @@ impl<'a> CommitGenerator<'a> {}self.emit_hint_if_needed();-- // Get staged diff data for commit message generation- let (diff, diff_stat) = wt- .repo()- .committable_diff_for_prompt(wt.root()?.as_path())?;- let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());- let repo_root = wt.root()?;- let repo_name = repo_root- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("repo");- let recent_commits = wt.repo().recent_subjects(None, 5);-- let input = crate::llm::CommitInput {- diff: &diff,- diff_stat: &diff_stat,- branch: ¤t_branch,- repo_name,- recent_commits: recent_commits.as_ref(),- };- let commit_message = crate::llm::generate_commit_message(&input, self.config)?;+ let commit_message = crate::llm::generate_commit_message(self.config)?;let formatted_message = self.format_message_for_display(&commit_message);eprintln!("{}", format_with_gutter(&formatted_message, None));@@ -176,7 +155,7 @@ impl<'a> CommitGenerator<'a> {/// Commit uncommitted changes with the shared commit pipeline.impl CommitOptions<'_> {pub fn commit(self) -> anyhow::Result<()> {- let project_config = self.ctx.workspace.load_project_config()?;+ let project_config = self.ctx.repo.load_project_config()?;let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_deref());let user_hooks_exist = user_hooks.pre_commit.is_some();let project_hooks_exist = project_config@@ -217,7 +196,7 @@ impl CommitOptions<'_> {}if self.warn_about_untracked && self.stage_mode == StageMode::All {- self.ctx.repo().unwrap().warn_if_auto_staging_untracked()?;+ self.ctx.repo.warn_if_auto_staging_untracked()?;}// Stage changes based on mode@@ -225,16 +204,14 @@ impl CommitOptions<'_> {StageMode::All => {// Stage everything: tracked modifications + untracked filesself.ctx- .repo()- .unwrap()+ .repo.run_command(&["add", "-A"]).context("Failed to stage changes")?;}StageMode::Tracked => {// Stage tracked modifications only (no untracked files)self.ctx- .repo()- .unwrap()+ .repo.run_command(&["add", "-u"]).context("Failed to stage tracked changes")?;}@@ -244,7 +221,7 @@ impl CommitOptions<'_> {}let effective_config = self.ctx.commit_generation();- let wt = self.ctx.repo().unwrap().current_worktree();+ let wt = self.ctx.repo.current_worktree();CommitGenerator::new(&effective_config).commit_staged_changes(&wt,true, // show_progressdiff --git a/src/commands/config/create.rs b/src/commands/config/create.rsindex cc08a59c0..ec3f5a023 100644--- a/src/commands/config/create.rs+++ b/src/commands/config/create.rs@@ -5,6 +5,7 @@use anyhow::Context;use color_print::cformat;use std::path::PathBuf;+use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;use worktrunk::styling::{eprintln, hint_message, info_message, success_message};@@ -42,8 +43,8 @@ pub(super) fn comment_out_config(content: &str) -> String {/// Handle the config create commandpub fn handle_config_create(project: bool) -> anyhow::Result<()> {if project {- let workspace = worktrunk::workspace::open_workspace()?;- let config_path = workspace.current_workspace_path()?.join(".config/wt.toml");+ let repo = Repository::current()?;+ let config_path = repo.current_worktree().root()?.join(".config/wt.toml");let user_config_exists = require_user_config_path().map(|p| p.exists()).unwrap_or(false);@@ -59,8 +60,8 @@ pub fn handle_config_create(project: bool) -> anyhow::Result<()> {true, // is_project)} else {- let project_config_exists = worktrunk::workspace::open_workspace()- .and_then(|ws| ws.current_workspace_path())+ let project_config_exists = Repository::current()+ .and_then(|repo| repo.current_worktree().root()).map(|root| root.join(".config/wt.toml").exists()).unwrap_or(false);create_config_file(diff --git a/src/commands/config/hints.rs b/src/commands/config/hints.rsindex 085c7e04d..d5f1e8bb0 100644--- a/src/commands/config/hints.rs+++ b/src/commands/config/hints.rs@@ -1,19 +1,14 @@//! Hint management commands.//!//! Commands for viewing and clearing shown hints.-//!-//! Hints are stored in git config — not yet supported for jj repositories.use color_print::cformat;+use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message, println, success_message};-use worktrunk::workspace::open_workspace;--use crate::commands::require_git_workspace;/// Handle the hints get command (list shown hints)pub fn handle_hints_get() -> anyhow::Result<()> {- let workspace = open_workspace()?;- let repo = require_git_workspace(&*workspace, "config hints")?;+ let repo = Repository::current()?;let hints = repo.list_shown_hints();if hints.is_empty() {@@ -29,8 +24,7 @@ pub fn handle_hints_get() -> anyhow::Result<()> {/// Handle the hints clear commandpub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {- let workspace = open_workspace()?;- let repo = require_git_workspace(&*workspace, "config hints")?;+ let repo = Repository::current()?;match name {Some(hint_name) => {diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 773907a9b..d71c5d5f2 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -20,7 +20,6 @@ use worktrunk::styling::{error_message, format_bash_with_gutter, format_heading, format_toml, format_with_gutter,hint_message, info_message, success_message, warning_message,};-use worktrunk::workspace::{Workspace, open_workspace};use super::state::require_user_config_path;use crate::cli::version_str;@@ -32,12 +31,6 @@ use crate::output;/// Handle the config show commandpub fn handle_config_show(full: bool) -> anyhow::Result<()> {- // Open workspace once and try downcast for git-specific sections- let workspace = open_workspace().ok();- let repo = workspace- .as_ref()- .and_then(|ws| ws.as_any().downcast_ref::<Repository>());-// Build the complete output as a stringlet mut show_output = String::new();@@ -45,8 +38,8 @@ pub fn handle_config_show(full: bool) -> anyhow::Result<()> {render_user_config(&mut show_output)?;show_output.push('\n');- // Render project config if in a repository- render_project_config(&mut show_output, workspace.as_deref(), repo)?;+ // Render project config if in a git repository+ render_project_config(&mut show_output)?;show_output.push('\n');// Render shell integration status@@ -59,7 +52,7 @@ pub fn handle_config_show(full: bool) -> anyhow::Result<()> {// Run full diagnostic checks if requested (includes slow network calls)if full {show_output.push('\n');- render_diagnostics(&mut show_output, workspace.as_deref(), repo)?;+ render_diagnostics(&mut show_output)?;}// Render runtime info at the bottom (version, binary name, shell integration status)@@ -266,55 +259,43 @@ fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {}/// Run full diagnostic checks (CI tools, commit generation) and render to buffer-fn render_diagnostics(- out: &mut String,- workspace: Option<&dyn Workspace>,- repo: Option<&Repository>,-) -> anyhow::Result<()> {+fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;// Check CI tool based on detected platform (with config override support)- // CI detection requires git (gh/glab are git-platform tools)- if let Some(repo) = repo {- let project_config = workspace.and_then(|ws| ws.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, None);-- match platform {- Some(CiPlatform::GitHub) => {- let ci_tools = CiToolsStatus::detect(None);- render_ci_tool_status(- out,- "gh",- "GitHub",- ci_tools.gh_installed,- ci_tools.gh_authenticated,- )?;- }- Some(CiPlatform::GitLab) => {- let ci_tools = CiToolsStatus::detect(None);- render_ci_tool_status(- out,- "glab",- "GitLab",- ci_tools.glab_installed,- ci_tools.glab_authenticated,- )?;- }- None => {- writeln!(- out,- "{}",- hint_message("CI status requires GitHub or GitLab remote")- )?;- }+ 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, None);++ match platform {+ Some(CiPlatform::GitHub) => {+ let ci_tools = CiToolsStatus::detect(None);+ render_ci_tool_status(+ out,+ "gh",+ "GitHub",+ ci_tools.gh_installed,+ ci_tools.gh_authenticated,+ )?;+ }+ Some(CiPlatform::GitLab) => {+ let ci_tools = CiToolsStatus::detect(None);+ render_ci_tool_status(+ out,+ "glab",+ "GitLab",+ ci_tools.glab_installed,+ ci_tools.glab_authenticated,+ )?;+ }+ None => {+ writeln!(+ out,+ "{}",+ hint_message("CI status requires GitHub or GitLab remote")+ )?;}- } else {- writeln!(- out,- "{}",- hint_message("CI status requires a git repository")- )?;}// Check for newer version on GitHub@@ -322,7 +303,9 @@ fn render_diagnostics(// Test commit generation - use effective config for current projectlet config = UserConfig::load()?;- let project_id = workspace.and_then(|ws| ws.project_identifier().ok());+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());let commit_config = config.commit_generation(project_id.as_deref());if !commit_config.is_configured() {@@ -451,30 +434,36 @@ pub(super) fn warn_unknown_keys<C: worktrunk::config::WorktrunkConfig>(out}-fn render_project_config(- out: &mut String,- workspace: Option<&dyn Workspace>,- repo: Option<&Repository>,-) -> anyhow::Result<()> {- // Try to get workspace root for project config path- let repo_root = if let Some(repo) = repo {- repo.current_worktree().root().ok()- } else {- workspace.and_then(|ws| ws.root_path().ok())+fn render_project_config(out: &mut String) -> anyhow::Result<()> {+ // Try to get current repository root+ let repo = match Repository::current() {+ Ok(repo) => repo,+ Err(_) => {+ writeln!(+ out,+ "{}",+ cformat!(+ "<dim>{}</>",+ format_heading("PROJECT CONFIG", Some("Not in a git repository"))+ )+ )?;+ return Ok(());+ }};-- let Some(repo_root) = repo_root else {- writeln!(- out,- "{}",- cformat!(- "<dim>{}</>",- format_heading("PROJECT CONFIG", Some("Not in a repository"))- )- )?;- return Ok(());+ let repo_root = match repo.current_worktree().root() {+ Ok(root) => root,+ Err(_) => {+ writeln!(+ out,+ "{}",+ cformat!(+ "<dim>{}</>",+ format_heading("PROJECT CONFIG", Some("Not in a git repository"))+ )+ )?;+ return Ok(());+ }};-let config_path = repo_root.join(".config").join("wt.toml");writeln!(@@ -501,14 +490,14 @@ fn render_project_config(}// Check for deprecations with show_brief_warning=false (silent mode)- // Only show in main worktree (where .git is a directory) — git only+ // Only show in main worktree (where .git is a directory)let is_main_worktree = repo_root.join(".git").is_dir();let has_deprecations = if let Ok(Some(info)) = worktrunk::config::check_and_migrate(&config_path,&contents,is_main_worktree,"Project config",- repo,+ Some(&repo),false, // silent mode - we'll format the output ourselves) {// Add deprecation details to the output bufferdiff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 2747cfbe0..71a01d0bf 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -4,7 +4,7 @@//! previous branch, CI status, markers, and logs.use std::fmt::Write as _;-use std::path::{Path, PathBuf};+use std::path::PathBuf;use color_print::cformat;use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};@@ -14,11 +14,9 @@ use worktrunk::styling::{eprintln, format_heading, format_with_gutter, info_message, println, success_message,warning_message,};-use worktrunk::workspace::{Workspace, open_workspace};use crate::cli::OutputFormat;use crate::commands::process::HookLog;-use crate::commands::require_git_workspace;use worktrunk::utils::get_now;use super::super::list::ci_status::{CachedCiStatus, CiBranchName};@@ -75,13 +73,15 @@ pub fn require_user_config_path() -> anyhow::Result<PathBuf> {// ==================== Log Management ====================/// Clear all log files from the wt-logs directory-fn clear_logs(log_dir: &Path) -> anyhow::Result<usize> {+fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {+ let log_dir = repo.wt_logs_dir();+if !log_dir.exists() {return Ok(0);}let mut cleared = 0;- for entry in std::fs::read_dir(log_dir)? {+ for entry in std::fs::read_dir(&log_dir)? {let entry = entry?;let path = entry.path();if path.is_file() && path.extension().is_some_and(|ext| ext == "log") {@@ -91,16 +91,17 @@ fn clear_logs(log_dir: &Path) -> anyhow::Result<usize> {}// Remove the directory if empty- if std::fs::read_dir(log_dir)?.next().is_none() {- let _ = std::fs::remove_dir(log_dir);+ if std::fs::read_dir(&log_dir)?.next().is_none() {+ let _ = std::fs::remove_dir(&log_dir);}Ok(cleared)}/// Render the LOG FILES section (heading + table or "(none)") into the output buffer-pub(super) fn render_log_files(out: &mut String, log_dir: &Path) -> anyhow::Result<()> {- let log_dir_display = format_path_for_display(log_dir);+pub(super) fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {+ let log_dir = repo.wt_logs_dir();+ let log_dir_display = format_path_for_display(&log_dir);writeln!(out,@@ -113,7 +114,7 @@ pub(super) fn render_log_files(out: &mut String, log_dir: &Path) -> anyhow::Resureturn Ok(());}- let mut entries: Vec<_> = std::fs::read_dir(log_dir)?+ let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?.filter_map(|e| e.ok()).filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log")).collect();@@ -175,14 +176,13 @@ pub(super) fn render_log_files(out: &mut String, log_dir: &Path) -> anyhow::Resu/// - `source:hook-type:name` for hook commands (e.g., `user:post-start:server`)/// - `internal:op` for internal operations (e.g., `internal:remove`)pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::Result<()> {- let workspace = open_workspace()?;- let log_dir = workspace.wt_logs_dir();+ let repo = Repository::current()?;match hook {None => {// No hook specified, show all log files (existing behavior)let mut out = String::new();- render_log_files(&mut out, &log_dir)?;+ render_log_files(&mut out, &repo)?;// Display through pager (fall back to stderr if pager unavailable)if show_help_in_pager(&out, true).is_err() {@@ -190,15 +190,14 @@ pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::}}Some(hook_spec) => {- // Get the branch name (workspace name for jj)- let cwd = std::env::current_dir()?;+ // Get the branch namelet branch = match branch {Some(b) => b,- None => workspace- .current_name(&cwd)?- .ok_or_else(|| anyhow::anyhow!("Cannot determine current workspace name"))?,+ None => repo.require_current_branch("get log for current branch")?,};+ let log_dir = repo.wt_logs_dir();+// Parse the hook spec using HookLoglet hook_log = HookLog::parse(&hook_spec).map_err(|e| anyhow::anyhow!("{}", e))?;@@ -260,79 +259,74 @@ pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {use super::super::list::ci_status::PrStatus;- let workspace = open_workspace()?;+ let repo = Repository::current()?;match key {"default-branch" => {- let branch_name = workspace.default_branch_name().ok_or_else(|| {+ let branch_name = repo.default_branch().ok_or_else(|| {anyhow::anyhow!(cformat!("Cannot determine default branch. To configure, run <bold>wt config state default-branch set BRANCH</>"))})?;println!("{branch_name}");}- "previous-branch" => match workspace.switch_previous() {+ "previous-branch" => match repo.switch_previous() {Some(prev) => println!("{prev}"),None => println!(""),},- "marker" | "ci-status" => {- let repo = require_git_workspace(&*workspace, "config state get")?;-- if key == "marker" {- let branch_name = match branch {- Some(b) => b,- None => repo.require_current_branch("get marker for current branch")?,- };- match repo.branch_marker(&branch_name) {- Some(marker) => println!("{marker}"),- None => println!(""),- }- } else {- // ci-status- let branch_name = match branch {- Some(b) => b,- 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 branch- let head = repo- .run_command(&["rev-parse", &branch_name])- .map(|s| s.trim().to_string())- .unwrap_or_default();+ "marker" => {+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("get marker for current branch")?,+ };+ match repo.branch_marker(&branch_name) {+ Some(marker) => println!("{marker}"),+ None => println!(""),+ }+ }+ "ci-status" => {+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("get ci-status for current branch")?,+ };- if head.is_empty() {- return Err(worktrunk::git::GitError::BranchNotFound {- branch: branch_name,- show_create_hint: true,- }- .into());+ // 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 branch+ let head = repo+ .run_command(&["rev-parse", &branch_name])+ .map(|s| s.trim().to_string())+ .unwrap_or_default();++ if head.is_empty() {+ return Err(worktrunk::git::GitError::BranchNotFound {+ branch: branch_name,+ show_create_hint: true,}-- 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- });- let status_str: &'static str = ci_status.into();- println!("{status_str}");+ .into());}++ 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+ });+ let status_str: &'static str = ci_status.into();+ println!("{status_str}");}// TODO: Consider simplifying to just print the path and let users run `ls -al` themselves"logs" => {- let log_dir = workspace.wt_logs_dir();let mut out = String::new();- render_log_files(&mut out, &log_dir)?;+ render_log_files(&mut out, &repo)?;// Display through pager (fall back to stderr if pager unavailable)if show_help_in_pager(&out, true).is_err() {@@ -351,34 +345,31 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>/// Handle the state set commandpub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> anyhow::Result<()> {- let workspace = open_workspace()?;+ let repo = Repository::current()?;match key {"default-branch" => {- // Warn if the branch doesn't exist locally (git-only check)- if let Some(repo) = workspace.as_any().downcast_ref::<Repository>()- && !repo.branch(&value).exists_locally()?- {+ // Warn if the branch doesn't exist locally+ if !repo.branch(&value).exists_locally()? {eprintln!("{}",warning_message(cformat!("Branch <bold>{value}</> does not exist locally")));}- workspace.set_default_branch(&value)?;+ repo.set_default_branch(&value)?;eprintln!("{}",success_message(cformat!("Set default branch to <bold>{value}</>")));}"previous-branch" => {- workspace.set_switch_previous(Some(&value))?;+ repo.set_switch_previous(Some(&value))?;eprintln!("{}",success_message(cformat!("Set previous branch to <bold>{value}</>")));}"marker" => {- let repo = require_git_workspace(&*workspace, "config state marker set")?;let branch_name = match branch {Some(b) => b,None => repo.require_current_branch("set marker for current branch")?,@@ -411,35 +402,29 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any/// Handle the state clear commandpub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhow::Result<()> {- let workspace = open_workspace()?;+ let repo = Repository::current()?;match key {"default-branch" => {- if workspace.clear_default_branch()? {+ if repo.clear_default_branch_cache()? {eprintln!("{}", success_message("Cleared default branch cache"));} else {eprintln!("{}", info_message("No default branch cache to clear"));}}"previous-branch" => {- if workspace.switch_previous().is_some() {- // For git, set_switch_previous(None) is a no-op (designed for detached HEAD),- // so we need the downcast to call git config --unset directly.- // For jj, set_switch_previous(None) does the right thing.- if let Some(repo) = workspace.as_any().downcast_ref::<Repository>() {- let _ = repo.run_command(&["config", "--unset", "worktrunk.history"]);- } else {- workspace.set_switch_previous(None)?;- }+ if repo+ .run_command(&["config", "--unset", "worktrunk.history"])+ .is_ok()+ {eprintln!("{}", success_message("Cleared previous branch"));} else {eprintln!("{}", info_message("No previous branch to clear"));}}"ci-status" => {- let repo = require_git_workspace(&*workspace, "config state ci-status clear")?;if all {- let cleared = CachedCiStatus::clear_all(repo);+ let cleared = CachedCiStatus::clear_all(&repo);if cleared == 0 {eprintln!("{}", info_message("No CI cache entries to clear"));} else {@@ -475,7 +460,6 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho}}"marker" => {- let repo = require_git_workspace(&*workspace, "config state marker clear")?;if all {let output = repo.run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])@@ -524,8 +508,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho}}"logs" => {- let log_dir = workspace.wt_logs_dir();- let cleared = clear_logs(&log_dir)?;+ let cleared = clear_logs(&repo)?;if cleared == 0 {eprintln!("{}", info_message("No logs to clear"));} else {@@ -550,55 +533,49 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho/// Handle the state clear all commandpub fn handle_state_clear_all() -> anyhow::Result<()> {- let workspace = open_workspace()?;+ let repo = Repository::current()?;let mut cleared_any = false;- // Clear previous branch (works for both git and jj)- if workspace.switch_previous().is_some() {- if let Some(repo) = workspace.as_any().downcast_ref::<Repository>() {- let _ = repo.run_command(&["config", "--unset", "worktrunk.history"]);- } else {- let _ = workspace.set_switch_previous(None);- }+ // Clear default branch cache+ if matches!(repo.clear_default_branch_cache(), Ok(true)) {cleared_any = true;}- // Clear logs (works for both git and jj)- let log_dir = workspace.wt_logs_dir();- let logs_cleared = clear_logs(&log_dir)?;- if logs_cleared > 0 {+ // Clear previous branch+ if repo+ .run_command(&["config", "--unset", "worktrunk.history"])+ .is_ok()+ {cleared_any = true;}- // Clear default branch cache (works for both git and jj)- if matches!(workspace.clear_default_branch(), Ok(true)) {- cleared_any = true;+ // Clear all markers+ let markers_output = repo+ .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])+ .unwrap_or_default();+ for line in markers_output.lines() {+ if let Some(config_key) = line.split_whitespace().next() {+ let _ = repo.run_command(&["config", "--unset", config_key]);+ cleared_any = true;+ }}- // Git-only state: markers, CI cache, hints- if let Some(repo) = workspace.as_any().downcast_ref::<Repository>() {- // Clear all markers- let markers_output = repo- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])- .unwrap_or_default();- for line in markers_output.lines() {- if let Some(config_key) = line.split_whitespace().next() {- let _ = repo.run_command(&["config", "--unset", config_key]);- cleared_any = true;- }- }+ // Clear all CI status cache+ let ci_cleared = CachedCiStatus::clear_all(&repo);+ if ci_cleared > 0 {+ cleared_any = true;+ }- // Clear all CI status cache- let ci_cleared = CachedCiStatus::clear_all(repo);- if ci_cleared > 0 {- cleared_any = true;- }+ // Clear all logs+ let logs_cleared = clear_logs(&repo)?;+ if logs_cleared > 0 {+ cleared_any = true;+ }- // Clear all hints- let hints_cleared = repo.clear_all_hints()?;- if hints_cleared > 0 {- cleared_any = true;- }+ // Clear all hints+ let hints_cleared = repo.clear_all_hints()?;+ if hints_cleared > 0 {+ cleared_any = true;}if cleared_any {@@ -614,70 +591,59 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {/// Handle the state get command (shows all state)pub fn handle_state_show(format: OutputFormat) -> anyhow::Result<()> {- let workspace = open_workspace()?;- let repo = workspace.as_any().downcast_ref::<Repository>();+ let repo = Repository::current()?;match format {- OutputFormat::Json => handle_state_show_json(&*workspace, repo),- OutputFormat::Table | OutputFormat::ClaudeCode => {- handle_state_show_table(&*workspace, repo)- }+ OutputFormat::Json => handle_state_show_json(&repo),+ OutputFormat::Table | OutputFormat::ClaudeCode => handle_state_show_table(&repo),}}/// Output state as JSON-fn handle_state_show_json(- workspace: &dyn Workspace,- repo: Option<&Repository>,-) -> anyhow::Result<()> {- // Trait-compatible state (works for both git and jj)- let default_branch = workspace.default_branch_name();- let previous_branch = workspace.switch_previous();-- // Git-only state- let markers: Vec<serde_json::Value> = repo- .map(|r| {- get_all_markers(r)- .into_iter()- .map(|m| {- serde_json::json!({- "branch": m.branch,- "marker": m.marker,- "set_at": if m.set_at > 0 { Some(m.set_at) } else { None }- })- })- .collect()+fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {+ // Get default branch+ let default_branch = repo.default_branch();++ // Get previous branch+ let previous_branch = repo.switch_previous();++ // Get markers+ let markers: Vec<serde_json::Value> = get_all_markers(repo)+ .into_iter()+ .map(|m| {+ serde_json::json!({+ "branch": m.branch,+ "marker": m.marker,+ "set_at": if m.set_at > 0 { Some(m.set_at) } else { None }+ })})- .unwrap_or_default();+ .collect();- let ci_status: Vec<serde_json::Value> = repo- .map(|r| {- let mut ci_entries = CachedCiStatus::list_all(r);- ci_entries.sort_by(|a, b| {- b.1.checked_at- .cmp(&a.1.checked_at)- .then_with(|| a.0.cmp(&b.0))- });- ci_entries- .into_iter()- .map(|(branch, cached)| {- let status = cached- .status- .as_ref()- .map(|s| -> &'static str { s.ci_status.into() });- serde_json::json!({- "branch": branch,- "status": status,- "checked_at": cached.checked_at,- "head": cached.head- })- })- .collect()+ // Get CI status cache+ let mut ci_entries = CachedCiStatus::list_all(repo);+ ci_entries.sort_by(|a, b| {+ b.1.checked_at+ .cmp(&a.1.checked_at)+ .then_with(|| a.0.cmp(&b.0))+ });+ let ci_status: Vec<serde_json::Value> = ci_entries+ .into_iter()+ .map(|(branch, cached)| {+ let status = cached+ .status+ .as_ref()+ .map(|s| -> &'static str { s.ci_status.into() });+ serde_json::json!({+ "branch": branch,+ "status": status,+ "checked_at": cached.checked_at,+ "head": cached.head+ })})- .unwrap_or_default();+ .collect();- // Log files (works for both git and jj)- let log_dir = workspace.wt_logs_dir();+ // Get log files+ let log_dir = repo.wt_logs_dir();let logs: Vec<serde_json::Value> = if log_dir.exists() {let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?.filter_map(|e| e.ok())@@ -717,8 +683,8 @@ fn handle_state_show_json(vec![]};- // Hints (git-only)- let hints: Vec<String> = repo.map(|r| r.list_shown_hints()).unwrap_or_default();+ // Get hints+ let hints = repo.list_shown_hints();let output = serde_json::json!({"default_branch": default_branch,@@ -734,100 +700,94 @@ fn handle_state_show_json(}/// Output state as human-readable table-fn handle_state_show_table(- workspace: &dyn Workspace,- repo: Option<&Repository>,-) -> anyhow::Result<()> {+fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {// Build complete output as a stringlet mut out = String::new();- // Show default branch cache (trait method)+ // Show default branch cachewriteln!(out, "{}", format_heading("DEFAULT BRANCH", None))?;- match workspace.default_branch_name() {+ match repo.default_branch() {Some(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,None => writeln!(out, "{}", format_with_gutter("(not available)", None))?,}writeln!(out)?;- // Show previous branch (trait method)+ // Show previous branch (for `wt switch -`)writeln!(out, "{}", format_heading("PREVIOUS BRANCH", None))?;- match workspace.switch_previous() {+ match repo.switch_previous() {Some(prev) => writeln!(out, "{}", format_with_gutter(&prev, None))?,None => writeln!(out, "{}", format_with_gutter("(none)", None))?,}writeln!(out)?;- // Show branch markers (git-only)- if let Some(repo) = repo {- writeln!(out, "{}", format_heading("BRANCH MARKERS", None))?;- let markers = get_all_markers(repo);- if markers.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- } else {- let mut table = String::from("| Branch | Marker | Age |\n");- table.push_str("|--------|--------|-----|\n");- for entry in markers {- let age = format_relative_time_short(entry.set_at as i64);- table.push_str(&format!(- "| {} | {} | {} |\n",- entry.branch, entry.marker, age- ));- }- let rendered = crate::md_help::render_markdown_table(&table);- writeln!(out, "{}", rendered.trim_end())?;+ // Show branch markers+ writeln!(out, "{}", format_heading("BRANCH MARKERS", None))?;+ let markers = get_all_markers(repo);+ if markers.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ let mut table = String::from("| Branch | Marker | Age |\n");+ table.push_str("|--------|--------|-----|\n");+ for entry in markers {+ let age = format_relative_time_short(entry.set_at as i64);+ table.push_str(&format!(+ "| {} | {} | {} |\n",+ entry.branch, entry.marker, age+ ));}- writeln!(out)?;-- // Show CI status cache (git-only)- writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;- let mut entries = CachedCiStatus::list_all(repo);- // Sort by age (most recent first), then by branch name for ties- entries.sort_by(|a, b| {- b.1.checked_at- .cmp(&a.1.checked_at)- .then_with(|| a.0.cmp(&b.0))- });- if entries.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- } else {- // Build markdown table- let mut table = String::from("| Branch | Status | Age | Head |\n");- table.push_str("|--------|--------|-----|------|\n");- for (branch, cached) in entries {- let status = match &cached.status {- Some(pr_status) => {- let status: &'static str = pr_status.ci_status.into();- status.to_string()- }- None => "none".to_string(),- };- let age = format_relative_time_short(cached.checked_at as i64);- let head: String = cached.head.chars().take(8).collect();+ let rendered = crate::md_help::render_markdown_table(&table);+ writeln!(out, "{}", rendered.trim_end())?;+ }+ writeln!(out)?;- table.push_str(&format!("| {branch} | {status} | {age} | {head} |\n"));- }+ // Show CI status cache+ writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;+ let mut entries = CachedCiStatus::list_all(repo);+ // Sort by age (most recent first), then by branch name for ties+ entries.sort_by(|a, b| {+ b.1.checked_at+ .cmp(&a.1.checked_at)+ .then_with(|| a.0.cmp(&b.0))+ });+ if entries.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ // Build markdown table+ let mut table = String::from("| Branch | Status | Age | Head |\n");+ table.push_str("|--------|--------|-----|------|\n");+ for (branch, cached) in entries {+ let status = match &cached.status {+ Some(pr_status) => {+ let status: &'static str = pr_status.ci_status.into();+ status.to_string()+ }+ None => "none".to_string(),+ };+ let age = format_relative_time_short(cached.checked_at as i64);+ let head: String = cached.head.chars().take(8).collect();- let rendered = crate::md_help::render_markdown_table(&table);- writeln!(out, "{}", rendered.trim_end())?;+ table.push_str(&format!("| {branch} | {status} | {age} | {head} |\n"));}- writeln!(out)?;- // Show hints (git-only)- writeln!(out, "{}", format_heading("HINTS", None))?;- let hints = repo.list_shown_hints();- if hints.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- } else {- for hint in hints {- writeln!(out, "{}", format_with_gutter(&hint, None))?;- }+ let rendered = crate::md_help::render_markdown_table(&table);+ writeln!(out, "{}", rendered.trim_end())?;+ }+ writeln!(out)?;++ // Show hints+ writeln!(out, "{}", format_heading("HINTS", None))?;+ let hints = repo.list_shown_hints();+ if hints.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ for hint in hints {+ writeln!(out, "{}", format_with_gutter(&hint, None))?;}- writeln!(out)?;}+ writeln!(out)?;- // Show log files (trait method)- let log_dir = workspace.wt_logs_dir();- render_log_files(&mut out, &log_dir)?;+ // Show log files+ render_log_files(&mut out, repo)?;// Display through pager (fall back to stderr if pager unavailable)if let Err(e) = show_help_in_pager(&out, true) {diff --git a/src/commands/context.rs b/src/commands/context.rsindex d856844e2..367b422dc 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -1,27 +1,22 @@-use std::path::PathBuf;-use anyhow::Context;+use std::path::PathBuf;use worktrunk::config::UserConfig;use worktrunk::git::Repository;-use worktrunk::workspace::{Workspace, open_workspace};use super::command_executor::CommandContext;/// Shared execution context for command handlers that operate on the current worktree.///-/// Centralizes the common "workspace + branch + config + cwd" setup so individual handlers+/// Centralizes the common "repo + branch + config + cwd" setup so individual handlers/// can focus on their core logic while sharing consistent error messaging.///-/// Holds a `Box<dyn Workspace>` for VCS-agnostic operations. Commands that need-/// git-specific features (hooks, staging) can access `&Repository` via [`repo()`](Self::repo).-////// This helper is used for commands that explicitly act on "where the user is standing"-/// (e.g., `step commit` and `merge`) and therefore need all of these pieces together.-/// Commands that inspect multiple worktrees or run without a config/branch requirement-/// (`list`, `select`, some `worktree` helpers) call `open_workspace()` directly so they-/// can operate in broader contexts without forcing config loads or branch resolution.+/// (e.g., `beta` and `merge`) and therefore need all of these pieces together. Commands that+/// inspect multiple worktrees or run without a config/branch requirement (`list`, `select`,+/// some `worktree` helpers) still call `Repository::current()` directly so they can operate in+/// broader contexts without forcing config loads or branch resolution.pub struct CommandEnv {- pub workspace: Box<dyn Workspace>,+ pub repo: Repository,/// Current branch name, if on a branch (None in detached HEAD state).pub branch: Option<String>,pub config: UserConfig,@@ -29,81 +24,49 @@ pub struct CommandEnv {}impl CommandEnv {- /// Build the command environment from a pre-opened workspace.+ /// Load the command environment for a specific action.////// `action` describes what command is running (e.g., "merge", "squash")./// Used in error messages when the environment can't be loaded.- /// Requires a branch (can't merge/squash in detached HEAD).- pub fn with_workspace(- workspace: Box<dyn Workspace>,- action: &str,- config: UserConfig,- ) -> anyhow::Result<Self> {- let worktree_path = workspace.current_workspace_path()?;- let branch = workspace.current_name(&worktree_path)?;-- // Require a branch (can't merge/squash in detached HEAD)- if branch.is_none() {- return Err(worktrunk::git::GitError::DetachedHead {- action: Some(action.into()),- }- .into());- }+ pub fn for_action(action: &str, config: UserConfig) -> anyhow::Result<Self> {+ let repo = Repository::current()?;+ let worktree_path = repo.current_worktree().path().to_path_buf();+ let branch = repo.require_current_branch(action)?;Ok(Self {- workspace,- branch,+ repo,+ branch: Some(branch),config,worktree_path,})}- /// Build the command environment from a pre-opened workspace, without requiring a branch.+ /// Load the command environment without requiring a branch.////// Use this for commands that can operate in detached HEAD state,/// such as running hooks (where `{{ branch }}` expands to "HEAD" if detached).- pub fn with_workspace_branchless(workspace: Box<dyn Workspace>) -> anyhow::Result<Self> {- let worktree_path = workspace.current_workspace_path()?;- let branch = workspace- .current_name(&worktree_path)+ pub fn for_action_branchless() -> anyhow::Result<Self> {+ let repo = Repository::current()?;+ let current_wt = repo.current_worktree();+ let worktree_path = current_wt.path().to_path_buf();+ // Propagate git errors (broken repo, missing git) but allow None for detached HEAD+ let branch = current_wt+ .branch().context("Failed to determine current branch")?;let config = UserConfig::load().context("Failed to load config")?;Ok(Self {- workspace,+ repo,branch,config,worktree_path,})}- /// Open a workspace and load the command environment without requiring a branch.- ///- /// Convenience wrapper that calls `open_workspace()` then `with_workspace_branchless()`.- pub fn for_action_branchless() -> anyhow::Result<Self> {- Self::with_workspace_branchless(open_workspace()?)- }-- /// Access the underlying git `Repository`.- ///- /// Returns `None` if this is a non-git workspace (e.g., jj).- /// For git workspaces, this is always `Some`.- pub fn repo(&self) -> Option<&Repository> {- self.workspace.as_any().downcast_ref::<Repository>()- }-- /// Access the underlying git `Repository`, returning an error if not git.- ///- /// Use in code paths that require git-specific features (hooks, staging).- pub fn require_repo(&self) -> anyhow::Result<&Repository> {- self.repo()- .ok_or_else(|| anyhow::anyhow!("This command requires a git repository"))- }-/// Build a `CommandContext` tied to this environment.pub fn context(&self, yes: bool) -> CommandContext<'_> {CommandContext::new(- self.workspace.as_ref(),+ &self.repo,&self.config,self.branch.as_deref(),&self.worktree_path,@@ -126,7 +89,7 @@ impl CommandEnv {/// Uses the remote URL if available, otherwise the canonical repository path./// Returns None only if the path is not valid UTF-8.pub fn project_id(&self) -> Option<String> {- self.workspace.project_identifier().ok()+ self.repo.project_identifier().ok()}/// Get all resolved config with defaults applied.diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 6a1d08952..9e05f27eb 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -27,12 +27,12 @@ use std::process::Stdio;use color_print::cformat;use worktrunk::config::{UserConfig, expand_template};+use worktrunk::git::Repository;use worktrunk::git::WorktrunkError;use worktrunk::shell_exec::ShellConfig;use worktrunk::styling::{eprintln, error_message, format_with_gutter, progress_message, success_message, warning_message,};-use worktrunk::workspace::build_worktree_map;use crate::commands::command_executor::{CommandContext, build_hook_context};use crate::commands::worktree_display_name;@@ -44,8 +44,7 @@ use crate::commands::worktree_display_name;////// All template variables from hooks are available, and context JSON is piped to stdin.pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {- let workspace = worktrunk::workspace::open_workspace()?;- let repo = super::require_git_workspace(&*workspace, "step for-each")?;+ let repo = Repository::current()?;// Filter out prunable worktrees (directory deleted) - can't run commands therelet worktrees: Vec<_> = repo.list_worktrees()?@@ -61,7 +60,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {let command_template = args.join(" ");for wt in &worktrees {- let display_name = worktree_display_name(wt, repo, &config);+ let display_name = worktree_display_name(wt, &repo, &config);eprintln!("{}",progress_message(format!("Running in {display_name}..."))@@ -69,7 +68,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {// Build full hook context for this worktree// Pass wt.branch directly (not the display string) so detached HEAD maps to None -> "HEAD"- let ctx = CommandContext::new(repo, &config, wt.branch.as_deref(), &wt.path, false);+ let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);let context_map = build_hook_context(&ctx, &[]);// Convert to &str references for expand_template@@ -79,15 +78,8 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {.collect();// Expand template with full context (shell-escaped)- let worktree_map = build_worktree_map(repo);- let command = expand_template(- &command_template,- &vars,- true,- &worktree_map,- "for-each command",- )- .map_err(|e| anyhow::anyhow!("Template expansion failed: {e}"))?;+ let command = expand_template(&command_template, &vars, true, &repo, "for-each command")+ .map_err(|e| anyhow::anyhow!("Template expansion failed: {e}"))?;// Build JSON context for stdinlet context_json = serde_json::to_string(&context_map)diff --git a/src/commands/handle_merge_jj.rs b/src/commands/handle_merge_jj.rsdeleted file mode 100644index 45db97e4a..000000000--- a/src/commands/handle_merge_jj.rs+++ /dev/null@@ -1,210 +0,0 @@-//! Merge command handler for jj repositories.-//!-//! Handles squash/rebase, hook execution, push, and optional workspace removal.-//! jj auto-snapshots the working copy (no staging area or pre-commit hooks).--use std::path::Path;--use anyhow::Context;-use color_print::cformat;-use worktrunk::HookType;-use worktrunk::config::UserConfig;-use worktrunk::styling::{eprintln, info_message, success_message};-use worktrunk::workspace::{JjWorkspace, Workspace};--use super::command_approval::approve_hooks;-use super::context::CommandEnv;-use super::handle_remove_jj::remove_jj_workspace_and_cd;-use super::hooks::{HookFailureStrategy, run_hook_with_filter};-use super::merge::MergeOptions;-use super::step_commands::{SquashResult, do_squash};--/// Handle `wt merge` for jj repositories.-///-/// Squashes (or rebases) the current workspace's changes into trunk,-/// runs pre-merge/post-merge hooks, updates the target bookmark, pushes-/// if possible, and optionally removes the workspace.-pub fn handle_merge_jj(opts: MergeOptions<'_>) -> anyhow::Result<()> {- let workspace = JjWorkspace::from_current_dir()?;- let cwd = std::env::current_dir()?;-- let current = workspace.current_workspace(&cwd)?;-- if current.is_default {- anyhow::bail!("Cannot merge the default workspace");- }-- let ws_name = current.name.clone();- let ws_path = current.path.clone();-- // Load config for merge defaults- let config = UserConfig::load().context("Failed to load config")?;- let project_id = workspace.project_identifier().ok();- let resolved = config.resolved(project_id.as_deref());-- // CLI flags override config values- let verify = opts.verify.unwrap_or(resolved.merge.verify());- let yes = opts.yes;- let remove = opts.remove.unwrap_or(resolved.merge.remove());-- // "Approve at the Gate": approve all hooks upfront- let verify = if verify {- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);-- let mut hook_types = vec![HookType::PreMerge, HookType::PostMerge];- if remove {- hook_types.extend_from_slice(&[- HookType::PreRemove,- HookType::PostRemove,- HookType::PostSwitch,- ]);- }-- let approved = approve_hooks(&ctx, &hook_types)?;- if !approved {- eprintln!("{}", info_message("Commands declined, continuing merge"));- false- } else {- true- }- } else {- false- };-- // Target bookmark name — detect from trunk() or use explicit override- let detected_target = workspace.trunk_bookmark()?;- let target = opts.target.unwrap_or(detected_target.as_str());-- // Check if already integrated- let feature_tip = workspace.feature_tip(&ws_path)?;- if workspace.is_integrated(&feature_tip, target)?.is_some() {- eprintln!(- "{}",- info_message(cformat!(- "Workspace <bold>{ws_name}</> is already integrated into trunk"- ))- );- return remove_if_requested(&workspace, remove, yes, &ws_name, &ws_path, verify);- }-- // CLI flags override config values (jj always squashes by default)- let squash = opts.squash.unwrap_or(resolved.merge.squash());-- if squash {- let repo_name = project_id.as_deref().unwrap_or("repo");- match do_squash(- &workspace,- target,- &ws_path,- &resolved.commit_generation,- &ws_name,- repo_name,- )? {- SquashResult::NoCommitsAhead(_) => {- eprintln!(- "{}",- info_message(cformat!(- "Workspace <bold>{ws_name}</> is already integrated into trunk"- ))- );- return remove_if_requested(&workspace, remove, yes, &ws_name, &ws_path, verify);- }- SquashResult::AlreadySingleCommit | SquashResult::Squashed => {- // Proceed to push- }- SquashResult::NoNetChanges => {- // Feature commits canceled out — nothing to push, just remove- return remove_if_requested(&workspace, remove, yes, &ws_name, &ws_path, verify);- }- }- } else {- rebase_onto_trunk(&workspace, &ws_path, target)?;- }-- // Run pre-merge hooks (after squash/rebase, before push)- if verify {- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- let project_config = workspace.load_project_config()?;- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- run_hook_with_filter(- &ctx,- user_hooks.pre_merge.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.pre_merge.as_ref()),- HookType::PreMerge,- &[("target", target)],- HookFailureStrategy::FailFast,- None,- None,- )?;- }-- let mode = if squash { "Squashed" } else { "Merged" };- eprintln!(- "{}",- success_message(cformat!(- "{mode} workspace <bold>{ws_name}</> into <bold>{target}</>"- ))- );-- // Run post-merge hooks before removal (cwd must still exist)- if verify {- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- let project_config = workspace.load_project_config()?;- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- run_hook_with_filter(- &ctx,- user_hooks.post_merge.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_merge.as_ref()),- HookType::PostMerge,- &[("target", target)],- HookFailureStrategy::Warn,- None,- None,- )?;- }-- // Remove workspace if requested- remove_if_requested(&workspace, remove, yes, &ws_name, &ws_path, verify)?;-- Ok(())-}--/// Rebase the feature branch onto trunk without squashing.-///-/// 1. `jj rebase -b @ -d {target}` — rebase entire branch-/// 2. Determine feature tip (@ if has content, @- if empty)-/// 3. `jj bookmark set {target} -r {tip}` — update bookmark-fn rebase_onto_trunk(workspace: &JjWorkspace, ws_path: &Path, target: &str) -> anyhow::Result<()> {- workspace.run_in_dir(ws_path, &["rebase", "-b", "@", "-d", target])?;-- // After rebase, find the feature tip (same logic as squash path)- let feature_tip = workspace.feature_tip(ws_path)?;- workspace.run_in_dir(ws_path, &["bookmark", "set", target, "-r", &feature_tip])?;-- Ok(())-}--/// Remove the workspace if `--no-remove` wasn't specified.-fn remove_if_requested(- workspace: &JjWorkspace,- remove: bool,- yes: bool,- ws_name: &str,- ws_path: &Path,- run_hooks: bool,-) -> anyhow::Result<()> {- if !remove {- eprintln!("{}", info_message("Workspace preserved (--no-remove)"));- return Ok(());- }-- // Pass through run_hooks so pre-remove/post-remove/post-switch hooks execute during merge- remove_jj_workspace_and_cd(workspace, ws_name, ws_path, run_hooks, yes)-}diff --git a/src/commands/handle_remove_jj.rs b/src/commands/handle_remove_jj.rsdeleted file mode 100644index 38546b885..000000000--- a/src/commands/handle_remove_jj.rs+++ /dev/null@@ -1,138 +0,0 @@-//! Remove helper for jj repositories.-//!-//! Simpler than git removal: no branch deletion, no merge status checks.-//! Just forget the workspace and remove the directory.--use std::path::Path;--use color_print::cformat;-use worktrunk::HookType;-use worktrunk::path::format_path_for_display;-use worktrunk::styling::{eprintln, success_message, warning_message};-use worktrunk::workspace::Workspace;--use super::context::CommandEnv;-use super::hooks::{HookFailureStrategy, run_hook_with_filter};-use crate::output;--/// Forget a jj workspace, remove its directory, and cd to default if needed.-///-/// Shared between `wt remove` and `wt merge` for jj repositories.-pub fn remove_jj_workspace_and_cd(- workspace: &dyn Workspace,- name: &str,- ws_path: &Path,- run_hooks: bool,- yes: bool,-) -> anyhow::Result<()> {- if name == "default" {- anyhow::bail!("Cannot remove the default workspace");- }-- let path_display = format_path_for_display(ws_path);-- // Check if we're inside the workspace being removed- let cwd = dunce::canonicalize(std::env::current_dir()?)?;- let canonical_ws = dunce::canonicalize(ws_path).unwrap_or_else(|_| ws_path.to_path_buf());- let removing_current = cwd.starts_with(&canonical_ws);-- // Build hook context BEFORE deletion — CommandEnv needs the current directory to exist- let hook_ctx = if run_hooks {- let env = CommandEnv::for_action_branchless()?;- let project_config = workspace.load_project_config()?;- Some((env, project_config))- } else {- None- };-- // Run pre-remove hooks- if let Some((ref env, ref project_config)) = hook_ctx {- let ctx = env.context(yes);- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- run_hook_with_filter(- &ctx,- user_hooks.pre_remove.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.pre_remove.as_ref()),- HookType::PreRemove,- &[],- HookFailureStrategy::FailFast,- None,- None,- )?;- }-- // Forget the workspace in jj- workspace.remove_workspace(name)?;-- // Remove the directory- if ws_path.exists() {- std::fs::remove_dir_all(ws_path).map_err(|e| {- anyhow::anyhow!(- "Workspace forgotten but failed to remove {}: {}",- path_display,- e- )- })?;- } else {- eprintln!(- "{}",- warning_message(cformat!(- "Workspace directory already removed: <bold>{path_display}</>"- ))- );- }- eprintln!(- "{}",- success_message(cformat!(- "Removed workspace <bold>{name}</> @ <bold>{path_display}</>"- ))- );-- // If removing current workspace, cd to default workspace- if removing_current {- let default_path = match workspace.default_workspace_path()? {- Some(p) => p,- None => workspace.root_path()?,- };- output::change_directory(&default_path)?;- }-- // Run post-remove hooks (using pre-built context from before deletion)- if let Some((ref env, ref project_config)) = hook_ctx {- let ctx = env.context(yes);- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- run_hook_with_filter(- &ctx,- user_hooks.post_remove.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_remove.as_ref()),- HookType::PostRemove,- &[],- HookFailureStrategy::Warn,- None,- None,- )?;-- // Run post-switch hooks when removing the current workspace- // (we've changed directory to the default workspace)- if removing_current {- run_hook_with_filter(- &ctx,- user_hooks.post_switch.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_switch.as_ref()),- HookType::PostSwitch,- &[],- HookFailureStrategy::Warn,- None,- None,- )?;- }- }-- Ok(())-}diff --git a/src/commands/handle_step_jj.rs b/src/commands/handle_step_jj.rsdeleted file mode 100644index 992dafe93..000000000--- a/src/commands/handle_step_jj.rs+++ /dev/null@@ -1,94 +0,0 @@-//! Step command handlers for jj repositories.-//!-//! jj equivalent of `step commit`. Squash and push are handled by unified-//! implementations via the [`Workspace`] trait.--use anyhow::Context;-use color_print::cformat;-use worktrunk::config::UserConfig;-use worktrunk::styling::{eprintln, success_message};-use worktrunk::workspace::{JjWorkspace, Workspace};--/// Handle `wt step commit` for jj repositories.-///-/// jj auto-snapshots the working copy, so "commit" means describing the-/// current change and starting a new one:-///-/// 1. Check if there are changes to commit (`jj diff`)-/// 2. Generate a commit message (LLM or fallback)-/// 3. `jj describe -m "{message}"` — set the description-/// 4. `jj new` — start a new change-pub fn step_commit_jj() -> anyhow::Result<()> {- let workspace = JjWorkspace::from_current_dir()?;- let cwd = std::env::current_dir()?;-- // Check if there are changes to commit- let (diff, diff_stat) = workspace.committable_diff_for_prompt(&cwd)?;- if diff.trim().is_empty() {- anyhow::bail!("Nothing to commit (working copy is empty)");- }-- let config = UserConfig::load().context("Failed to load config")?;- let project_id = workspace.project_identifier().ok();- let commit_config = config.commit_generation(project_id.as_deref());-- let commit_message =- generate_jj_commit_message(&workspace, &cwd, &diff, &diff_stat, &commit_config)?;-- // Describe the current change and start a new one- workspace.commit(&commit_message, &cwd)?;-- // Show commit message first line (more useful than change ID)- let first_line = commit_message.lines().next().unwrap_or(&commit_message);- eprintln!(- "{}",- success_message(cformat!("Committed: <dim>{}</>", first_line))- );-- Ok(())-}--// ============================================================================-// Helpers-// ============================================================================--/// Generate a commit message for jj changes.-///-/// Uses LLM if configured, otherwise falls back to the existing jj description-/// or a message based on changed files (shared fallback with git via `generate_commit_message`).-fn generate_jj_commit_message(- workspace: &JjWorkspace,- cwd: &std::path::Path,- diff: &str,- diff_stat: &str,- config: &worktrunk::config::CommitGenerationConfig,-) -> anyhow::Result<String> {- // jj-specific: check existing description first (jj may already have one)- if !config.is_configured() {- let description = workspace.run_in_dir(- cwd,- &["log", "-r", "@", "--no-graph", "-T", "self.description()"],- )?;- let description = description.trim();-- if !description.is_empty() {- return Ok(description.to_string());- }- }-- // Shared path: build CommitInput and use unified generate_commit_message- let ws_name = workspace- .current_name(cwd)?- .unwrap_or_else(|| "default".to_string());- let repo_name = workspace.project_identifier().ok();- let repo_name_str = repo_name.as_deref().unwrap_or("repo");-- let input = crate::llm::CommitInput {- diff,- diff_stat,- branch: &ws_name,- repo_name: repo_name_str,- recent_commits: None,- };- crate::llm::generate_commit_message(&input, config)-}diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 24de2c91e..67bf181bf 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -8,12 +8,11 @@ use worktrunk::HookType;use worktrunk::config::{UserConfig, expand_template};use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message};-use worktrunk::workspace::build_worktree_map;use super::command_approval::approve_hooks;use super::command_executor::{CommandContext, build_hook_context};use super::worktree::{- SwitchPlan, SwitchResult, execute_switch, plan_switch, resolve_path_mismatch,+ SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, get_path_mismatch, plan_switch,};use crate::output::{execute_user_command, handle_switch_output, is_shell_integration_active,@@ -39,7 +38,7 @@ pub struct SwitchOptions<'a> {/// Returns `true` if hooks are approved to run./// Returns `false` if hooks should be skipped (`!verify` or user declined).pub(crate) fn approve_switch_hooks(- workspace: &dyn worktrunk::workspace::Workspace,+ repo: &Repository,config: &UserConfig,plan: &SwitchPlan,yes: bool,@@ -49,13 +48,7 @@ pub(crate) fn approve_switch_hooks(return Ok(false);}- let ctx = CommandContext::new(- workspace,- config,- Some(plan.branch()),- plan.worktree_path(),- yes,- );+ let ctx = CommandContext::new(repo, config, Some(plan.branch()), plan.worktree_path(), yes);let approved = if plan.is_create() {approve_hooks(&ctx,@@ -107,7 +100,7 @@ pub(crate) fn switch_extra_vars(result: &SwitchResult) -> Vec<(&str, &str)> {/// Spawn post-switch (and post-start for creates) background hooks.pub(crate) fn spawn_switch_background_hooks(- workspace: &dyn worktrunk::workspace::Workspace,+ repo: &Repository,config: &UserConfig,result: &SwitchResult,branch: &str,@@ -115,7 +108,7 @@ pub(crate) fn spawn_switch_background_hooks(extra_vars: &[(&str, &str)],hooks_display_path: Option<&Path>,) -> anyhow::Result<()> {- let ctx = CommandContext::new(workspace, config, Some(branch), result.path(), yes);+ let ctx = CommandContext::new(repo, config, Some(branch), result.path(), yes);let mut hooks = super::hooks::prepare_background_hooks(&ctx,@@ -140,12 +133,6 @@ pub fn handle_switch(config: &mut UserConfig,binary_name: &str,) -> anyhow::Result<()> {- // Open workspace once, route by VCS type via downcast- let workspace = worktrunk::workspace::open_workspace()?;- let Some(repo) = workspace.as_any().downcast_ref::<Repository>() else {- return super::handle_switch_jj::handle_switch_jj(opts, config, binary_name);- };-let SwitchOptions {branch,create,@@ -158,16 +145,18 @@ pub fn handle_switch(verify,} = opts;+ let repo = Repository::current().context("Failed to switch worktree")?;+// Validate FIRST (before approval) - fails fast if branch doesn't exist, etc.- let plan = plan_switch(repo, branch, create, base, clobber, config)?;+ let plan = plan_switch(&repo, branch, create, base, clobber, config)?;// "Approve at the Gate": collect and approve hooks upfront// This ensures approval happens once at the command entry point// If user declines, skip hooks but continue with worktree operation- let skip_hooks = !approve_switch_hooks(repo, config, &plan, yes, verify)?;+ let skip_hooks = !approve_switch_hooks(&repo, config, &plan, yes, verify)?;// Execute the validated plan- let (result, branch_info) = execute_switch(repo, plan, config, yes, skip_hooks)?;+ let (result, branch_info) = execute_switch(&repo, plan, config, yes, skip_hooks)?;// Early exit for benchmarking time-to-first-outputif std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {@@ -175,7 +164,16 @@ pub fn handle_switch(}// Compute path mismatch lazily (deferred from plan_switch for existing worktrees)- let branch_info = resolve_path_mismatch(branch_info, &result, repo, config);+ let branch_info = match &result {+ SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {+ let expected_path = get_path_mismatch(&repo, &branch_info.branch, path, config);+ SwitchBranchInfo {+ expected_path,+ ..branch_info+ }+ }+ _ => branch_info,+ };// Show success message (temporal locality: immediately after worktree operation)// Returns path to display in hooks when user's shell won't be in the worktree@@ -205,7 +203,7 @@ pub fn handle_switch(// Batch hooks into a single message when both types are presentif !skip_hooks {spawn_switch_background_hooks(- repo,+ &repo,config,&result,&branch_info.branch,@@ -218,54 +216,38 @@ pub fn handle_switch(// Execute user command after post-start hooks have been spawned// Note: execute_args requires execute via clap's `requires` attributeif let Some(cmd) = execute {- let ctx = CommandContext::new(repo, config, Some(&branch_info.branch), result.path(), yes);- expand_and_execute_command(- &ctx,- cmd,- execute_args,- &extra_vars,- hooks_display_path.as_deref(),- )?;+ // Build template context for expansion (includes base vars when creating)+ let ctx = CommandContext::new(&repo, config, Some(&branch_info.branch), result.path(), yes);+ let template_vars = build_hook_context(&ctx, &extra_vars);+ let vars: HashMap<&str, &str> = template_vars+ .iter()+ .map(|(k, v)| (k.as_str(), v.as_str()))+ .collect();++ // Expand template variables in command (shell_escape: true for safety)+ let expanded_cmd = expand_template(cmd, &vars, true, &repo, "--execute command")+ .map_err(|e| anyhow::anyhow!("Failed to expand --execute template: {}", e))?;++ // Append any trailing args (after --) to the execute command+ // Each arg is also expanded, then shell-escaped+ let full_cmd = if execute_args.is_empty() {+ expanded_cmd+ } else {+ let expanded_args: Result<Vec<_>, _> = execute_args+ .iter()+ .map(|arg| {+ expand_template(arg, &vars, false, &repo, "--execute argument")+ .map_err(|e| anyhow::anyhow!("Failed to expand argument template: {}", e))+ })+ .collect();+ let escaped_args: Vec<_> = expanded_args?+ .iter()+ .map(|arg| shlex::try_quote(arg).unwrap_or(arg.into()).into_owned())+ .collect();+ format!("{} {}", expanded_cmd, escaped_args.join(" "))+ };+ execute_user_command(&full_cmd, hooks_display_path.as_deref())?;}Ok(())}--/// Expand `--execute` template with context variables and run the command.-///-/// Shared between git and jj switch handlers.-pub(crate) fn expand_and_execute_command(- ctx: &CommandContext<'_>,- cmd: &str,- execute_args: &[String],- extra_vars: &[(&str, &str)],- hooks_display_path: Option<&Path>,-) -> anyhow::Result<()> {- let template_vars = build_hook_context(ctx, extra_vars);- let vars: HashMap<&str, &str> = template_vars- .iter()- .map(|(k, v)| (k.as_str(), v.as_str()))- .collect();- let worktree_map = build_worktree_map(ctx.workspace);-- let expanded_cmd = expand_template(cmd, &vars, true, &worktree_map, "--execute command")- .map_err(|e| anyhow::anyhow!("Failed to expand --execute template: {}", e))?;-- let full_cmd = if execute_args.is_empty() {- expanded_cmd- } else {- let expanded_args: Result<Vec<_>, _> = execute_args- .iter()- .map(|arg| {- expand_template(arg, &vars, false, &worktree_map, "--execute argument")- .map_err(|e| anyhow::anyhow!("Failed to expand argument template: {}", e))- })- .collect();- let escaped_args: Vec<_> = expanded_args?- .iter()- .map(|arg| shlex::try_quote(arg).unwrap_or(arg.into()).into_owned())- .collect();- format!("{} {}", expanded_cmd, escaped_args.join(" "))- };- execute_user_command(&full_cmd, hooks_display_path)-}diff --git a/src/commands/handle_switch_jj.rs b/src/commands/handle_switch_jj.rsdeleted file mode 100644index f218130b5..000000000--- a/src/commands/handle_switch_jj.rs+++ /dev/null@@ -1,280 +0,0 @@-//! Switch command handler for jj repositories.-//!-//! Supports the same hook lifecycle as the git path: approval, post-create-//! (blocking), post-start/post-switch (background), `--execute`, switch-previous-//! tracking, and shell integration prompts.--use std::path::PathBuf;--use color_print::cformat;-use normalize_path::NormalizePath;-use worktrunk::HookType;-use worktrunk::config::{UserConfig, sanitize_branch_name};-use worktrunk::path::format_path_for_display;-use worktrunk::styling::{eprintln, info_message, success_message};-use worktrunk::workspace::{JjWorkspace, Workspace};--use super::command_approval::approve_hooks;-use super::command_executor::CommandContext;-use super::handle_switch::SwitchOptions;-use crate::output;-use crate::output::{is_shell_integration_active, prompt_shell_integration};--/// Handle `wt switch` for jj repositories.-pub fn handle_switch_jj(- opts: SwitchOptions<'_>,- config: &mut UserConfig,- binary_name: &str,-) -> anyhow::Result<()> {- let workspace = JjWorkspace::from_current_dir()?;-- // Resolve `wt switch -` to the previous workspace- let resolved_name;- let name = if opts.branch == "-" {- resolved_name = workspace- .switch_previous()- .ok_or_else(|| anyhow::anyhow!("No previous workspace to switch to"))?;- &resolved_name- } else {- opts.branch- };-- // Check if workspace already exists- let existing_path = find_existing_workspace(&workspace, name)?;-- if let Some(path) = existing_path {- return handle_existing_switch(&workspace, name, &path, &opts, config, binary_name);- }-- // Workspace doesn't exist — need --create to make one- if !opts.create {- anyhow::bail!("Workspace '{}' not found. Use --create to create it.", name);- }-- handle_create_switch(&workspace, name, &opts, config, binary_name)-}--/// Switch to an existing workspace.-fn handle_existing_switch(- workspace: &JjWorkspace,- name: &str,- path: &std::path::Path,- opts: &SwitchOptions<'_>,- config: &mut UserConfig,- binary_name: &str,-) -> anyhow::Result<()> {- // Approve post-switch hooks upfront- let skip_hooks = if opts.verify {- let ctx = CommandContext::new(workspace, config, Some(name), path, opts.yes);- let approved = approve_hooks(&ctx, &[HookType::PostSwitch])?;- if !approved {- eprintln!("{}", info_message("Commands declined"));- }- !approved- } else {- true- };-- // Track switch-previous before switching- record_switch_previous(workspace);-- // Show success message- let path_display = format_path_for_display(path);- eprintln!(- "{}",- success_message(cformat!(- "Switched to workspace <bold>{name}</> @ <bold>{path_display}</>"- ))- );-- if opts.change_dir {- output::change_directory(path)?;- }-- // Shell integration prompt- if !is_shell_integration_active() {- let skip_prompt = opts.execute.is_some();- let _ = prompt_shell_integration(config, binary_name, skip_prompt);- }-- let hooks_display_path = output::post_hook_display_path(path).map(|p| p.to_path_buf());-- // Background hooks (post-switch only for existing)- if !skip_hooks {- let ctx = CommandContext::new(workspace, config, Some(name), path, opts.yes);- let hooks = super::hooks::prepare_background_hooks(- &ctx,- HookType::PostSwitch,- &[],- hooks_display_path.as_deref(),- )?;- super::hooks::spawn_background_hooks(&ctx, hooks)?;- }-- // Execute user command (--execute)- if let Some(cmd) = opts.execute {- let ctx = CommandContext::new(workspace, config, Some(name), path, opts.yes);- super::handle_switch::expand_and_execute_command(- &ctx,- cmd,- opts.execute_args,- &[],- hooks_display_path.as_deref(),- )?;- }-- Ok(())-}--/// Create a new workspace and switch to it.-fn handle_create_switch(- workspace: &JjWorkspace,- name: &str,- opts: &SwitchOptions<'_>,- config: &mut UserConfig,- binary_name: &str,-) -> anyhow::Result<()> {- // Compute path for new workspace- let worktree_path = compute_jj_workspace_path(workspace, name)?;-- if worktree_path.exists() {- anyhow::bail!(- "Path already exists: {}",- format_path_for_display(&worktree_path)- );- }-- // Approve hooks upfront (post-create, post-start, post-switch)- let skip_hooks = if opts.verify {- let ctx = CommandContext::new(workspace, config, Some(name), &worktree_path, opts.yes);- let approved = approve_hooks(- &ctx,- &[- HookType::PostCreate,- HookType::PostStart,- HookType::PostSwitch,- ],- )?;- if !approved {- eprintln!(- "{}",- info_message("Commands declined, continuing workspace creation")- );- }- !approved- } else {- true- };-- // Track switch-previous before creating- record_switch_previous(workspace);-- // Create the workspace- workspace.create_workspace(name, opts.base, &worktree_path)?;-- // Run post-create hooks (blocking) before success message- let base_str = opts.base.unwrap_or_default().to_string();- let extra_vars: Vec<(&str, &str)> = if opts.base.is_some() {- vec![("base", &base_str)]- } else {- Vec::new()- };-- if !skip_hooks {- let ctx = CommandContext::new(workspace, config, Some(name), &worktree_path, opts.yes);- ctx.execute_post_create_commands(&extra_vars)?;- }-- // Show success message- let path_display = format_path_for_display(&worktree_path);- eprintln!(- "{}",- success_message(cformat!(- "Created workspace <bold>{name}</> @ <bold>{path_display}</>"- ))- );-- if opts.change_dir {- output::change_directory(&worktree_path)?;- }-- // Shell integration prompt- if !is_shell_integration_active() {- let skip_prompt = opts.execute.is_some();- let _ = prompt_shell_integration(config, binary_name, skip_prompt);- }-- let hooks_display_path =- output::post_hook_display_path(&worktree_path).map(|p| p.to_path_buf());-- // Background hooks (post-switch + post-start for creates)- if !skip_hooks {- let ctx = CommandContext::new(workspace, config, Some(name), &worktree_path, opts.yes);- let mut hooks = super::hooks::prepare_background_hooks(- &ctx,- HookType::PostSwitch,- &extra_vars,- hooks_display_path.as_deref(),- )?;- hooks.extend(super::hooks::prepare_background_hooks(- &ctx,- HookType::PostStart,- &extra_vars,- hooks_display_path.as_deref(),- )?);- super::hooks::spawn_background_hooks(&ctx, hooks)?;- }-- // Execute user command (--execute)- if let Some(cmd) = opts.execute {- let ctx = CommandContext::new(workspace, config, Some(name), &worktree_path, opts.yes);- super::handle_switch::expand_and_execute_command(- &ctx,- cmd,- opts.execute_args,- &extra_vars,- hooks_display_path.as_deref(),- )?;- }-- Ok(())-}--/// Record the current workspace name as switch-previous.-fn record_switch_previous(workspace: &JjWorkspace) {- if let Ok(current_path) = workspace.current_workspace_path()- && let Ok(Some(current)) = workspace.current_name(¤t_path)- {- let _ = workspace.set_switch_previous(Some(¤t));- }-}--/// Find an existing workspace by name, returning its path if it exists.-fn find_existing_workspace(workspace: &JjWorkspace, name: &str) -> anyhow::Result<Option<PathBuf>> {- let workspaces = workspace.list_workspaces()?;- for ws in &workspaces {- if ws.name == name {- return Ok(Some(ws.path.clone()));- }- }- Ok(None)-}--/// Compute the filesystem path for a new jj workspace.-///-/// Uses the same sibling-directory convention as git worktrees:-/// `{repo_root}/../{repo_name}.{workspace_name}`-fn compute_jj_workspace_path(workspace: &JjWorkspace, name: &str) -> anyhow::Result<PathBuf> {- let root = workspace.root();- let repo_name = root- .file_name()- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename"))?- .to_str()- .ok_or_else(|| anyhow::anyhow!("Repository path contains invalid UTF-8"))?;-- let sanitized = sanitize_branch_name(name);- let path = root- .join(format!("../{}.{}", repo_name, sanitized))- .normalize();- Ok(path)-}diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex a7735eddc..6b0226052 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -14,13 +14,12 @@ use color_print::cformat;use strum::IntoEnumIterator;use worktrunk::HookType;use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};-use worktrunk::git::GitError;+use worktrunk::git::{GitError, Repository};use worktrunk::path::format_path_for_display;use worktrunk::styling::{INFO_SYMBOL, PROMPT_SYMBOL, eprintln, format_bash_with_gutter, format_heading, hint_message,info_message, success_message,};-use worktrunk::workspace::{Workspace, build_worktree_map, open_workspace};use super::command_approval::approve_hooks_filtered;use super::command_executor::build_hook_context;@@ -57,10 +56,11 @@ pub fn run_hook() -> anyhow::Result<()> {// Derive context from current environment (branch-optional for CI compatibility)let env = CommandEnv::for_action_branchless()?;+ let repo = &env.repo;let ctx = env.context(yes);// Load project config (optional - user hooks can run without project config)- let project_config = ctx.workspace.load_project_config()?;+ let project_config = repo.load_project_config()?;// "Approve at the Gate": approve project hooks upfront// Pass name_filter to only approve the targeted hook, not all hooks of this type@@ -201,7 +201,7 @@ pub fn run_hook(require_hooks(user_config, project_config, hook_type)?;// Pre-commit hook can optionally use target branch context// Custom vars take precedence (added last)- let target_branch = ctx.workspace.default_branch_name();+ let target_branch = repo.default_branch();let mut extra_vars: Vec<(&str, &str)> = target_branch.as_deref().into_iter()@@ -324,13 +324,17 @@ pub fn run_hook(pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {use super::command_approval::approve_command_batch;- let workspace = open_workspace()?;- let project_id = workspace.project_identifier()?;+ let repo = Repository::current()?;+ let project_id = repo.project_identifier()?;let config = UserConfig::load().context("Failed to load config")?;// Load project config (error if missing - this command requires it)- let config_path = workspace.root_path()?.join(".config").join("wt.toml");- let project_config = workspace+ let config_path = repo+ .current_worktree()+ .root()?+ .join(".config")+ .join("wt.toml");+ let project_config = repo.load_project_config()?.ok_or(GitError::ProjectConfigNotFound { config_path })?;@@ -417,8 +421,8 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {);} else {// Clear approvals for current project (default)- let workspace = open_workspace()?;- let project_id = workspace.project_identifier()?;+ let repo = Repository::current()?;+ let project_id = repo.project_identifier()?;// Check if project has any approvals (not just if it exists)let had_approvals = config@@ -458,10 +462,10 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyhow::Result<()> {use crate::help_pager::show_help_in_pager;- let workspace = open_workspace()?;+ let repo = Repository::current()?;let config = UserConfig::load().context("Failed to load user config")?;- let project_config = workspace.load_project_config()?;- let project_id = workspace.project_identifier().ok();+ let project_config = repo.load_project_config()?;+ let project_id = repo.project_identifier().ok();// Parse hook type filter if providedlet filter: Option<HookType> = hook_type_filter.map(|s| match s {@@ -495,7 +499,7 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho// Render project hooksrender_project_hooks(&mut output,- &*workspace,+ &repo,project_config.as_ref(),&config,project_id.as_deref(),@@ -573,15 +577,15 @@ fn render_user_hooks(/// Render project hooks sectionfn render_project_hooks(out: &mut String,- workspace: &dyn Workspace,+ repo: &Repository,project_config: Option<&ProjectConfig>,user_config: &UserConfig,project_id: Option<&str>,filter: Option<HookType>,ctx: Option<&CommandContext>,) -> anyhow::Result<()> {- let root = workspace.root_path()?;- let config_path = root.join(".config").join("wt.toml");+ let repo_root = repo.current_worktree().root()?;+ let config_path = repo_root.join(".config").join("wt.toml");writeln!(out,@@ -685,7 +689,7 @@ fn render_hook_commands(/// Expand a command template with context variablesfn expand_command_template(template: &str, ctx: &CommandContext, hook_type: HookType) -> String {// Build extra vars based on hook type (same logic as run_hook approval)- let default_branch = ctx.workspace.default_branch_name();+ let default_branch = ctx.repo.default_branch();let extra_vars: Vec<(&str, &str)> = match hook_type {HookType::PreCommit => {// Pre-commit uses default branch as target (for comparison context)@@ -706,10 +710,9 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();- let worktree_map = build_worktree_map(ctx.workspace);// Use the standard template expansion (shell-escaped)// On any error, show both the template and error message- worktrunk::config::expand_template(template, &vars, true, &worktree_map, "hook preview")+ worktrunk::config::expand_template(template, &vars, true, ctx.repo, "hook preview").unwrap_or_else(|err| format!("# Template error: {}\n{}", err, template))}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex f58c91e6f..ef7811163 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -222,7 +222,7 @@ pub fn spawn_background_hooks(let hook_log = HookLog::hook(cmd.source, cmd.hook_type, &name);if let Err(err) = spawn_detached(- &ctx.workspace.wt_logs_dir(),+ ctx.repo,ctx.worktree_path,&cmd.prepared.expanded,ctx.branch_or_head(),@@ -424,7 +424,7 @@ pub fn execute_hook(name_filter: Option<&str>,display_path: Option<&Path>,) -> anyhow::Result<()> {- let project_config = ctx.workspace.load_project_config()?;+ let project_config = ctx.repo.load_project_config()?;let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());let (user_config, proj_config) =lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);@@ -457,7 +457,7 @@ pub(crate) fn prepare_background_hooks(extra_vars: &[(&str, &str)],display_path: Option<&Path>,) -> anyhow::Result<Vec<SourcedCommand>> {- let project_config = ctx.workspace.load_project_config()?;+ let project_config = ctx.repo.load_project_config()?;let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());let (user_config, proj_config) =lookup_hook_configs(&user_hooks, project_config.as_ref(), hook_type);diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex c89634036..681d93e3f 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -10,7 +10,6 @@ use std::sync::Arc;use crossbeam_channel as chan;use worktrunk::git::{BranchRef, Repository, WorktreeInfo};-use worktrunk::workspace::build_worktree_map;use super::CollectOptions;use super::tasks::{@@ -154,15 +153,8 @@ pub fn work_items_for_worktree(wt.branch.as_ref().and_then(|branch| {let mut vars = std::collections::HashMap::new();vars.insert("branch", branch.as_str());- let worktree_map = build_worktree_map(repo);- worktrunk::config::expand_template(- template,- &vars,- false,- &worktree_map,- "url-template",- )- .ok()+ worktrunk::config::expand_template(template, &vars, false, repo, "url-template")+ .ok()})})} else {diff --git a/src/commands/list/collect_jj.rs b/src/commands/list/collect_jj.rsdeleted file mode 100644index 075b8e014..000000000--- a/src/commands/list/collect_jj.rs+++ /dev/null@@ -1,146 +0,0 @@-//! Jujutsu workspace data collection for `wt list`.-//!-//! Simpler than the git collection path: sequential execution, no progressive-//! rendering. jj repos typically have few workspaces (1-5), so parallelism-//! isn't needed for acceptable latency.--use worktrunk::workspace::{JjWorkspace, Workspace, WorkspaceItem};--use super::model::item::{DisplayFields, ItemKind, ListData, ListItem, WorktreeData};-use super::model::stats::{AheadBehind, CommitDetails};--/// Collect workspace data from a jj repository.-///-/// Returns `ListData` compatible with the existing rendering pipeline.-/// Fields not applicable to jj (upstream, CI, branch diff) are left as None.-pub fn collect_jj(workspace: &JjWorkspace) -> anyhow::Result<ListData> {- let workspaces = workspace.list_workspaces()?;-- // Determine current workspace by matching cwd- let cwd = dunce::canonicalize(std::env::current_dir()?)?;-- let mut items: Vec<ListItem> = Vec::with_capacity(workspaces.len());-- for ws in &workspaces {- let is_current = dunce::canonicalize(&ws.path)- .map(|p| cwd.starts_with(&p))- .unwrap_or(false);-- let mut item = build_jj_item(ws, is_current);-- // Collect status data (sequential — few workspaces expected)- populate_jj_item(workspace, ws, &mut item);-- // Compute status symbols with available data- item.compute_status_symbols(None, false, None, None, false);- item.finalize_display();-- items.push(item);- }-- // Sort: current first, then default, then by name- items.sort_by(|a, b| {- let a_current = a.worktree_data().is_some_and(|d| d.is_current);- let b_current = b.worktree_data().is_some_and(|d| d.is_current);- let a_main = a.worktree_data().is_some_and(|d| d.is_main);- let b_main = b.worktree_data().is_some_and(|d| d.is_main);-- b_current- .cmp(&a_current)- .then(b_main.cmp(&a_main))- .then(a.branch_name().cmp(b.branch_name()))- });-- let main_path = workspace- .default_workspace_path()?- .unwrap_or_else(|| workspace.root().to_path_buf());-- Ok(ListData {- items,- main_worktree_path: main_path,- })-}--/// Build a minimal ListItem for a jj workspace.-fn build_jj_item(ws: &WorkspaceItem, is_current: bool) -> ListItem {- ListItem {- head: ws.head.clone(),- // Use workspace name as the "branch" for display purposes- branch: Some(ws.name.clone()),- commit: None,- counts: None,- branch_diff: None,- committed_trees_match: None,- has_file_changes: None,- would_merge_add: None,- is_ancestor: None,- is_orphan: None,- upstream: None,- pr_status: None,- url: None,- url_active: None,- status_symbols: None,- display: DisplayFields::default(),- kind: ItemKind::Worktree(Box::new(WorktreeData {- path: ws.path.clone(),- detached: false,- locked: ws.locked.clone(),- prunable: ws.prunable.clone(),- is_main: ws.is_default,- is_current,- is_previous: false,- ..Default::default()- })),- }-}--/// Populate computed fields for a jj workspace item.-///-/// Collects working tree diff, ahead/behind counts, and integration status.-/// Errors are logged but don't fail the overall collection.-fn populate_jj_item(workspace: &JjWorkspace, ws: &WorkspaceItem, item: &mut ListItem) {- // Skip status collection for the default workspace if it's the trunk target- let is_main = ws.is_default;-- // Working tree diff- match workspace.working_diff(&ws.path) {- Ok(diff) => {- if let ItemKind::Worktree(ref mut data) = item.kind {- data.working_tree_diff = Some(diff);- }- }- Err(e) => log::debug!("Failed to get working diff for {}: {}", ws.name, e),- }-- // Ahead/behind vs trunk (skip for default workspace)- if !is_main {- // Use trunk() revset as base, workspace change ID as head- match workspace.ahead_behind("trunk()", &ws.head) {- Ok((ahead, behind)) => {- item.counts = Some(AheadBehind { ahead, behind });- }- Err(e) => log::debug!("Failed to get ahead/behind for {}: {}", ws.name, e),- }-- // Integration check- match workspace.is_integrated(&ws.head, "trunk()") {- Ok(reason) => {- if reason.is_some() {- item.is_ancestor = Some(true);- }- }- Err(e) => log::debug!("Failed integration check for {}: {}", ws.name, e),- }- }-- // Commit details (timestamp + description)- match workspace.commit_details(&ws.path) {- Ok((timestamp, commit_message)) => {- item.commit = Some(CommitDetails {- timestamp,- commit_message,- });- }- Err(e) => log::debug!("Failed to get commit details for {}: {}", ws.name, e),- }-}diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 87f70dc78..6a543b7a3 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -120,7 +120,6 @@pub mod ci_status;pub(crate) mod collect;-mod collect_jj;pub(crate) mod columns;pub mod json_output;pub(crate) mod layout;@@ -141,7 +140,6 @@ use model::{ListData, ListItem};use progressive::RenderMode;use worktrunk::git::Repository;use worktrunk::styling::INFO_SYMBOL;-use worktrunk::workspace::JjWorkspace;use collect::TaskKind;@@ -149,91 +147,7 @@ use collect::TaskKind;pub use collect::{CollectOptions, build_worktree_item, populate_item};pub use model::StatuslineSegment;-/// Handle `wt list` command.-///-/// `branches`, `remotes`, `full` are raw CLI flags (false when not passed).-/// Config resolution (project-specific merged with global) happens internally-/// using the workspace's project identifier.pub fn handle_list(- format: crate::OutputFormat,- branches: bool,- remotes: bool,- full: bool,- render_mode: RenderMode,- config: &worktrunk::config::UserConfig,-) -> anyhow::Result<()> {- // Open workspace once, route by VCS type via downcast- let workspace = worktrunk::workspace::open_workspace()?;- if workspace.as_any().downcast_ref::<Repository>().is_none() {- return handle_list_jj(format);- }-- // Resolve config using workspace's project identifier (avoids extra Repository::current())- let project_id = workspace.project_identifier().ok();- let resolved = config.resolved(project_id.as_deref());-- // CLI flags override config values- let show_branches = branches || resolved.list.branches();- let show_remotes = remotes || resolved.list.remotes();- let show_full = full || resolved.list.full();-- handle_list_git(- format,- show_branches,- show_remotes,- show_full,- render_mode,- config,- )-}--/// Handle `wt list` for jj repositories.-fn handle_list_jj(format: crate::OutputFormat) -> anyhow::Result<()> {- let workspace = JjWorkspace::from_current_dir()?;- let list_data = collect_jj::collect_jj(&workspace)?;- let items = &list_data.items;-- match format {- crate::OutputFormat::Json => {- let json_items = json_output::to_json_items(items);- let json =- serde_json::to_string_pretty(&json_items).context("Failed to serialize to JSON")?;- println!("{}", json);- }- crate::OutputFormat::Table | crate::OutputFormat::ClaudeCode => {- // For jj: render table in buffered mode (no progressive rendering)- let skip_tasks: HashSet<TaskKind> = [- TaskKind::BranchDiff,- TaskKind::CiStatus,- TaskKind::WorkingTreeConflicts,- TaskKind::Upstream,- TaskKind::MergeTreeConflicts,- ]- .into_iter()- .collect();-- let layout = layout::calculate_layout_from_basics(- items,- &skip_tasks,- &list_data.main_worktree_path,- None,- );-- println!("{}", layout.format_header_line());- for item in items {- println!("{}", layout.format_list_item_line(item));- }-- let summary = format_summary_message(items, false, layout.hidden_column_count, 0, 0);- println!("{}", summary);- }- }-- Ok(())-}--/// Handle `wt list` for git repositories (existing behavior).-fn handle_list_git(format: crate::OutputFormat,show_branches: bool,show_remotes: bool,diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 7220d9579..5eee90b03 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,10 +1,8 @@use anyhow::Context;-use color_print::cformat;use worktrunk::HookType;use worktrunk::config::UserConfig;-use worktrunk::git::{GitError, Repository};-use worktrunk::styling::{eprintln, info_message, success_message};-use worktrunk::workspace::LocalPushDisplay;+use worktrunk::git::Repository;+use worktrunk::styling::{eprintln, info_message};use super::command_approval::approve_command_batch;use super::command_executor::CommandContext;@@ -12,7 +10,10 @@ use super::commit::CommitOptions;use super::context::CommandEnv;use super::hooks::{HookFailureStrategy, execute_hook};use super::project_config::{HookCommand, collect_commands_for_hooks};-use super::worktree::{BranchDeletionMode, RemoveResult, get_path_mismatch};+use super::repository_ext::RepositoryCliExt;+use super::worktree::{+ BranchDeletionMode, MergeOperations, RemoveResult, get_path_mismatch, handle_push,+};/// Options for the merge command///@@ -76,12 +77,6 @@ fn collect_merge_commands(}pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {- // Open workspace once, route by VCS type via downcast- let workspace = worktrunk::workspace::open_workspace()?;- if workspace.as_any().downcast_ref::<Repository>().is_none() {- return super::handle_merge_jj::handle_merge_jj(opts);- }-let MergeOptions {target,squash: squash_opt,@@ -100,8 +95,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let _ = crate::output::prompt_commit_generation(&mut config);}- let env = CommandEnv::with_workspace(workspace, "merge", config)?;- let repo = env.require_repo()?;+ let env = CommandEnv::for_action("merge", config)?;+ let repo = &env.repo;let config = &env.config;// Merge requires being on a branch (can't merge from detached HEAD)let current_branch = env.require_branch("merge")?.to_string();@@ -223,95 +218,16 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {)?;}- // Build operations note for the progress line (e.g., " (no commit/squash needed)")- let operations_note = {- let mut skipped_ops = Vec::new();- if !committed && !squashed {- skipped_ops.push("commit/squash");- }- if !rebased {- skipped_ops.push("rebase");- }- if skipped_ops.is_empty() {- String::new()- } else {- format!(" (no {} needed)", skipped_ops.join("/"))- }- };-- // Local push: advance target branch ref to include feature commits- let push_result = env- .workspace- .local_push(- &target_branch,- &env.worktree_path,- LocalPushDisplay {- verb: "Merging",- notes: &operations_note,- },- )- .map_err(|e| {- // Rewrite NotFastForward hint for merge context- if let Some(GitError::NotFastForward {- target_branch,- commits_formatted,- ..- }) = e.downcast_ref::<GitError>()- {- return GitError::NotFastForward {- target_branch: target_branch.clone(),- commits_formatted: commits_formatted.clone(),- in_merge_context: true,- }- .into();- }- e- })?;-- // Format merge-specific success/info message- if push_result.commit_count > 0 {- let mut summary_parts = vec![format!(- "{} commit{}",- push_result.commit_count,- if push_result.commit_count == 1 {- ""- } else {- "s"- }- )];- summary_parts.extend(push_result.stats_summary);-- let stats_str = summary_parts.join(", ");- let paren_close = cformat!("<bright-black>)</>");- eprintln!(- "{}",- success_message(cformat!(- "Merged to <bold>{target_branch}</> <bright-black>({stats_str}</>{}",- paren_close- ))- );- } else {- // Explain why nothing was pushed- let mut notes = Vec::new();- if !committed && !squashed {- notes.push("no new commits");- }- if !rebased {- notes.push("no rebase needed");- }- let context = if notes.is_empty() {- String::new()- } else {- format!(" ({})", notes.join(", "))- };-- eprintln!(- "{}",- info_message(cformat!(- "Already up to date with <bold>{target_branch}</>{context}"- ))- );- }+ // Fast-forward push to target branch with commit/squash/rebase info for consolidated message+ handle_push(+ Some(&target_branch),+ "Merged to",+ Some(MergeOperations {+ committed,+ squashed,+ rebased,+ }),+ )?;// Destination: prefer the target branch's worktree; fall back to home path.let destination_path = match target_worktree_path {diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 24fb24aa3..a814e485f 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -6,11 +6,7 @@ pub(crate) mod config;pub(crate) mod configure_shell;pub(crate) mod context;mod for_each;-mod handle_merge_jj;-pub(crate) mod handle_remove_jj;-pub(crate) mod handle_step_jj;mod handle_switch;-mod handle_switch_jj;mod hook_commands;mod hook_filter;pub(crate) mod hooks;@@ -20,7 +16,6 @@ pub(crate) mod merge;pub(crate) mod process;pub(crate) mod project_config;mod relocate;-mod remove_command;pub(crate) mod repository_ext;#[cfg(unix)]pub(crate) mod select;@@ -42,36 +37,22 @@ pub(crate) use hook_commands::{add_approvals, clear_approvals, handle_hook_show,pub(crate) use init::{handle_completions, handle_init};pub(crate) use list::handle_list;pub(crate) use merge::{MergeOptions, handle_merge};-pub(crate) use remove_command::{RemoveOptions, handle_remove_command};#[cfg(unix)]pub(crate) use select::handle_select;pub(crate) use step_commands::{RebaseResult, SquashResult, handle_rebase, handle_squash, step_commit, step_copy_ignored,- step_push, step_relocate, step_show_squash_prompt,+ step_relocate, step_show_squash_prompt,+};+pub(crate) use worktree::{+ OperationMode, handle_remove, handle_remove_current, is_worktree_at_expected_path,+ resolve_worktree_arg, worktree_display_name,};-pub(crate) use worktree::{is_worktree_at_expected_path, worktree_display_name};// Re-export Shell from the canonical locationpub(crate) use worktrunk::shell::Shell;use color_print::cformat;-use worktrunk::git::Repository;-use worktrunk::workspace::Workspace;--/// Downcast a workspace to `Repository`, or error for jj repositories.-///-/// Replaces the old `require_git()` + `Repository::current()` two-step pattern.-/// Returns a reference to the `Repository` if this is a git workspace,-/// or a clear error for jj users.-pub(crate) fn require_git_workspace<'a>(- workspace: &'a dyn Workspace,- command: &str,-) -> anyhow::Result<&'a Repository> {- workspace- .as_any()- .downcast_ref::<Repository>()- .ok_or_else(|| anyhow::anyhow!("`wt {command}` is not yet supported for jj repositories"))-}+use worktrunk::styling::{eprintln, format_with_gutter};/// Format command execution label with optional command name.///@@ -85,6 +66,35 @@ pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> St}}+/// Show detailed diffstat for a given commit range.+///+/// Displays the diff statistics (file changes, insertions, deletions) in a gutter format.+/// Used after commit/squash to show what was included in the commit.+///+/// # Arguments+/// * `repo` - The repository to query+/// * `range` - The commit range to diff (e.g., "HEAD~1..HEAD" or "main..HEAD")+pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::Result<()> {+ let term_width = crate::display::get_terminal_width();+ let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);+ let diff_stat = repo+ .run_command(&[+ "diff",+ "--color=always",+ "--stat",+ &format!("--stat-width={}", stat_width),+ range,+ ])?+ .trim_end()+ .to_string();++ if !diff_stat.is_empty() {+ eprintln!("{}", format_with_gutter(&diff_stat, None));+ }++ Ok(())+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/commands/process.rs b/src/commands/process.rsindex 53f8f8487..bcdd4a6f5 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -7,7 +7,7 @@ use std::process::Command;use std::process::Stdio;use std::str::FromStr;use strum::IntoEnumIterator;-use worktrunk::git::HookType;+use worktrunk::git::{HookType, Repository};use worktrunk::path::{format_path_for_display, sanitize_for_filename};use crate::commands::hook_filter::HookSource;@@ -187,7 +187,7 @@ fn posix_command_separator(command: &str) -> &'static str {/// Logs are centralized in the main worktree's `.git/wt-logs/` directory.////// # Arguments-/// * `log_dir` - Directory for background hook log files+/// * `repo` - Repository instance for accessing git common directory/// * `worktree_path` - Working directory for the command/// * `command` - Shell command to execute/// * `branch` - Branch name for log organization@@ -197,23 +197,24 @@ fn posix_command_separator(command: &str) -> &'static str {/// # Returns/// Path to the log file where output is being writtenpub fn spawn_detached(- log_dir: &Path,+ repo: &Repository,worktree_path: &Path,command: &str,branch: &str,hook_log: &HookLog,context_json: Option<&str>,) -> anyhow::Result<std::path::PathBuf> {- // Create log directory- fs::create_dir_all(log_dir).with_context(|| {+ // Create log directory in the common git directory+ let log_dir = repo.wt_logs_dir();+ fs::create_dir_all(&log_dir).with_context(|| {format!("Failed to create log directory {}",- format_path_for_display(log_dir)+ format_path_for_display(&log_dir))})?;// Generate log path using the HookLog specification- let log_path = hook_log.path(log_dir, branch);+ let log_path = hook_log.path(&log_dir, branch);// Create log filelet log_file = fs::File::create(&log_path).with_context(|| {diff --git a/src/commands/remove_command.rs b/src/commands/remove_command.rsdeleted file mode 100644index 6839950ff..000000000--- a/src/commands/remove_command.rs+++ /dev/null@@ -1,256 +0,0 @@-//! Remove command handler.-//!-//! Orchestrates worktree removal for both git and jj repositories.-//! Handles single and multi-worktree removal, hook approval, and cleanup.--use std::collections::HashSet;--use anyhow::Context;-use worktrunk::HookType;-use worktrunk::config::UserConfig;-use worktrunk::git::{Repository, ResolvedWorktree};-use worktrunk::styling::{eprintln, info_message, warning_message};--use super::command_approval::approve_hooks;-use super::context::CommandEnv;-use super::worktree::{- OperationMode, RemoveResult, handle_remove, handle_remove_current, resolve_worktree_arg,-};-use crate::output::handle_remove_output;--/// Options for the remove command.-pub struct RemoveOptions {- pub branches: Vec<String>,- pub delete_branch: bool,- pub force_delete: bool,- pub foreground: bool,- pub no_background: bool,- pub verify: bool,- pub yes: bool,- pub force: bool,-}--/// Handle the `wt remove` command.-///-/// Orchestrates worktree removal: VCS detection, validation, hook approval,-/// and execution. Supports both single and multi-worktree removal.-pub fn handle_remove_command(opts: RemoveOptions) -> anyhow::Result<()> {- let RemoveOptions {- branches,- delete_branch,- force_delete,- foreground,- no_background,- verify,- yes,- force,- } = opts;-- let config = UserConfig::load().context("Failed to load config")?;-- // Open workspace once, route by VCS type via downcast- let workspace = worktrunk::workspace::open_workspace()?;- let Some(repo) = workspace.as_any().downcast_ref::<Repository>() else {- // JJ path: resolve targets, approve hooks, remove each workspace- let cwd = std::env::current_dir()?;- let targets = if branches.is_empty() {- let name = workspace- .current_name(&cwd)?- .ok_or_else(|| anyhow::anyhow!("Not inside a jj workspace"))?;- vec![name]- } else {- branches- };-- let run_hooks = approve_remove_hooks(verify, yes)?;-- for name in &targets {- let ws_path = workspace.workspace_path(name)?;- super::handle_remove_jj::remove_jj_workspace_and_cd(- &*workspace,- name,- &ws_path,- run_hooks,- yes,- )?;- }- return Ok(());- };-- // Handle deprecated --no-background flag- if no_background {- eprintln!(- "{}",- warning_message("--no-background is deprecated; use --foreground instead")- );- }- let background = !(foreground || no_background);-- // Validate conflicting flags- if !delete_branch && force_delete {- return Err(worktrunk::git::GitError::Other {- message: "Cannot use --force-delete with --no-delete-branch".into(),- }- .into());- }-- if branches.is_empty() {- // Single worktree removal: validate FIRST, then approve, then execute- let result = handle_remove_current(!delete_branch, force_delete, force, &config)- .context("Failed to remove worktree")?;-- // Early exit for benchmarking time-to-first-output- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return Ok(());- }-- // "Approve at the Gate": approval happens AFTER validation passes- let run_hooks = approve_remove_hooks(verify, yes)?;-- handle_remove_output(&result, background, run_hooks)- } else {- // Multi-worktree removal: validate ALL first, then approve, then execute- // This supports partial success - some may fail validation while others succeed.- let current_worktree = repo- .current_worktree()- .root()- .ok()- .and_then(|p| dunce::canonicalize(&p).ok());-- // Dedupe inputs to avoid redundant planning/execution- let branches: Vec<_> = {- let mut seen = HashSet::new();- branches- .into_iter()- .filter(|b| seen.insert(b.clone()))- .collect()- };-- // Phase 1: Validate all targets (resolution + preparation)- // Store successful plans for execution after approval- let mut plans_others: Vec<RemoveResult> = Vec::new();- let mut plans_branch_only: Vec<RemoveResult> = Vec::new();- let mut plan_current: Option<RemoveResult> = None;- let mut all_errors: Vec<anyhow::Error> = Vec::new();-- // Helper: record error and continue- let mut record_error = |e: anyhow::Error| {- eprintln!("{}", e);- all_errors.push(e);- };-- for branch_name in &branches {- // Resolve the target- let resolved =- match resolve_worktree_arg(repo, branch_name, &config, OperationMode::Remove) {- Ok(r) => r,- Err(e) => {- record_error(e);- continue;- }- };-- match resolved {- ResolvedWorktree::Worktree { path, branch } => {- // Use canonical paths to avoid symlink/normalization mismatches- let path_canonical = dunce::canonicalize(&path).unwrap_or(path);- let is_current = current_worktree.as_ref() == Some(&path_canonical);-- if is_current {- // Current worktree - use handle_remove_current for detached HEAD- match handle_remove_current(!delete_branch, force_delete, force, &config) {- Ok(result) => plan_current = Some(result),- Err(e) => record_error(e),- }- continue;- }-- // Non-current worktree - branch is always Some because:- // - "@" resolves to current worktree (handled by is_current branch above)- // - Other names resolve via resolve_worktree_arg which always sets branch: Some(...)- let branch_for_remove = branch.as_ref().unwrap();-- match handle_remove(- branch_for_remove,- !delete_branch,- force_delete,- force,- &config,- ) {- Ok(result) => plans_others.push(result),- Err(e) => record_error(e),- }- }- ResolvedWorktree::BranchOnly { branch } => {- match handle_remove(&branch, !delete_branch, force_delete, force, &config) {- Ok(result) => plans_branch_only.push(result),- Err(e) => record_error(e),- }- }- }- }-- // If no valid plans, bail early (all failed validation)- let has_valid_plans =- !plans_others.is_empty() || !plans_branch_only.is_empty() || plan_current.is_some();- if !has_valid_plans {- anyhow::bail!("");- }-- // Early exit for benchmarking time-to-first-output- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {- return Ok(());- }-- // Phase 2: Approve hooks (only if we have valid plans)- // TODO(pre-remove-context): Approval context uses current worktree,- // but hooks execute in each target worktree.- let run_hooks = approve_remove_hooks(verify, yes)?;-- // Phase 3: Execute all validated plans- // Remove other worktrees first- for result in plans_others {- handle_remove_output(&result, background, run_hooks)?;- }-- // Handle branch-only cases- for result in plans_branch_only {- handle_remove_output(&result, background, run_hooks)?;- }-- // Remove current worktree last (if it was in the list)- if let Some(result) = plan_current {- handle_remove_output(&result, background, run_hooks)?;- }-- // Exit with failure if any validation errors occurred- if !all_errors.is_empty() {- anyhow::bail!("");- }-- Ok(())- }-}--/// Approve remove hooks if verification is enabled.-///-/// Shared between git and jj remove paths. Returns `true` if hooks should run.-fn approve_remove_hooks(verify: bool, yes: bool) -> anyhow::Result<bool> {- if !verify {- return Ok(false);- }- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- let approved = approve_hooks(- &ctx,- &[- HookType::PreRemove,- HookType::PostRemove,- HookType::PostSwitch,- ],- )?;- if !approved {- eprintln!("{}", info_message("Commands declined, continuing removal"));- }- Ok(approved)-}diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 04a901ab8..660e6b4c8 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -1,8 +1,16 @@+use std::path::{Path, PathBuf};+use std::process;+use std::time::{SystemTime, UNIX_EPOCH};+use super::worktree::{BranchDeletionMode, RemoveResult, get_path_mismatch};-use anyhow::Context;+use anyhow::{Context, bail};+use color_print::cformat;use worktrunk::config::UserConfig;-use worktrunk::git::{GitError, IntegrationReason, Repository, parse_untracked_files};-use worktrunk::styling::{eprintln, format_with_gutter, warning_message};+use worktrunk::git::{+ GitError, IntegrationReason, Repository, parse_porcelain_z, parse_untracked_files,+};+use worktrunk::path::format_path_for_display;+use worktrunk::styling::{eprintln, format_with_gutter, progress_message, warning_message};/// Target for worktree removal.#[derive(Debug)]@@ -33,6 +41,23 @@ pub trait RepositoryCliExt {force_worktree: bool,config: &UserConfig,) -> anyhow::Result<RemoveResult>;++ /// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.+ fn prepare_target_worktree(+ &self,+ target_worktree: Option<&PathBuf>,+ target_branch: &str,+ ) -> anyhow::Result<Option<TargetWorktreeStash>>;++ /// Check if HEAD is a linear extension of the target branch.+ ///+ /// Returns true when:+ /// 1. The merge-base equals target's SHA (target hasn't advanced), AND+ /// 2. There are no merge commits between target and HEAD (history is linear)+ ///+ /// This detects branches that have merged the target into themselves — such+ /// branches need rebasing to linearize history even though merge-base equals target.+ fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool>;}impl RepositoryCliExt for Repository {@@ -197,6 +222,119 @@ impl RepositoryCliExt for Repository {removed_commit,})}++ fn prepare_target_worktree(+ &self,+ target_worktree: Option<&PathBuf>,+ target_branch: &str,+ ) -> anyhow::Result<Option<TargetWorktreeStash>> {+ let Some(wt_path) = target_worktree else {+ return Ok(None);+ };++ // Skip if target worktree directory is missing (prunable worktree)+ if !wt_path.exists() {+ return Ok(None);+ }++ let wt = self.worktree_at(wt_path);+ if !wt.is_dirty()? {+ return Ok(None);+ }++ let push_files = self.changed_files(target_branch, "HEAD")?;+ // Use -z for NUL-separated output: handles filenames with spaces and renames correctly+ // Format: "XY path\0" for normal files, "XY new_path\0old_path\0" for renames/copies+ let wt_status_output = wt.run_command(&["status", "--porcelain", "-z"])?;++ let wt_files: Vec<String> = parse_porcelain_z(&wt_status_output);++ let overlapping: Vec<String> = push_files+ .iter()+ .filter(|f| wt_files.contains(f))+ .cloned()+ .collect();++ if !overlapping.is_empty() {+ return Err(GitError::ConflictingChanges {+ target_branch: target_branch.to_string(),+ files: overlapping,+ worktree_path: wt_path.clone(),+ }+ .into());+ }++ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos();+ let stash_name = format!(+ "worktrunk autostash::{}::{}::{}",+ target_branch,+ process::id(),+ nanos+ );++ eprintln!(+ "{}",+ progress_message(cformat!(+ "Stashing changes in <bold>{}</>...",+ format_path_for_display(wt_path)+ ))+ );++ // Stash all changes including untracked files.+ // Note: git stash push returns exit code 0 whether or not anything was stashed.+ wt.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;++ // Verify stash was created by checking the stash list for our entry.+ let list_output = wt.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;+ let mut parts = list_output.split('\0');+ while let Some(id) = parts.next() {+ if id.is_empty() {+ continue;+ }+ if let Some(message) = parts.next()+ && (message == stash_name || message.ends_with(&stash_name))+ {+ return Ok(Some(TargetWorktreeStash::new(wt_path, id.to_string())));+ }+ }++ // Stash entry not found. Verify the worktree is now clean — if it's still+ // dirty, stashing may have failed silently or our lookup missed the entry.+ if wt.is_dirty()? {+ bail!(+ "Failed to stash changes in {}; worktree still has uncommitted changes. \+ Expected stash entry: '{}'. Check 'git stash list'.",+ format_path_for_display(wt_path),+ stash_name+ );+ }++ // Worktree is clean and no stash entry — nothing needed to be stashed+ Ok(None)+ }++ fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {+ // Orphan branches have no common ancestor, so they can't be "rebased onto" target+ let Some(merge_base) = self.merge_base("HEAD", target)? else {+ return Ok(false);+ };+ let target_sha = self.run_command(&["rev-parse", target])?.trim().to_string();++ if merge_base != target_sha {+ return Ok(false); // Target has advanced past merge-base+ }++ // Check for merge commits — if present, history is not linear+ let merge_commits = self+ .run_command(&["rev-list", "--merges", &format!("{}..HEAD", target)])?+ .trim()+ .to_string();++ Ok(merge_commits.is_empty())+ }}/// Compute integration reason for branch deletion.@@ -246,10 +384,89 @@ fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {Ok(())}+/// Stash guard that auto-restores on drop.+///+/// Created by `prepare_target_worktree()` when the target worktree has changes+/// that don't conflict with the push. Automatically restores the stash when+/// dropped, ensuring cleanup happens in both success and error paths.+#[must_use = "stash guard restores immediately if dropped; hold it until push completes"]+pub(crate) struct TargetWorktreeStash {+ /// Inner data wrapped in Option so we can take() in Drop.+ /// None means already restored (or disarmed).+ inner: Option<StashData>,+}++struct StashData {+ path: PathBuf,+ stash_ref: String,+}++impl StashData {+ /// Restore the stash, printing progress and warning on failure.+ fn restore(self) {+ eprintln!(+ "{}",+ progress_message(cformat!(+ "Restoring stashed changes in <bold>{}</>...",+ format_path_for_display(&self.path)+ ))+ );++ // Don't use --quiet so git shows conflicts if any+ let success = Repository::current()+ .ok()+ .and_then(|repo| {+ repo.worktree_at(&self.path)+ .run_command(&["stash", "pop", &self.stash_ref])+ .ok()+ })+ .is_some();++ if !success {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Failed to restore stash <bold>{stash_ref}</>; run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",+ stash_ref = self.stash_ref,+ path = format_path_for_display(&self.path),+ ))+ );+ }+ }+}++impl Drop for TargetWorktreeStash {+ fn drop(&mut self) {+ if let Some(data) = self.inner.take() {+ data.restore();+ }+ }+}++impl TargetWorktreeStash {+ pub(crate) fn new(path: &Path, stash_ref: String) -> Self {+ Self {+ inner: Some(StashData {+ path: path.to_path_buf(),+ stash_ref,+ }),+ }+ }++ /// Explicitly restore the stash now, preventing Drop from restoring again.+ ///+ /// Use this when you need the restore to happen at a specific point+ /// (e.g., before a success message). Drop handles errors/early returns.+ pub(crate) fn restore_now(&mut self) {+ if let Some(data) = self.inner.take() {+ data.restore();+ }+ }+}+#[cfg(test)]mod tests {use super::*;- use worktrunk::git::parse_porcelain_z;#[test]fn test_parse_porcelain_z_modified_staged() {@@ -398,4 +615,35 @@ mod tests {// All files are tracked (modified, staged, etc.)assert!(parse_untracked_files(" M file1.txt\0M file2.txt\0").is_empty());}++ #[test]+ fn test_stash_guard_restore_now_clears_inner() {+ // Create a guard - note: this doesn't actually create a stash since we're not+ // in a real git repo with that stash ref. We're just testing the state machine.+ let mut guard = TargetWorktreeStash::new(std::path::Path::new("/tmp"), "stash@{0}".into());++ // Inner should be populated+ assert!(guard.inner.is_some());++ // restore_now() should clear inner (the restore itself will fail since no real repo,+ // but that's expected - we're testing the state transition)+ guard.restore_now();++ // Inner should now be None+ assert!(guard.inner.is_none());++ // Calling restore_now() again is a no-op+ guard.restore_now();+ assert!(guard.inner.is_none());+ }++ #[test]+ fn test_stash_guard_drop_clears_inner() {+ // Test that Drop also consumes the inner+ let guard = TargetWorktreeStash::new(std::path::Path::new("/tmp"), "stash@{0}".into());++ // Just drop it - the restore will fail (no real repo) but Drop shouldn't panic+ drop(guard);+ // If we get here, Drop worked without panicking+ }}diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rsindex 0406b2853..a9e76956f 100644--- a/src/commands/select/mod.rs+++ b/src/commands/select/mod.rs@@ -14,37 +14,31 @@ use anyhow::Context;use dashmap::DashMap;use skim::prelude::*;use worktrunk::config::UserConfig;+use worktrunk::git::Repository;use super::handle_switch::{approve_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,};use super::list::collect;-use super::worktree::{execute_switch, plan_switch, resolve_path_mismatch};+use super::worktree::{+ SwitchBranchInfo, SwitchResult, execute_switch, get_path_mismatch, plan_switch,+};use crate::output::handle_switch_output;use items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};use preview::{PreviewLayout, PreviewMode, PreviewState};-/// Handle the interactive select/switch picker.-///-/// `branches` and `remotes` are raw CLI flags (false when not passed).-/// Config resolution (project-specific merged with global) happens internally.-pub fn handle_select(branches: bool, remotes: bool, config: &UserConfig) -> anyhow::Result<()> {+pub fn handle_select(+ show_branches: bool,+ show_remotes: bool,+ config: &UserConfig,+) -> anyhow::Result<()> {// Interactive picker requires a terminal for the TUIif !std::io::stdin().is_terminal() {anyhow::bail!("Interactive picker requires an interactive terminal");}- let workspace = worktrunk::workspace::open_workspace()?;- let repo = crate::commands::require_git_workspace(&*workspace, "select")?;-- // Resolve config using workspace's project identifier (avoids extra Repository::current())- let project_id = workspace.project_identifier().ok();- let resolved = config.resolved(project_id.as_deref());-- // CLI flags override config values- let show_branches = branches || resolved.list.branches();- let show_remotes = remotes || resolved.list.remotes();+ let repo = Repository::current()?;// Initialize preview mode state file (auto-cleanup on drop)let state = PreviewState::new();@@ -66,7 +60,7 @@ pub fn handle_select(branches: bool, remotes: bool, config: &UserConfig) -> anyhlet command_timeout = Some(std::time::Duration::from_millis(500));let Some(list_data) = collect::collect(- repo,+ &repo,show_branches,show_remotes,&skip_tasks,@@ -160,10 +154,6 @@ pub fn handle_select(branches: bool, remotes: bool, config: &UserConfig) -> anyh// Configure skim options with Rust-based preview and mode switching keybindingslet options = SkimOptionsBuilder::default().height("90%".to_string())- // Workaround for skim-tuikit bug: partial-height mode skips smcup but- // cleanup still sends rmcup, leaving artifacts. no_clear_start forces- // cursor_goto + erase_down cleanup instead. See skim-rs/skim#880.- .no_clear_start(true).layout("reverse".to_string()).header_lines(1) // Make first line (header) non-selectable.multi(false)@@ -281,17 +271,26 @@ pub fn handle_select(branches: bool, remotes: bool, config: &UserConfig) -> anyh(selected.output().to_string(), false)};- // Load config (fresh load for switch operation)+ // Load configlet config = UserConfig::load().context("Failed to load config")?;+ let repo = Repository::current().context("Failed to switch worktree")?;// Switch to existing worktree or create new one- let plan = plan_switch(repo, &identifier, should_create, None, false, &config)?;- let skip_hooks = !approve_switch_hooks(repo, &config, &plan, false, true)?;- let (result, branch_info) = execute_switch(repo, plan, &config, false, skip_hooks)?;-- // Compute path mismatch lazily (deferred from plan_switch for existing worktrees).- // No early exit here — select's TUI already dominates latency.- let branch_info = resolve_path_mismatch(branch_info, &result, repo, &config);+ let plan = plan_switch(&repo, &identifier, should_create, None, false, &config)?;+ let skip_hooks = !approve_switch_hooks(&repo, &config, &plan, false, true)?;+ let (result, branch_info) = execute_switch(&repo, plan, &config, false, skip_hooks)?;++ // Compute path mismatch lazily (deferred from plan_switch for existing worktrees)+ let branch_info = match &result {+ SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {+ let expected_path = get_path_mismatch(&repo, &branch_info.branch, path, &config);+ SwitchBranchInfo {+ expected_path,+ ..branch_info+ }+ }+ _ => branch_info,+ };// Show success message; emit cd directive if shell integration is active// Interactive picker always performs cd (change_dir: true)@@ -304,7 +303,7 @@ pub fn handle_select(branches: bool, remotes: bool, config: &UserConfig) -> anyhif !skip_hooks {let extra_vars = switch_extra_vars(&result);spawn_switch_background_hooks(- repo,+ &repo,&config,&result,&branch_info.branch,diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 481242227..f1676c387 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -16,9 +16,7 @@ use ansi_str::AnsiStr;use anyhow::{Context, Result};use worktrunk::git::Repository;use worktrunk::styling::{fix_dim_after_color_reset, get_terminal_width, truncate_visible};-use worktrunk::workspace::open_workspace;-use super::list::columns::ColumnKind;use super::list::{self, CollectOptions, StatuslineSegment, json_output};use crate::cli::OutputFormat;@@ -199,28 +197,20 @@ pub fn run(format: OutputFormat) -> Result<()> {None};- // VCS status segments (skip links in claude-code mode - OSC 8 not supported)- if let Ok(workspace) = open_workspace() {- if let Some(repo) = workspace.as_any().downcast_ref::<Repository>() {- // Git path: full statusline with all git details- if repo.worktree_at(&cwd).git_dir().is_ok() {- let git_segments = get_git_status_segments(repo, &cwd, !claude_code)?;-- // In claude-code mode, skip branch segment if directory matches worktrunk template- let git_segments = if let Some(ref dir) = dir_str {- filter_redundant_branch(git_segments, dir)- } else {- git_segments- };-- segments.extend(git_segments);- }+ // Git status segments (skip links in claude-code mode - OSC 8 not supported)+ if let Ok(repo) = Repository::current()+ && repo.worktree_at(&cwd).git_dir().is_ok()+ {+ let git_segments = get_git_status_segments(&repo, &cwd, !claude_code)?;++ // In claude-code mode, skip branch segment if directory matches worktrunk template+ let git_segments = if let Some(ref dir) = dir_str {+ filter_redundant_branch(git_segments, dir)} else {- // jj path: show workspace name as branch segment- if let Ok(Some(name)) = workspace.current_name(&cwd) {- segments.push(StatuslineSegment::from_column(name, ColumnKind::Branch));- }- }+ git_segments+ };++ segments.extend(git_segments);}// Model name (claude-code mode only) - priority 1 (same as Branch)@@ -265,11 +255,7 @@ pub fn run(format: OutputFormat) -> Result<()> {fn run_json() -> Result<()> {let cwd = env::current_dir().context("Failed to get current directory")?;- let workspace = open_workspace().context("Not in a repository")?;- let repo = workspace- .as_any()- .downcast_ref::<Repository>()- .context("JSON statusline format is only supported for git repositories")?;+ let repo = Repository::current().context("Not in a git repository")?;// Verify we're in a worktreeif repo.worktree_at(&cwd).git_dir().is_err() {@@ -314,7 +300,7 @@ fn run_json() -> Result<()> {};// Populate computed fields (parallel git operations)- list::populate_item(repo, &mut item, options)?;+ list::populate_item(&repo, &mut item, options)?;// Convert to JSON formatlet json_item = json_output::JsonItem::from_list_item(&item);diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 1c77b2aa9..c88b5c252 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -15,18 +15,18 @@ use anyhow::Context;use color_print::cformat;use ignore::gitignore::GitignoreBuilder;use worktrunk::HookType;-use worktrunk::config::{CommitGenerationConfig, UserConfig};+use worktrunk::config::UserConfig;use worktrunk::git::Repository;use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,};-use worktrunk::workspace::{SquashOutcome, Workspace};use super::command_approval::approve_hooks;use super::commit::{CommitGenerator, CommitOptions, StageMode};use super::context::CommandEnv;use super::hooks::{HookFailureStrategy, run_hook_with_filter};use super::repository_ext::RepositoryCliExt;+use worktrunk::shell_exec::Cmd;/// Handle `wt step commit` command///@@ -37,47 +37,23 @@ pub fn step_commit(stage: Option<StageMode>,show_prompt: bool,) -> anyhow::Result<()> {- // --show-prompt is VCS-agnostic: build prompt from trait method and print+ // Handle --show-prompt early: just build and output the promptif show_prompt {- let ws = worktrunk::workspace::open_workspace()?;- let cwd = std::env::current_dir()?;+ let repo = worktrunk::git::Repository::current()?;let config = UserConfig::load().context("Failed to load config")?;- let project_id = ws.project_identifier().ok();+ let project_id = repo.project_identifier().ok();let commit_config = config.commit_generation(project_id.as_deref());-- let (diff, diff_stat) = ws.committable_diff_for_prompt(&cwd)?;- let branch = ws.current_name(&cwd)?.unwrap_or_else(|| "HEAD".to_string());- let repo_name = ws- .root_path()?- .file_name()- .and_then(|n| n.to_str().map(String::from))- .unwrap_or_else(|| "repo".to_string());- let recent_commits = ws.recent_subjects(None, 5);-- let input = crate::llm::CommitInput {- diff: &diff,- diff_stat: &diff_stat,- branch: &branch,- repo_name: &repo_name,- recent_commits: recent_commits.as_ref(),- };- let prompt = crate::llm::build_commit_prompt(&input, &commit_config)?;+ let prompt = crate::llm::build_commit_prompt(&commit_config)?;println!("{}", prompt);return Ok(());}- // Open workspace once, route by VCS type via downcast- let workspace = worktrunk::workspace::open_workspace()?;- if workspace.as_any().downcast_ref::<Repository>().is_none() {- return super::handle_step_jj::step_commit_jj();- }-// Load config once, run LLM setup prompt, then reuse configlet mut config = UserConfig::load().context("Failed to load config")?;// One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = CommandEnv::with_workspace(workspace, "commit", config)?;+ let env = CommandEnv::for_action("commit", config)?;let ctx = env.context(yes);// CLI flag overrides config value@@ -123,81 +99,6 @@ pub enum SquashResult {NoNetChanges,}-/// VCS-agnostic squash core: count, generate message, execute squash.-///-/// Used by both git and jj paths. Does NOT handle staging, hooks, safety backups,-/// or progress display — those are git-specific concerns in `handle_squash`.-pub(crate) fn do_squash(- workspace: &dyn Workspace,- target: &str,- path: &Path,- commit_gen_config: &CommitGenerationConfig,- branch_name: &str,- repo_name: &str,-) -> anyhow::Result<SquashResult> {- let feature_head = workspace.feature_head(path)?;-- // Check if already integrated- if workspace.is_integrated(&feature_head, target)?.is_some() {- return Ok(SquashResult::NoCommitsAhead(target.to_string()));- }-- let (ahead, _) = workspace.ahead_behind(target, &feature_head)?;-- if ahead == 0 {- return Ok(SquashResult::NoCommitsAhead(target.to_string()));- }-- if ahead == 1 && !workspace.is_dirty(path)? {- return Ok(SquashResult::AlreadySingleCommit);- }-- // Gather data for message generation- let subjects = workspace.commit_subjects(target, &feature_head)?;- let (diff, diff_stat) = workspace.diff_for_prompt(target, &feature_head, path)?;- let recent_commits = workspace.recent_subjects(Some(target), 5);-- // Generate squash commit message- eprintln!(- "{}",- progress_message("Generating squash commit message...")- );-- let generator = CommitGenerator::new(commit_gen_config);- generator.emit_hint_if_needed();-- let input = crate::llm::SquashInput {- target_branch: target,- diff: &diff,- diff_stat: &diff_stat,- subjects: &subjects,- current_branch: branch_name,- repo_name,- recent_commits: recent_commits.as_ref(),- };- let commit_message = crate::llm::generate_squash_message(&input, commit_gen_config)?;-- // Display the generated commit message- let formatted_message = generator.format_message_for_display(&commit_message);- eprintln!("{}", format_with_gutter(&formatted_message, None));-- // Execute the squash- match workspace.squash_commits(target, &commit_message, path)? {- SquashOutcome::Squashed(id) => {- eprintln!("{}", success_message(cformat!("Squashed @ <dim>{id}</>")));- Ok(SquashResult::Squashed)- }- SquashOutcome::NoNetChanges => {- let commit_text = if ahead == 1 { "commit" } else { "commits" };- eprintln!(- "{}",- info_message(format!("No changes after squashing {ahead} {commit_text}"))- );- Ok(SquashResult::NoNetChanges)- }- }-}-/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)////// # Arguments@@ -209,39 +110,13 @@ pub fn handle_squash(no_verify: bool,stage: Option<StageMode>,) -> anyhow::Result<SquashResult> {- // Open workspace once, route by VCS type via downcast- let workspace = worktrunk::workspace::open_workspace()?;- if workspace.as_any().downcast_ref::<Repository>().is_none() {- // jj path: use do_squash() directly (no staging/hooks)- let cwd = std::env::current_dir()?;- let target = workspace.resolve_integration_target(target)?;-- let config = UserConfig::load().context("Failed to load config")?;- let project_id = workspace.project_identifier().ok();- let resolved = config.resolved(project_id.as_deref());-- let ws_name = workspace- .current_name(&cwd)?- .unwrap_or_else(|| "default".to_string());- let repo_name = project_id.as_deref().unwrap_or("repo");-- return do_squash(- &*workspace,- &target,- &cwd,- &resolved.commit_generation,- &ws_name,- repo_name,- );- }- // Workspace is git — proceed with CommandEnv which takes ownership- let cwd = std::env::current_dir()?;+ // Load config once, run LLM setup prompt, then reuse configlet mut config = UserConfig::load().context("Failed to load config")?;// One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = CommandEnv::with_workspace(workspace, "squash", config)?;- let repo = env.require_repo()?;+ let env = CommandEnv::for_action("squash", config)?;+ let repo = &env.repo;// Squash requires being on a branch (can't squash in detached HEAD)let current_branch = env.require_branch("squash")?.to_string();let ctx = env.context(yes);@@ -415,132 +290,99 @@ pub fn handle_squash(.and_then(|n| n.to_str()).unwrap_or("repo");- // Get diff data for LLM prompt- let (diff, diff_stat) = repo.diff_for_prompt(&merge_base, "HEAD", &cwd)?;- let recent_commits = repo.recent_subjects(Some(&merge_base), 5);-- let input = crate::llm::SquashInput {- target_branch: &integration_target,- diff: &diff,- diff_stat: &diff_stat,- subjects: &subjects,- current_branch: ¤t_branch,+ let commit_message = crate::llm::generate_squash_message(+ &integration_target,+ &merge_base,+ &subjects,+ ¤t_branch,repo_name,- recent_commits: recent_commits.as_ref(),- };- let commit_message = crate::llm::generate_squash_message(&input, &resolved.commit_generation)?;+ &resolved.commit_generation,+ )?;// Display the generated commit messagelet formatted_message = generator.format_message_for_display(&commit_message);eprintln!("{}", format_with_gutter(&formatted_message, None));- // Execute squash via trait (reset --soft, check staged, commit)+ // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)//- // TOCTOU note: Between the reset and commit inside squash_commits, an external- // process could modify the staging area. This is extremely unlikely and the- // consequence is minor (unexpected content in squash commit). Considered acceptable.- match repo.squash_commits(&integration_target, &commit_message, &cwd)? {- SquashOutcome::Squashed(commit_hash) => {- eprintln!(- "{}",- success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))- );- Ok(SquashResult::Squashed)- }- SquashOutcome::NoNetChanges => {- eprintln!(- "{}",- info_message(format!(- "No changes after squashing {commit_count} {commit_text}"- ))- );- Ok(SquashResult::NoNetChanges)- }- }-}--/// Handle `wt step push` command.-///-/// Fully trait-based: opens the workspace and uses `local_push`-/// for both git and jj, with zero VcsKind branching.-///-/// Each VCS implementation validates push safety internally:-/// - Git checks fast-forward (is_ancestor) — allows merge commits-/// - Jj checks that target is ancestor of feature tip (is_rebased_onto)-pub fn step_push(target: Option<&str>) -> anyhow::Result<()> {- let ws = worktrunk::workspace::open_workspace()?;- let cwd = std::env::current_dir()?;-- let target = ws.resolve_integration_target(target)?;-- let result = ws- .local_push(&target, &cwd, Default::default())- .context("Failed to push")?;-- if result.commit_count > 0 {- let mut summary_parts = vec![format!(- "{} commit{}",- result.commit_count,- if result.commit_count == 1 { "" } else { "s" }- )];- summary_parts.extend(result.stats_summary);-- let stats_str = summary_parts.join(", ");- let paren_close = cformat!("<bright-black>)</>");+ // TOCTOU note: Between this reset and the commit below, an external process could+ // modify the staging area. This is extremely unlikely (requires precise timing) and+ // the consequence is minor (unexpected content in squash commit). The commit message+ // generated above accurately reflects the original commits being squashed, so any+ // discrepancy would be visible in the diff. Considered acceptable risk.+ repo.run_command(&["reset", "--soft", &merge_base])+ .context("Failed to reset to merge base")?;++ // Check if there are actually any changes to commit+ if !wt.has_staged_changes()? {eprintln!("{}",- success_message(cformat!(- "Pushed to <bold>{target}</> <bright-black>({stats_str}</>{}",- paren_close+ info_message(format!(+ "No changes after squashing {commit_count} {commit_text}")));- } else {- eprintln!(- "{}",- info_message(cformat!("Already up to date with <bold>{target}</>"))- );+ return Ok(SquashResult::NoNetChanges);}- Ok(())+ // Commit with the generated message+ repo.run_command(&["commit", "-m", &commit_message])+ .context("Failed to create squash commit")?;++ // Get commit hash for display+ let commit_hash = repo+ .run_command(&["rev-parse", "--short", "HEAD"])?+ .trim()+ .to_string();++ // Show success immediately after completing the squash+ eprintln!(+ "{}",+ success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))+ );++ Ok(SquashResult::Squashed)}/// Handle `wt step squash --show-prompt`////// Builds and outputs the squash prompt without running the LLM or squashing.-/// Works for both git and jj repositories.pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {- let ws = worktrunk::workspace::open_workspace()?;- let cwd = std::env::current_dir()?;-+ let repo = Repository::current()?;let config = UserConfig::load().context("Failed to load config")?;- let project_id = ws.project_identifier().ok();+ let project_id = repo.project_identifier().ok();let effective_config = config.commit_generation(project_id.as_deref());- let target = ws.resolve_integration_target(target)?;- let feature_head = ws.feature_head(&cwd)?;+ // Get and validate target ref (any commit-ish for merge-base calculation)+ let integration_target = repo.require_target_ref(target)?;- let current_branch = ws.current_name(&cwd)?.unwrap_or_else(|| "HEAD".to_string());+ // Get current branch+ let wt = repo.current_worktree();+ let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());- let subjects = ws.commit_subjects(&target, &feature_head)?;- let (diff, diff_stat) = ws.diff_for_prompt(&target, &feature_head, &cwd)?;- let recent_commits = ws.recent_subjects(Some(&target), 5);+ // Get merge base with target branch (required for generating squash message)+ let merge_base = repo+ .merge_base("HEAD", &integration_target)?+ .context("Cannot generate squash message: no common ancestor with target branch")?;++ // Get commit subjects for the squash message+ let range = format!("{}..HEAD", merge_base);+ let subjects = repo.commit_subjects(&range)?;- let repo_name = ws- .root_path()?+ // Get repo name from directory+ let repo_root = wt.root()?;+ let repo_name = repo_root.file_name()- .and_then(|n| n.to_str().map(String::from))- .unwrap_or_else(|| "repo".to_string());-- let input = crate::llm::SquashInput {- target_branch: &target,- diff: &diff,- diff_stat: &diff_stat,- subjects: &subjects,- current_branch: ¤t_branch,- repo_name: &repo_name,- recent_commits: recent_commits.as_ref(),- };- let prompt = crate::llm::build_squash_prompt(&input, &effective_config)?;+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let prompt = crate::llm::build_squash_prompt(+ &integration_target,+ &merge_base,+ &subjects,+ ¤t_branch,+ repo_name,+ &effective_config,+ )?;println!("{}", prompt);Ok(())}@@ -555,24 +397,73 @@ pub enum RebaseResult {/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {- let ws = worktrunk::workspace::open_workspace()?;- let cwd = std::env::current_dir()?;+ let repo = Repository::current()?;- let target = ws.resolve_integration_target(target)?;+ // Get and validate target ref (any commit-ish for rebase)+ let integration_target = repo.require_target_ref(target)?;- if ws.is_rebased_onto(&target, &cwd)? {- return Ok(RebaseResult::UpToDate(target));+ // Check if already up-to-date (linear extension of target, no merge commits)+ if repo.is_rebased_onto(&integration_target)? {+ return Ok(RebaseResult::UpToDate(integration_target));}- let outcome = ws.rebase_onto(&target, &cwd)?;+ // Check if this is a fast-forward or true rebase+ let merge_base = repo+ .merge_base("HEAD", &integration_target)?+ .context("Cannot rebase: no common ancestor with target branch")?;+ let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();+ let is_fast_forward = merge_base == head_sha;- let msg = match outcome {- worktrunk::workspace::RebaseOutcome::FastForward => {- cformat!("Fast-forwarded to <bold>{target}</>")+ // Only show progress for true rebases (fast-forwards are instant)+ if !is_fast_forward {+ eprintln!(+ "{}",+ progress_message(cformat!("Rebasing onto <bold>{integration_target}</>..."))+ );+ }++ let rebase_result = repo.run_command(&["rebase", &integration_target]);++ // If rebase failed, check if it's due to conflicts+ if let Err(e) = rebase_result {+ // Check if it's a rebase conflict+ let is_rebasing = repo+ .worktree_state()?+ .is_some_and(|s| s.starts_with("REBASING"));+ if is_rebasing {+ // Extract git's stderr output from the error+ let git_output = e.to_string();+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: integration_target,+ git_output,+ }+ .into());}- worktrunk::workspace::RebaseOutcome::Rebased => {- cformat!("Rebased onto <bold>{target}</>")+ // Not a rebase conflict, return original error+ return Err(worktrunk::git::GitError::Other {+ message: cformat!(+ "Failed to rebase onto <bold>{}</>: {}",+ integration_target,+ e+ ),}+ .into());+ }++ // Verify rebase completed successfully (safety check for edge cases)+ if repo.worktree_state()?.is_some() {+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: integration_target,+ git_output: String::new(),+ }+ .into());+ }++ // Success+ let msg = if is_fast_forward {+ cformat!("Fast-forwarded to <bold>{integration_target}</>")+ } else {+ cformat!("Rebased onto <bold>{integration_target}</>")};eprintln!("{}", success_message(msg));@@ -592,24 +483,44 @@ pub fn step_copy_ignored(dry_run: bool,force: bool,) -> anyhow::Result<()> {- let workspace = worktrunk::workspace::open_workspace()?;-- // Resolve source and destination workspace paths- let source_path = match from {- Some(name) => workspace.workspace_path(name)?,- None => workspace- .default_workspace_path()?- .ok_or_else(|| anyhow::anyhow!("No default workspace found"))?,+ let repo = Repository::current()?;++ // Resolve source and destination worktree paths+ let (source_path, source_context) = match from {+ Some(branch) => {+ let path = repo.worktree_for_branch(branch)?.ok_or_else(|| {+ worktrunk::git::GitError::WorktreeNotFound {+ branch: branch.to_string(),+ }+ })?;+ (path, branch.to_string())+ }+ None => {+ // Default source is the primary worktree (main worktree for normal repos,+ // default branch worktree for bare repos).+ let path = repo.primary_worktree()?.ok_or_else(|| {+ anyhow::anyhow!(+ "No primary worktree found (bare repo with no default branch worktree)"+ )+ })?;+ let context = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ (path, context)+ }};let dest_path = match to {- Some(name) => workspace.workspace_path(name)?,- None => workspace.current_workspace_path()?,+ Some(branch) => repo.worktree_for_branch(branch)?.ok_or_else(|| {+ worktrunk::git::GitError::WorktreeNotFound {+ branch: branch.to_string(),+ }+ })?,+ None => repo.current_worktree().root()?,};- if dunce::canonicalize(&source_path).unwrap_or_else(|_| source_path.clone())- == dunce::canonicalize(&dest_path).unwrap_or_else(|_| dest_path.clone())- {+ if source_path == dest_path {eprintln!("{}",info_message("Source and destination are the same worktree")@@ -617,8 +528,9 @@ pub fn step_copy_ignored(return Ok(());}- // Get ignored entries via git ls-files (works for both git and jj with git backend)- let ignored_entries = workspace.list_ignored_entries(&source_path)?;+ // Get ignored entries from git+ // --directory stops at directory boundaries (avoids listing thousands of files in target/)+ let ignored_entries = list_ignored_entries(&source_path, &source_context)?;// Filter to entries that match .worktreeinclude (or all if no file exists)let include_path = source_path.join(".worktreeinclude");@@ -627,8 +539,10 @@ pub fn step_copy_ignored(let include_matcher = {let mut builder = GitignoreBuilder::new(&source_path);if let Some(err) = builder.add(&include_path) {- return Err(anyhow::anyhow!("{err}"))- .context(cformat!("Error parsing <bold>.worktreeinclude</>"));+ return Err(worktrunk::git::GitError::WorktreeIncludeParseError {+ error: err.to_string(),+ }+ .into());}builder.build().context("Failed to build include matcher")?};@@ -641,20 +555,20 @@ pub fn step_copy_ignored(ignored_entries};- // Filter out entries that contain other workspaces (prevents recursive copying when- // workspaces are nested inside the source, e.g., worktree-path = ".worktrees/...")- let workspace_paths: Vec<PathBuf> = workspace- .list_workspaces()?+ // Filter out entries that contain other worktrees (prevents recursive copying when+ // worktrees are nested inside the source, e.g., worktree-path = ".worktrees/...")+ let worktree_paths: Vec<PathBuf> = repo+ .list_worktrees()?.into_iter()- .map(|ws| ws.path)+ .map(|wt| wt.path).collect();let entries_to_copy: Vec<_> = entries_to_copy.into_iter().filter(|(entry_path, _)| {- // Exclude if any workspace (other than source) is inside or equal to this entry- !workspace_paths+ // Exclude if any worktree (other than source) is inside or equal to this entry+ !worktree_paths.iter()- .any(|ws_path| ws_path != &source_path && ws_path.starts_with(entry_path))+ .any(|wt_path| wt_path != &source_path && wt_path.starts_with(entry_path))}).collect();@@ -692,10 +606,10 @@ pub fn step_copy_ignored(// Copy entriesfor (src_entry, is_dir) in &entries_to_copy {- // Paths from list_ignored_entries are always under source_path+ // Paths from git ls-files are always under source_pathlet relative = src_entry.strip_prefix(&source_path)- .expect("ignored entry path under source workspace");+ .expect("git ls-files path under worktree");let dest_entry = dest_path.join(relative);if *is_dir {@@ -739,6 +653,46 @@ fn remove_if_exists(path: &Path) -> anyhow::Result<()> {Ok(())}+/// List ignored entries using git ls-files+///+/// Uses `git ls-files --ignored --exclude-standard -o --directory` which:+/// - Handles all gitignore sources (global, .gitignore, .git/info/exclude, nested)+/// - Stops at directory boundaries (--directory) to avoid listing thousands of files+fn list_ignored_entries(+ worktree_path: &Path,+ context: &str,+) -> anyhow::Result<Vec<(std::path::PathBuf, bool)>> {+ let output = Cmd::new("git")+ .args([+ "ls-files",+ "--ignored",+ "--exclude-standard",+ "-o",+ "--directory",+ ])+ .current_dir(worktree_path)+ .context(context)+ .run()+ .context("Failed to run git ls-files")?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!("git ls-files failed: {}", stderr.trim());+ }++ // Parse output: directories end with /+ let entries = String::from_utf8_lossy(&output.stdout)+ .lines()+ .map(|line| {+ let is_dir = line.ends_with('/');+ let path = worktree_path.join(line.trim_end_matches('/'));+ (path, is_dir)+ })+ .collect();++ Ok(entries)+}+/// Copy a directory recursively using reflink (COW).////// Uses file-by-file copying with per-file reflink on all platforms. This spreads@@ -837,8 +791,7 @@ pub fn step_relocate(show_dry_run_preview, show_no_relocations_needed, show_summary, validate_candidates,};- let workspace = worktrunk::workspace::open_workspace()?;- let repo = super::require_git_workspace(&*workspace, "step relocate")?;+ let repo = Repository::current()?;let config = UserConfig::load()?;let default_branch = repo.default_branch().unwrap_or_default();@@ -854,7 +807,7 @@ pub fn step_relocate(let GatherResult {candidates,template_errors,- } = gather_candidates(repo, &config, &branches)?;+ } = gather_candidates(&repo, &config, &branches)?;if candidates.is_empty() {show_no_relocations_needed(template_errors);@@ -869,7 +822,7 @@ pub fn step_relocate(// Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)let ValidationResult { validated, skipped } =- validate_candidates(repo, &config, candidates, commit, &repo_path)?;+ validate_candidates(&repo, &config, candidates, commit, &repo_path)?;if validated.is_empty() {show_all_skipped(skipped);@@ -877,7 +830,7 @@ pub fn step_relocate(}// Phase 3 & 4: Create executor (classifies targets) and execute relocations- let mut executor = RelocationExecutor::new(repo, validated, clobber)?;+ let mut executor = RelocationExecutor::new(&repo, validated, clobber)?;let cwd = std::env::current_dir().ok();executor.execute(&repo_path, &default_branch, cwd.as_deref())?;diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex cf2591071..aed44015e 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -50,7 +50,7 @@ impl<'a> CommandContext<'a> {removed_commit: Option<&str>,display_path: Option<&Path>,) -> anyhow::Result<Vec<SourcedCommand>> {- let project_config = self.workspace.load_project_config()?;+ let project_config = self.repo.load_project_config()?;// Template variables should reflect the removed worktree, not where we run from.// The removed worktree path no longer exists, but hooks may need to reference itdiff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 6ef86e4bc..8d17cacc2 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -79,19 +79,22 @@//! The shell wrapper is generated by `wt config shell init <shell>` from templates in `templates/`.mod hooks;+mod push;mod remove;mod resolve;mod switch;mod types;// Re-export public types and functions+pub use push::handle_push;pub use remove::{handle_remove, handle_remove_current};pub(crate) use resolve::paths_match;pub use resolve::{compute_worktree_path, get_path_mismatch, is_worktree_at_expected_path, resolve_worktree_arg,worktree_display_name,};-pub use switch::{execute_switch, plan_switch, resolve_path_mismatch};+pub use switch::{execute_switch, plan_switch};pub use types::{- BranchDeletionMode, OperationMode, RemoveResult, SwitchBranchInfo, SwitchPlan, SwitchResult,+ BranchDeletionMode, MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchPlan,+ SwitchResult,};diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsnew file mode 100644index 000000000..fa574f729--- /dev/null+++ b/src/commands/worktree/push.rs@@ -0,0 +1,211 @@+//! Worktree push operations.+//!+//! Push changes to target branch with safety checks.++use color_print::cformat;+use worktrunk::git::{GitError, Repository};+use worktrunk::styling::{+ eprintln, format_with_gutter, info_message, progress_message, success_message,+};++use super::types::MergeOperations;+use crate::commands::repository_ext::RepositoryCliExt;++/// Push changes to target branch+///+/// The `operations` parameter indicates which merge operations occurred (commit, squash, rebase).+/// Pass `None` for standalone push operations where these concepts don't apply.+///+/// During the push stage we temporarily `git stash` non-overlapping changes in the+/// target worktree (if present) so that concurrent edits there do not block the+/// fast-forward. The stash is restored afterward and we bail out early if any file+/// overlaps with the push range.+pub fn handle_push(+ target: Option<&str>,+ verb: &str,+ operations: Option<MergeOperations>,+) -> anyhow::Result<()> {+ let repo = Repository::current()?;++ // Get and validate target branch (must be a branch since we're updating it)+ let target_branch = repo.require_target_branch(target)?;++ // A worktree for the target branch is optional for push:+ // - If present, we use it to check for overlapping dirty files.+ // - If absent, we skip that safety step but still allow the push (git itself is fine).+ let target_worktree_path = repo.worktree_for_branch(&target_branch)?;++ // Check if it's a fast-forward+ if !repo.is_ancestor(&target_branch, "HEAD")? {+ // Get formatted commit log (commits in target that we don't have)+ let commits_formatted = repo+ .run_command(&[+ "log",+ "--color=always",+ "--graph",+ "--oneline",+ &format!("HEAD..{}", target_branch),+ ])?+ .trim()+ .to_string();++ return Err(GitError::NotFastForward {+ target_branch: target_branch.clone(),+ commits_formatted,+ in_merge_context: operations.is_some(),+ }+ .into());+ }++ // Check for conflicting changes in target worktree (auto-stash safe changes)+ // The stash guard auto-restores on drop (error paths), or explicitly via restore_now()+ let mut stash_guard =+ repo.prepare_target_worktree(target_worktree_path.as_ref(), &target_branch)?;++ // Count commits and show what will be pushed+ let commit_count = repo.count_commits(&target_branch, "HEAD")?;++ // Get diff statistics BEFORE push (will be needed for success message later)+ let stats_summary = if commit_count > 0 {+ repo.diff_stats_summary(&["diff", "--shortstat", &format!("{}..HEAD", target_branch)])+ } else {+ Vec::new()+ };++ // Build and show consolidated message with squash/rebase info+ if commit_count > 0 {+ let commit_text = if commit_count == 1 {+ "commit"+ } else {+ "commits"+ };+ let head_sha = repo.run_command(&["rev-parse", "--short", "HEAD"])?;+ let head_sha = head_sha.trim();++ let verb_ing = if verb.starts_with("Merged") {+ "Merging"+ } else {+ "Pushing"+ };++ // Build parenthetical showing which operations didn't happen and flags used+ let mut notes = Vec::new();++ // Skipped operations - only include if we're in merge workflow context+ if let Some(ops) = operations {+ let mut skipped_ops = Vec::new();+ if !ops.committed && !ops.squashed {+ // Neither commit nor squash happened - combine them+ skipped_ops.push("commit/squash");+ }+ if !ops.rebased {+ skipped_ops.push("rebase");+ }+ if !skipped_ops.is_empty() {+ notes.push(format!("no {} needed", skipped_ops.join("/")));+ }+ }++ let operations_note = if notes.is_empty() {+ String::new()+ } else {+ format!(" ({})", notes.join(", "))+ };++ eprintln!(+ "{}",+ progress_message(cformat!(+ "{verb_ing} {commit_count} {commit_text} to <bold>{target_branch}</> @ <dim>{head_sha}</>{operations_note}"+ ))+ );++ // Show the commit graph with color+ let log_output = repo.run_command(&[+ "log",+ "--color=always",+ "--graph",+ "--oneline",+ &format!("{}..HEAD", target_branch),+ ])?;+ eprintln!("{}", format_with_gutter(&log_output, None));++ // Show diff statistics+ crate::commands::show_diffstat(&repo, &format!("{}..HEAD", target_branch))?;+ }++ // Get git common dir for the push+ let git_common_dir = repo.git_common_dir();+ let git_common_dir_str = git_common_dir.to_string_lossy();++ // Perform the push - stash guard will auto-restore on any exit path+ // Use --receive-pack to pass config to the receiving end without permanently mutating repo config+ let push_target = format!("HEAD:{}", target_branch);+ repo.run_command(&[+ "push",+ "--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",+ git_common_dir_str.as_ref(),+ &push_target,+ ])+ .map_err(|e| {+ // CommandFailed contains raw git output, wrap in PushFailed for proper formatting+ GitError::PushFailed {+ target_branch: target_branch.clone(),+ error: e.to_string(),+ }+ })?;++ // Restore stash before success message (Drop handles error paths automatically)+ if let Some(guard) = stash_guard.as_mut() {+ guard.restore_now();+ }++ // Show success message after push completes+ if commit_count > 0 {+ // Use the diff statistics captured earlier (before push)+ let mut summary_parts = vec![format!(+ "{} commit{}",+ commit_count,+ if commit_count == 1 { "" } else { "s" }+ )];+ summary_parts.extend(stats_summary);++ // Re-apply bright-black after stats (which end with a reset) so ) is also gray+ let stats_str = summary_parts.join(", ");+ let paren_close = cformat!("<bright-black>)</>"); // Separate to avoid cformat optimization+ eprintln!(+ "{}",+ success_message(cformat!(+ "{verb} <bold>{target_branch}</> <bright-black>({stats_str}</>{}",+ paren_close+ ))+ );+ } else {+ // For merge workflow context, explain why nothing was pushed+ let context = if let Some(ops) = operations {+ let mut notes = Vec::new();+ if !ops.committed && !ops.squashed {+ notes.push("no new commits");+ }+ if !ops.rebased {+ notes.push("no rebase needed");+ }+ if notes.is_empty() {+ String::new()+ } else {+ format!(" ({})", notes.join(", "))+ }+ } else {+ String::new()+ };++ // No action: nothing was pushed, just acknowledging state+ eprintln!(+ "{}",+ info_message(cformat!(+ "Already up to date with <bold>{target_branch}</>{context}"+ ))+ );+ }++ Ok(())+}diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 5f477c0d3..b1677ff28 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -10,7 +10,6 @@ use normalize_path::NormalizePath;use worktrunk::config::UserConfig;use worktrunk::git::{GitError, Repository, ResolvedWorktree};use worktrunk::path::format_path_for_display;-use worktrunk::workspace::build_worktree_map;use super::types::OperationMode;@@ -108,16 +107,8 @@ pub fn compute_worktree_path(})?;let project = repo.project_identifier().ok();- let repo_path_str = repo.repo_path().to_string_lossy().to_string();- let worktree_map = build_worktree_map(repo);let expanded_path = config- .format_path(- repo_name,- branch,- &repo_path_str,- &worktree_map,- project.as_deref(),- )+ .format_path(repo_name, branch, repo, project.as_deref()).map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;Ok(repo_root.join(expanded_path).normalize())diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex b6a35f2f4..4360f3e99 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -17,7 +17,7 @@ use worktrunk::styling::{warning_message,};-use super::resolve::{compute_clobber_backup, compute_worktree_path, get_path_mismatch};+use super::resolve::{compute_clobber_backup, compute_worktree_path};use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};use crate::commands::command_executor::CommandContext;@@ -628,8 +628,8 @@ pub fn plan_switch(////// Takes a `SwitchPlan` from `plan_switch()` and executes it./// For `SwitchPlan::Existing`, just records history. The returned-/// `SwitchBranchInfo` has `expected_path: None` — callers must use-/// [`resolve_path_mismatch`] after first output to fill in mismatch warnings.+/// `SwitchBranchInfo` has `expected_path: None` — callers fill it in after+/// first output to avoid computing path mismatch on the hot path./// For `SwitchPlan::Create`, creates the worktree and runs hooks.pub fn execute_switch(repo: &Repository,@@ -907,27 +907,6 @@ pub fn execute_switch(/// Resolve the deferred path mismatch for existing worktree switches.///-/// `execute_switch` returns `expected_path: None` for existing worktrees to avoid-/// ~7 git commands on the hot path. Call this after first output to fill in the-/// mismatch warning.-pub fn resolve_path_mismatch(- branch_info: SwitchBranchInfo,- result: &SwitchResult,- repo: &Repository,- config: &UserConfig,-) -> SwitchBranchInfo {- match result {- SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {- let expected_path = get_path_mismatch(repo, &branch_info.branch, path, config);- SwitchBranchInfo {- expected_path,- ..branch_info- }- }- _ => branch_info,- }-}-fn worktree_creation_error(err: &anyhow::Error,branch: String,diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 95529a5d1..140aaa84c 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -1,11 +1,19 @@//! Types for worktree operations.//!-//! Core data structures used by switch and remove operations.+//! Core data structures used by switch, remove, and push operations.use std::path::{Path, PathBuf};use worktrunk::git::RefType;+/// Flags indicating which merge operations occurred+#[derive(Debug, Clone, Copy)]+pub struct MergeOperations {+ pub committed: bool,+ pub squashed: bool,+ pub rebased: bool,+}+/// Result of a worktree switch operationpub enum SwitchResult {/// Already at the target worktree (no action taken)@@ -259,6 +267,59 @@ mod tests {assert_eq!(result.path(), &path);}+ #[test]+ fn test_merge_operations_struct() {+ let ops = MergeOperations {+ committed: true,+ squashed: false,+ rebased: true,+ };+ assert!(ops.committed);+ assert!(!ops.squashed);+ assert!(ops.rebased);+ }++ #[test]+ fn test_merge_operations_clone() {+ let ops = MergeOperations {+ committed: true,+ squashed: true,+ rebased: false,+ };+ // MergeOperations implements both Clone and Copy+ // Use Clone explicitly to test the Clone impl+ let cloned = Clone::clone(&ops);+ assert_eq!(ops.committed, cloned.committed);+ assert_eq!(ops.squashed, cloned.squashed);+ assert_eq!(ops.rebased, cloned.rebased);+ }++ #[test]+ fn test_merge_operations_copy() {+ let ops = MergeOperations {+ committed: false,+ squashed: false,+ rebased: true,+ };+ let copied = ops; // Copy trait+ assert_eq!(ops.committed, copied.committed);+ assert_eq!(ops.squashed, copied.squashed);+ assert_eq!(ops.rebased, copied.rebased);+ }++ #[test]+ fn test_merge_operations_debug() {+ let ops = MergeOperations {+ committed: true,+ squashed: false,+ rebased: true,+ };+ let debug = format!("{:?}", ops);+ assert!(debug.contains("committed: true"));+ assert!(debug.contains("squashed: false"));+ assert!(debug.contains("rebased: true"));+ }+#[test]fn test_remove_result_removed_worktree() {let result = RemoveResult::RemovedWorktree {diff --git a/src/completion.rs b/src/completion.rsindex 264e169d2..43feb2826 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -8,7 +8,7 @@ use clap_complete::env::CompleteEnv;use crate::cli;use crate::display::format_relative_time_short;-use worktrunk::config::UserConfig;+use worktrunk::config::{ProjectConfig, UserConfig};use worktrunk::git::{BranchCategory, HookType, Repository};/// Deprecated args that should never appear in completions.@@ -268,9 +268,9 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {}// Load project config and add project hook names- // Uses workspace trait (works for both git and jj)- if let Ok(workspace) = worktrunk::workspace::open_workspace()- && let Ok(Some(project_config)) = workspace.load_project_config()+ // Pass write_hints=false to avoid side effects during completion+ if let Ok(repo) = Repository::current()+ && let Ok(Some(project_config)) = ProjectConfig::load(&repo, false)&& let Some(config) = project_config.hooks.get(hook_type){add_named_commands(&mut candidates, config);@@ -320,46 +320,36 @@ fn complete_branches(return Vec::new();}- // Try git first (fast path, no workspace detection overhead)- if let Ok(repo) = Repository::current() {- let branches = repo.branches_for_completion().unwrap_or_default();- return branches- .into_iter()- .filter(|branch| {- if worktree_only {- matches!(branch.category, BranchCategory::Worktree)- } else if exclude_remote_only {- !matches!(branch.category, BranchCategory::Remote(_))- } else {- true- }- })- .map(|branch| {- let time_str = format_relative_time_short(branch.timestamp);- let help = match branch.category {- BranchCategory::Worktree => format!("+ {}", time_str),- BranchCategory::Local => format!("/ {}", time_str),- BranchCategory::Remote(remotes) => {- format!("⇣ {} {}", time_str, remotes.join(", "))- }- };- CompletionCandidate::new(branch.name).help(Some(help.into()))- })- .collect();- }+ let branches = match Repository::current().and_then(|repo| repo.branches_for_completion()) {+ Ok(b) => b,+ Err(_) => return Vec::new(),+ };- // Not in a git repo — try jj: workspace names as branch completions- if let Ok(workspace) = worktrunk::workspace::open_workspace()- && let Ok(items) = workspace.list_workspaces()- {- return items- .iter()- .filter_map(|w| w.branch.as_ref())- .map(|name| CompletionCandidate::new(name.clone()))- .collect();+ if branches.is_empty() {+ return Vec::new();}- Vec::new()+ branches+ .into_iter()+ .filter(|branch| {+ if worktree_only {+ matches!(branch.category, BranchCategory::Worktree)+ } else if exclude_remote_only {+ !matches!(branch.category, BranchCategory::Remote(_))+ } else {+ true+ }+ })+ .map(|branch| {+ let time_str = format_relative_time_short(branch.timestamp);+ let help = match branch.category {+ BranchCategory::Worktree => format!("+ {}", time_str),+ BranchCategory::Local => format!("/ {}", time_str),+ BranchCategory::Remote(remotes) => format!("⇣ {} {}", time_str, remotes.join(", ")),+ };+ CompletionCandidate::new(branch.name).help(Some(help.into()))+ })+ .collect()}fn suppress_switch_branch_completion() -> bool {diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex df8debbf8..477bc2359 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -9,13 +9,13 @@//! See `wt hook --help` for available filters and functions.use std::borrow::Cow;-use std::path::PathBuf;use color_print::cformat;use minijinja::{Environment, UndefinedBehavior, Value};use regex::Regex;use shell_escape::escape;+use crate::git::Repository;use crate::path::to_posix_path;use crate::styling::{eprintln, format_with_gutter, info_message, verbosity};@@ -213,8 +213,7 @@ pub fn redact_credentials(s: &str) -> String {/// * `vars` - Variables to substitute/// * `shell_escape` - If true, shell-escape all values for safe command execution./// If false, substitute values literally (for filesystem paths).-/// * `worktree_map` - Branch/workspace name → filesystem path lookup for-/// `worktree_path_of_branch()`. Build with [`crate::workspace::build_worktree_map()`].+/// * `repo` - Repository for looking up worktree paths////// # Filters/// - `sanitize` — Replace `/` and `\` with `-` for filesystem-safe paths@@ -230,7 +229,7 @@ pub fn expand_template(template: &str,vars: &HashMap<&str, &str>,shell_escape: bool,- worktree_map: &HashMap<String, PathBuf>,+ repo: &Repository,name: &str,) -> Result<String, String> {// Build context map with raw values (shell escaping is applied at output time via formatter)@@ -277,9 +276,12 @@ pub fn expand_template(// Register worktree_path_of_branch function for looking up branch worktree paths.// Returns raw paths — shell escaping is applied by the formatter at output time.- let map = worktree_map.clone();+ let repo_clone = repo.clone();env.add_function("worktree_path_of_branch", move |branch: String| -> String {- map.get(&branch)+ repo_clone+ .worktree_for_branch(&branch)+ .ok()+ .flatten().map(|p| to_posix_path(&p.to_string_lossy())).unwrap_or_default()});@@ -340,8 +342,27 @@ pub fn expand_template(mod tests {use super::*;- fn empty_map() -> HashMap<String, PathBuf> {- HashMap::new()+ /// Test fixture that creates a real temporary git repository.+ struct TestRepo {+ _dir: tempfile::TempDir,+ repo: Repository,+ }++ impl TestRepo {+ fn new() -> Self {+ let dir = tempfile::tempdir().unwrap();+ std::process::Command::new("git")+ .args(["init"])+ .current_dir(dir.path())+ .output()+ .unwrap();+ let repo = Repository::at(dir.path()).unwrap();+ Self { _dir: dir, repo }+ }+ }++ fn test_repo() -> TestRepo {+ TestRepo::new()}#[test]@@ -475,36 +496,36 @@ mod tests {#[test]fn test_expand_template_basic() {- let map = empty_map();+ let test = test_repo();// Single variablelet mut vars = HashMap::new();vars.insert("name", "world");assert_eq!(- expand_template("Hello {{ name }}", &vars, false, &map, "test").unwrap(),+ expand_template("Hello {{ name }}", &vars, false, &test.repo, "test").unwrap(),"Hello world");// Multiple variablesvars.insert("repo", "myrepo");assert_eq!(- expand_template("{{ repo }}/{{ name }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ repo }}/{{ name }}", &vars, false, &test.repo, "test").unwrap(),"myrepo/world");// Empty/static caseslet empty: HashMap<&str, &str> = HashMap::new();assert_eq!(- expand_template("", &empty, false, &map, "test").unwrap(),+ expand_template("", &empty, false, &test.repo, "test").unwrap(),"");assert_eq!(- expand_template("static text", &empty, false, &map, "test").unwrap(),+ expand_template("static text", &empty, false, &test.repo, "test").unwrap(),"static text");// Undefined variables now error in SemiStrict modeassert!(- expand_template("no {{ variables }} here", &empty, false, &map, "test")+ expand_template("no {{ variables }} here", &empty, false, &test.repo, "test").unwrap_err().contains("undefined"));@@ -512,50 +533,64 @@ mod tests {#[test]fn test_expand_template_shell_escape() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("path", "my path");- let expanded = expand_template("cd {{ path }}", &vars, true, &map, "test").unwrap();+ let expanded = expand_template("cd {{ path }}", &vars, true, &test.repo, "test").unwrap();assert!(expanded.contains("'my path'") || expanded.contains("my\\ path"));// Command injection preventionvars.insert("arg", "test;rm -rf");- let expanded = expand_template("echo {{ arg }}", &vars, true, &map, "test").unwrap();+ let expanded = expand_template("echo {{ arg }}", &vars, true, &test.repo, "test").unwrap();assert!(!expanded.contains(";rm") || expanded.contains("'"));// No escape for literal modevars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");}#[test]fn test_expand_template_errors() {- let map = empty_map();+ let test = test_repo();let vars = HashMap::new();assert!(- expand_template("{{ unclosed", &vars, false, &map, "test")+ expand_template("{{ unclosed", &vars, false, &test.repo, "test").unwrap_err().contains("syntax error"));- assert!(expand_template("{{ 1 + }}", &vars, false, &map, "test").is_err());+ assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());}#[test]fn test_expand_template_jinja_features() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("debug", "true");assert_eq!(- expand_template("{% if debug %}DEBUG{% endif %}", &vars, false, &map, "test").unwrap(),+ expand_template(+ "{% if debug %}DEBUG{% endif %}",+ &vars,+ false,+ &test.repo,+ "test"+ )+ .unwrap(),"DEBUG");vars.insert("debug", "");assert_eq!(- expand_template("{% if debug %}DEBUG{% endif %}", &vars, false, &map, "test").unwrap(),+ expand_template(+ "{% if debug %}DEBUG{% endif %}",+ &vars,+ false,+ &test.repo,+ "test"+ )+ .unwrap(),"");@@ -565,7 +600,7 @@ mod tests {"{{ missing | default('fallback') }}",&empty,false,- &map,+ &test.repo,"test",).unwrap(),@@ -574,14 +609,14 @@ mod tests {vars.insert("name", "hello");assert_eq!(- expand_template("{{ name | upper }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ name | upper }}", &vars, false, &test.repo, "test").unwrap(),"HELLO");}#[test]fn test_expand_template_strip_prefix() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();// Built-in replace filter strips prefix (replaces all occurrences)@@ -591,7 +626,7 @@ mod tests {"{{ branch | replace('feature/', '') }}",&vars,false,- &map,+ &test.repo,"test").unwrap(),@@ -604,7 +639,7 @@ mod tests {"{{ branch | replace('feature/', '') | sanitize }}",&vars,false,- &map,+ &test.repo,"test").unwrap(),@@ -618,7 +653,7 @@ mod tests {"{{ branch | replace('feature/', '') }}",&vars,false,- &map,+ &test.repo,"test").unwrap(),@@ -628,7 +663,7 @@ mod tests {// Slicing for prefix-only removal (avoids replacing mid-string)vars.insert("branch", "feature/nested/feature/deep");assert_eq!(- expand_template("{{ branch[8:] }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch[8:] }}", &vars, false, &test.repo, "test").unwrap(),"nested/feature/deep");@@ -638,7 +673,7 @@ mod tests {"{% if branch[:8] == 'feature/' %}{{ branch[8:] }}{% else %}{{ branch }}{% endif %}",&vars,false,- &map,+ &test.repo,"test").unwrap(),@@ -652,7 +687,7 @@ mod tests {"{% if branch[:8] == 'feature/' %}{{ branch[8:] }}{% else %}{{ branch }}{% endif %}",&vars,false,- &map,+ &test.repo,"test").unwrap(),@@ -662,32 +697,32 @@ mod tests {#[test]fn test_expand_template_sanitize_filter() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),"feature-foo");// Backslashes are also sanitizedvars.insert("branch", "feature\\bar");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),"feature-bar");// Multiple slashesvars.insert("branch", "user/feature/task");assert_eq!(- expand_template("{{ branch | sanitize }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),"user-feature-task");// Raw branch is unchangedvars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");@@ -695,7 +730,8 @@ mod tests {// Previously, shell escaping was applied BEFORE filters, corrupting the result// when values contained shell-special characters (quotes, backslashes).vars.insert("branch", "user's/feature");- let result = expand_template("{{ branch | sanitize }}", &vars, true, &map, "test").unwrap();+ let result =+ expand_template("{{ branch | sanitize }}", &vars, true, &test.repo, "test").unwrap();// sanitize replaces / with -, producing "user's-feature"// shell_escape wraps it: 'user'\''s-feature' (valid shell for user's-feature)assert_eq!(result, "'user'\\''s-feature'", "sanitize + shell escape");@@ -704,7 +740,7 @@ mod tests {// sanitize would replace the / and \ in the already-escaped value.// Shell escaping without filter: raw value with special chars- let result = expand_template("{{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("{{ branch }}", &vars, true, &test.repo, "test").unwrap();// shell_escape wraps: 'user'\''s/feature' (valid shell for user's/feature)assert_eq!(result, "'user'\\''s/feature'",@@ -713,48 +749,66 @@ mod tests {// Shell-escape formatter handles none values (renders as empty string)let result =- expand_template("prefix-{{ none }}-suffix", &vars, true, &map, "test").unwrap();+ expand_template("prefix-{{ none }}-suffix", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "prefix--suffix", "none renders as empty");}#[test]fn test_expand_template_sanitize_db_filter() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();// Basic transformation (with hash suffix)vars.insert("branch", "feature/auth-oauth2");- let result =- expand_template("{{ branch | sanitize_db }}", &vars, false, &map, "test").unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert!(result.starts_with("feature_auth_oauth2_"), "got: {result}");// Leading digit gets underscore prefixvars.insert("branch", "123-bug-fix");- let result =- expand_template("{{ branch | sanitize_db }}", &vars, false, &map, "test").unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert!(result.starts_with("_123_bug_fix_"), "got: {result}");// Uppercase conversionvars.insert("branch", "UPPERCASE.Branch");- let result =- expand_template("{{ branch | sanitize_db }}", &vars, false, &map, "test").unwrap();+ let result = expand_template(+ "{{ branch | sanitize_db }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();assert!(result.starts_with("uppercase_branch_"), "got: {result}");// Raw branch is unchangedvars.insert("branch", "feature/foo");assert_eq!(- expand_template("{{ branch }}", &vars, false, &map, "test").unwrap(),+ expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");}#[test]fn test_expand_template_trailing_newline() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("cmd", "echo hello");assert!(- expand_template("{{ cmd }}\n", &vars, true, &map, "test")+ expand_template("{{ cmd }}\n", &vars, true, &test.repo, "test").unwrap().ends_with('\n'));@@ -772,14 +826,14 @@ mod tests {#[test]fn test_hash_port_filter() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("branch", "feature-foo");vars.insert("repo", "myrepo");// Filter produces a number in rangelet result =- expand_template("{{ branch | hash_port }}", &vars, false, &map, "test").unwrap();+ expand_template("{{ branch | hash_port }}", &vars, false, &test.repo, "test").unwrap();let port: u16 = result.parse().expect("should be a number");assert!((10000..20000).contains(&port));@@ -788,7 +842,7 @@ mod tests {"{{ (repo ~ '-' ~ branch) | hash_port }}",&vars,false,- &map,+ &test.repo,"test",).unwrap();@@ -797,7 +851,7 @@ mod tests {"{{ (repo ~ '-' ~ branch) | hash_port }}",&vars,false,- &map,+ &test.repo,"test",).unwrap();diff --git a/src/config/mod.rs b/src/config/mod.rsindex a9a49fc6e..4d244d408 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -100,9 +100,29 @@ pub use user::{#[cfg(test)]mod tests {use super::*;+ use crate::git::Repository;++ /// Test fixture that creates a real temporary git repository.+ struct TestRepo {+ _dir: tempfile::TempDir,+ repo: Repository,+ }++ impl TestRepo {+ fn new() -> Self {+ let dir = tempfile::tempdir().unwrap();+ std::process::Command::new("git")+ .args(["init"])+ .current_dir(dir.path())+ .output()+ .unwrap();+ let repo = Repository::at(dir.path()).unwrap();+ Self { _dir: dir, repo }+ }+ }- fn empty_worktree_map() -> std::collections::HashMap<String, std::path::PathBuf> {- std::collections::HashMap::new()+ fn test_repo() -> TestRepo {+ TestRepo::new()}#[test]@@ -146,7 +166,7 @@ mod tests {#[test]fn test_format_worktree_path() {- let wt_map = empty_worktree_map();+ let test = test_repo();let config = UserConfig {configs: OverridableConfig {worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),@@ -156,7 +176,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature-x", "", &wt_map, None)+ .format_path("myproject", "feature-x", &test.repo, None).unwrap(),"myproject.feature-x");@@ -164,7 +184,7 @@ mod tests {#[test]fn test_format_worktree_path_custom_template() {- let wt_map = empty_worktree_map();+ let test = test_repo();let config = UserConfig {configs: OverridableConfig {worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),@@ -174,7 +194,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature-x", "", &wt_map, None)+ .format_path("myproject", "feature-x", &test.repo, None).unwrap(),"myproject-feature-x");@@ -182,7 +202,7 @@ mod tests {#[test]fn test_format_worktree_path_only_branch() {- let wt_map = empty_worktree_map();+ let test = test_repo();let config = UserConfig {configs: OverridableConfig {worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),@@ -192,7 +212,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature-x", "", &wt_map, None)+ .format_path("myproject", "feature-x", &test.repo, None).unwrap(),".worktrees/myproject/feature-x");@@ -200,7 +220,7 @@ mod tests {#[test]fn test_format_worktree_path_with_slashes() {- let wt_map = empty_worktree_map();+ let test = test_repo();// Use {{ branch | sanitize }} to replace slashes with dasheslet config = UserConfig {configs: OverridableConfig {@@ -211,7 +231,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature/foo", "", &wt_map, None)+ .format_path("myproject", "feature/foo", &test.repo, None).unwrap(),"myproject.feature-foo");@@ -219,7 +239,7 @@ mod tests {#[test]fn test_format_worktree_path_with_multiple_slashes() {- let wt_map = empty_worktree_map();+ let test = test_repo();let config = UserConfig {configs: OverridableConfig {worktree_path: Some(@@ -231,7 +251,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature/sub/task", "", &wt_map, None)+ .format_path("myproject", "feature/sub/task", &test.repo, None).unwrap(),".worktrees/myproject/feature-sub-task");@@ -239,7 +259,7 @@ mod tests {#[test]fn test_format_worktree_path_with_backslashes() {- let wt_map = empty_worktree_map();+ let test = test_repo();// Windows-style path separators should also be sanitizedlet config = UserConfig {configs: OverridableConfig {@@ -252,7 +272,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature\\foo", "", &wt_map, None)+ .format_path("myproject", "feature\\foo", &test.repo, None).unwrap(),".worktrees/myproject/feature-foo");@@ -260,7 +280,7 @@ mod tests {#[test]fn test_format_worktree_path_raw_branch() {- let wt_map = empty_worktree_map();+ let test = test_repo();// {{ branch }} without filter gives raw branch namelet config = UserConfig {configs: OverridableConfig {@@ -271,7 +291,7 @@ mod tests {};assert_eq!(config- .format_path("myproject", "feature/foo", "", &wt_map, None)+ .format_path("myproject", "feature/foo", &test.repo, None).unwrap(),"myproject.feature/foo");@@ -656,7 +676,7 @@ task2 = "echo 'Task 2 running' > task2.txt"fn test_expand_template_basic() {use std::collections::HashMap;- let wt_map = empty_worktree_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");vars.insert("branch", "feature-x");@@ -664,7 +684,7 @@ task2 = "echo 'Task 2 running' > task2.txt""../{{ main_worktree }}.{{ branch }}",&vars,true,- &wt_map,+ &test.repo,"test",).unwrap();@@ -675,7 +695,7 @@ task2 = "echo 'Task 2 running' > task2.txt"fn test_expand_template_sanitizes_branch() {use std::collections::HashMap;- let wt_map = empty_worktree_map();+ let test = test_repo();// Use {{ branch | sanitize }} filter for filesystem-safe paths// shell_escape=false to test filter in isolation (shell escaping tested separately)@@ -686,7 +706,7 @@ task2 = "echo 'Task 2 running' > task2.txt""{{ main_worktree }}/{{ branch | sanitize }}",&vars,false,- &wt_map,+ &test.repo,"test",).unwrap();@@ -699,7 +719,7 @@ task2 = "echo 'Task 2 running' > task2.txt"".worktrees/{{ main_worktree }}/{{ branch | sanitize }}",&vars,false,- &wt_map,+ &test.repo,"test",).unwrap();@@ -710,7 +730,6 @@ task2 = "echo 'Task 2 running' > task2.txt"fn test_expand_template_with_extra_vars() {use std::collections::HashMap;- let wt_map = empty_worktree_map();let mut vars = HashMap::new();vars.insert("worktree", "/path/to/worktree");vars.insert("repo_root", "/path/to/repo");@@ -719,7 +738,7 @@ task2 = "echo 'Task 2 running' > task2.txt""{{ repo_root }}/target -> {{ worktree }}/target",&vars,true,- &wt_map,+ &test_repo().repo,"test",).unwrap();diff --git a/src/config/project.rs b/src/config/project.rsindex efb7319a5..391f5b4ce 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -111,27 +111,10 @@ pub struct ProjectConfig {}impl ProjectConfig {- /// Load project configuration from a root path without git-specific features.+ /// Load project configuration from .config/wt.toml in the repository root///- /// Skips deprecation migration and unknown-field warnings (those require- /// git-specific context like main-worktree detection). Used by jj workspace- /// and other non-git contexts.- pub fn load_from_root(root: &std::path::Path) -> Result<Option<Self>, ConfigError> {- let config_path = root.join(".config").join("wt.toml");-- if !config_path.exists() {- return Ok(None);- }-- let contents = std::fs::read_to_string(&config_path)- .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;-- let config: ProjectConfig = toml::from_str(&contents)- .map_err(|e| ConfigError::Message(format!("Failed to parse TOML: {}", e)))?;-- Ok(Some(config))- }-+ /// Set `write_hints` to true for normal usage. Set to false during completion+ /// to avoid side effects (writing git config hints).pub fn load(repo: &crate::git::Repository,write_hints: bool,@@ -476,62 +459,4 @@ post-create = "npm install"let cloned = config.clone();assert_eq!(config, cloned);}-- #[test]- fn test_ci_platform() {- // No CI config- let config: ProjectConfig = toml::from_str("").unwrap();- assert_eq!(config.ci_platform(), None);-- // CI config with platform- let config: ProjectConfig = toml::from_str("[ci]\nplatform = \"github\"").unwrap();- assert_eq!(config.ci_platform(), Some("github"));- }-- #[test]- fn test_load_from_root_missing() {- let temp = tempfile::tempdir().unwrap();- let result = ProjectConfig::load_from_root(temp.path()).unwrap();- assert!(result.is_none());- }-- #[test]- fn test_load_from_root_valid() {- let temp = tempfile::tempdir().unwrap();- let config_dir = temp.path().join(".config");- std::fs::create_dir(&config_dir).unwrap();- std::fs::write(config_dir.join("wt.toml"), "[ci]\nplatform = \"gitlab\"\n").unwrap();- let config = ProjectConfig::load_from_root(temp.path()).unwrap().unwrap();- assert_eq!(config.ci_platform(), Some("gitlab"));- }-- #[test]- fn test_list_config_is_configured() {- assert!(!ProjectListConfig::default().is_configured());- let with_url = ProjectListConfig {- url: Some("http://localhost:3000".into()),- };- assert!(with_url.is_configured());- }-- #[test]- fn test_load_from_root_invalid_toml() {- let temp = tempfile::tempdir().unwrap();- let config_dir = temp.path().join(".config");- std::fs::create_dir(&config_dir).unwrap();- std::fs::write(config_dir.join("wt.toml"), "not valid [[ toml").unwrap();- let err = ProjectConfig::load_from_root(temp.path()).unwrap_err();- assert!(err.to_string().contains("Failed to parse TOML"));- }-- #[test]- fn test_load_from_root_unreadable() {- let temp = tempfile::tempdir().unwrap();- let config_dir = temp.path().join(".config");- std::fs::create_dir(&config_dir).unwrap();- // Create a directory where the file should be (causes read error)- std::fs::create_dir(config_dir.join("wt.toml")).unwrap();- let err = ProjectConfig::load_from_root(temp.path()).unwrap_err();- assert!(err.to_string().contains("Failed to read config file"));- }}diff --git a/src/config/test.rs b/src/config/test.rsindex 262a057d9..1af648184 100644--- a/src/config/test.rs+++ b/src/config/test.rs@@ -4,11 +4,30 @@//! edge cases in template variable substitution.use super::expand_template;+use crate::git::Repository;use std::collections::HashMap;-use std::path::PathBuf;-fn empty_map() -> HashMap<String, PathBuf> {- HashMap::new()+/// Test fixture that creates a real temporary git repository.+struct TestRepo {+ _dir: tempfile::TempDir,+ repo: Repository,+}++impl TestRepo {+ fn new() -> Self {+ let dir = tempfile::tempdir().unwrap();+ std::process::Command::new("git")+ .args(["init"])+ .current_dir(dir.path())+ .output()+ .unwrap();+ let repo = Repository::at(dir.path()).unwrap();+ Self { _dir: dir, repo }+ }+}++fn test_repo() -> TestRepo {+ TestRepo::new()}/// Helper to build vars with common fields@@ -22,13 +41,13 @@ fn vars_with_branch(branch: &str) -> HashMap<&str, &str> {#[test]fn test_expand_template_normal() {- let map = empty_map();+ let test = test_repo();let vars = vars_with_branch("feature");let result = expand_template("echo {{ branch }} {{ main_worktree }}",&vars,true,- &map,+ &test.repo,"test",).unwrap();@@ -37,20 +56,26 @@ fn test_expand_template_normal() {#[test]fn test_expand_template_branch_with_slashes() {- let map = empty_map();+ let test = test_repo();// Use {{ branch | sanitize }} to replace slashes with dasheslet vars = vars_with_branch("feature/nested/branch");- let result =- expand_template("echo {{ branch | sanitize }}", &vars, true, &map, "test").unwrap();+ let result = expand_template(+ "echo {{ branch | sanitize }}",+ &vars,+ true,+ &test.repo,+ "test",+ )+ .unwrap();assert_eq!(result, "echo feature-nested-branch");}#[test]fn test_expand_template_branch_raw_with_slashes() {- let map = empty_map();+ let test = test_repo();// Raw branch preserves slasheslet vars = vars_with_branch("feature/nested/branch");- let result = expand_template("echo {{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "echo feature/nested/branch");}@@ -58,13 +83,13 @@ fn test_expand_template_branch_raw_with_slashes() {#[test]#[cfg(unix)]fn test_expand_template_branch_escaping() {- let map = empty_map();+ let test = test_repo();let expand = |input| {expand_template("echo {{ branch }}",&vars_with_branch(input),true,- &map,+ &test.repo,"test",).unwrap()@@ -78,22 +103,22 @@ fn test_expand_template_branch_escaping() {#[test]#[cfg(unix)]fn snapshot_expand_template_branch_with_quotes() {- let map = empty_map();+ let test = test_repo();let vars = vars_with_branch("feature'test");- let result = expand_template("echo '{{ branch }}'", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo '{{ branch }}'", &vars, true, &test.repo, "test").unwrap();insta::assert_snapshot!(result, @r"echo ''feature'\''test''");}#[test]#[cfg(unix)]fn test_expand_template_extra_vars_path_escaping() {- let map = empty_map();+ let test = test_repo();let expand = |path| {expand_template("cd {{ worktree }}",&HashMap::from([("worktree", path)]),true,- &map,+ &test.repo,"test",).unwrap()@@ -109,31 +134,32 @@ fn test_expand_template_extra_vars_path_escaping() {#[test]#[cfg(unix)]fn snapshot_expand_template_extra_vars_with_command_substitution() {- let map = empty_map();+ let test = test_repo();let mut extras = HashMap::new();extras.insert("target", "main; rm -rf /");- let result = expand_template("git merge {{ target }}", &extras, true, &map, "test").unwrap();+ let result =+ expand_template("git merge {{ target }}", &extras, true, &test.repo, "test").unwrap();insta::assert_snapshot!(result, @"git merge 'main; rm -rf /'");}#[test]fn test_expand_template_variable_override() {- let map = empty_map();+ let test = test_repo();// Variables in the hashmap take precedencelet mut vars = HashMap::new();vars.insert("branch", "overridden");- let result = expand_template("echo {{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "echo overridden");}#[test]fn test_expand_template_missing_variable() {- let map = empty_map();+ let test = test_repo();// Undefined variables error in SemiStrict mode (catches typos)let vars: HashMap<&str, &str> = HashMap::new();- let result = expand_template("echo {{ undefined }}", &vars, true, &map, "test");+ let result = expand_template("echo {{ undefined }}", &vars, true, &test.repo, "test");assert!(result.is_err());assert!(result.unwrap_err().contains("undefined"));@@ -142,10 +168,10 @@ fn test_expand_template_missing_variable() {#[test]#[cfg(unix)]fn test_expand_template_empty_branch() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("branch", "");- let result = expand_template("echo {{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();// Empty string is shell-escaped to ''assert_eq!(result, "echo ''");@@ -154,10 +180,10 @@ fn test_expand_template_empty_branch() {#[test]#[cfg(unix)]fn test_expand_template_unicode_in_branch() {- let map = empty_map();+ let test = test_repo();// Unicode characters in branch name are shell-escapedlet vars = vars_with_branch("feature-\u{1F680}");- let result = expand_template("echo {{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();// Unicode is preserved but quoted for shell safetyassert_eq!(result, "echo 'feature-\u{1F680}'");@@ -165,12 +191,18 @@ fn test_expand_template_unicode_in_branch() {#[test]fn test_expand_template_backslash_in_branch() {- let map = empty_map();+ let test = test_repo();// Use {{ branch | sanitize }} to replace backslashes with dashes// Note: shell_escape=false to test sanitize filter in isolationlet vars = vars_with_branch("feature\\branch");- let result =- expand_template("path/{{ branch | sanitize }}", &vars, false, &map, "test").unwrap();+ let result = expand_template(+ "path/{{ branch | sanitize }}",+ &vars,+ false,+ &test.repo,+ "test",+ )+ .unwrap();// Backslashes are replaced with dashes by sanitize filterassert_eq!(result, "path/feature-branch");@@ -178,7 +210,7 @@ fn test_expand_template_backslash_in_branch() {#[test]fn test_expand_template_multiple_replacements() {- let map = empty_map();+ let test = test_repo();let mut vars = vars_with_branch("feature");vars.insert("worktree", "/path/to/wt");vars.insert("target", "develop");@@ -187,7 +219,7 @@ fn test_expand_template_multiple_replacements() {"cd {{ worktree }} && git merge {{ target }} from {{ branch }}",&vars,true,- &map,+ &test.repo,"test",).unwrap();@@ -197,21 +229,27 @@ fn test_expand_template_multiple_replacements() {#[test]fn test_expand_template_curly_braces_without_variables() {- let map = empty_map();+ let test = test_repo();// Just curly braces, not variableslet vars: HashMap<&str, &str> = HashMap::new();- let result = expand_template("echo {}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {}", &vars, true, &test.repo, "test").unwrap();assert_eq!(result, "echo {}");}#[test]fn test_expand_template_nested_curly_braces() {- let map = empty_map();+ let test = test_repo();// Nested braces - minijinja doesn't support {{{ syntax, use literal curly braces insteadlet vars = vars_with_branch("main");- let result =- expand_template("echo {{ '{' ~ branch ~ '}' }}", &vars, true, &map, "test").unwrap();+ let result = expand_template(+ "echo {{ '{' ~ branch ~ '}' }}",+ &vars,+ true,+ &test.repo,+ "test",+ )+ .unwrap();// Renders as '{main}' — curly braces are shell metacharacters (brace expansion)// so the formatter correctly escapes the concatenated result@@ -242,11 +280,11 @@ fn snapshot_shell_escaping_special_chars() {("brackets", "feature[0-9]"),];- let map = empty_map();+ let test = test_repo();let mut results = Vec::new();for (name, branch) in test_cases {let vars = vars_with_branch(branch);- let result = expand_template("echo {{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();results.push((name, branch, result));}@@ -264,11 +302,11 @@ fn snapshot_shell_escaping_quotes() {("multiple_single", "don't'panic"),];- let map = empty_map();+ let test = test_repo();let mut results = Vec::new();for (name, branch) in test_cases {let vars = vars_with_branch(branch);- let result = expand_template("echo {{ branch }}", &vars, true, &map, "test").unwrap();+ let result = expand_template("echo {{ branch }}", &vars, true, &test.repo, "test").unwrap();results.push((name, branch, result));}@@ -287,7 +325,7 @@ fn snapshot_shell_escaping_paths() {("unicode", "/path/to/\u{1F680}/worktree"),];- let map = empty_map();+ let test = test_repo();let mut results = Vec::new();for (name, path) in test_cases {let mut vars = vars_with_branch("main");@@ -296,7 +334,7 @@ fn snapshot_shell_escaping_paths() {"cd {{ worktree }} && echo {{ branch }}",&vars,true,- &map,+ &test.repo,"test",).unwrap();@@ -329,7 +367,7 @@ fn snapshot_complex_templates() {),];- let map = empty_map();+ let test = test_repo();let mut results = Vec::new();for (name, template, branch) in test_cases {let mut vars = HashMap::new();@@ -337,7 +375,7 @@ fn snapshot_complex_templates() {vars.insert("main_worktree", "/repo/path");vars.insert("worktree", "/path with spaces/wt");vars.insert("target", "main; rm -rf /");- let result = expand_template(template, &vars, true, &map, "test").unwrap();+ let result = expand_template(template, &vars, true, &test.repo, "test").unwrap();results.push((name, template, branch, result));}@@ -348,7 +386,7 @@ fn snapshot_complex_templates() {#[test]fn test_expand_template_literal_normal() {- let map = empty_map();+ let test = test_repo();let mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");vars.insert("branch", "feature");@@ -356,7 +394,7 @@ fn test_expand_template_literal_normal() {"{{ main_worktree }}.{{ branch }}",&vars,false,- &map,+ &test.repo,"test",).unwrap();@@ -365,7 +403,7 @@ fn test_expand_template_literal_normal() {#[test]fn test_expand_template_literal_unicode_no_escaping() {- let map = empty_map();+ let test = test_repo();// Unicode should NOT be shell-escaped in filesystem pathslet mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");@@ -374,7 +412,7 @@ fn test_expand_template_literal_unicode_no_escaping() {"{{ main_worktree }}.{{ branch }}",&vars,false,- &map,+ &test.repo,"test",).unwrap();@@ -388,7 +426,7 @@ fn test_expand_template_literal_unicode_no_escaping() {#[test]fn test_expand_template_literal_spaces_no_escaping() {- let map = empty_map();+ let test = test_repo();// Spaces should NOT be shell-escaped (filesystem paths can have spaces)let mut vars = HashMap::new();vars.insert("main_worktree", "my repo");@@ -397,7 +435,7 @@ fn test_expand_template_literal_spaces_no_escaping() {"{{ main_worktree }}.{{ branch }}",&vars,false,- &map,+ &test.repo,"test",).unwrap();@@ -411,7 +449,7 @@ fn test_expand_template_literal_spaces_no_escaping() {#[test]fn test_expand_template_literal_sanitizes_slashes() {- let map = empty_map();+ let test = test_repo();// Use {{ branch | sanitize }} to replace slashes with dasheslet mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");@@ -420,7 +458,7 @@ fn test_expand_template_literal_sanitizes_slashes() {"{{ main_worktree }}.{{ branch | sanitize }}",&vars,false,- &map,+ &test.repo,"test",).unwrap();@@ -430,15 +468,15 @@ fn test_expand_template_literal_sanitizes_slashes() {#[test]#[cfg(unix)]fn test_expand_template_literal_vs_escaped_unicode() {- let map = empty_map();+ let test = test_repo();// Demonstrate the difference between literal and escaped expansionlet mut vars = HashMap::new();vars.insert("main_worktree", "myrepo");vars.insert("branch", "test-\u{2282}");let template = "{{ main_worktree }}.{{ branch }}";- let literal_result = expand_template(template, &vars, false, &map, "test").unwrap();- let escaped_result = expand_template(template, &vars, true, &map, "test").unwrap();+ let literal_result = expand_template(template, &vars, false, &test.repo, "test").unwrap();+ let escaped_result = expand_template(template, &vars, true, &test.repo, "test").unwrap();// Literal has no quotesassert_eq!(literal_result, "myrepo.test-\u{2282}");diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rsindex eb67caf9f..8413fe927 100644--- a/src/config/user/accessors.rs+++ b/src/config/user/accessors.rs@@ -4,7 +4,6 @@//! project by merging global settings with project-specific overrides.use std::collections::HashMap;-use std::path::PathBuf;use crate::config::HooksConfig;use crate::config::expansion::expand_template;@@ -154,16 +153,14 @@ impl UserConfig {/// # Arguments/// * `main_worktree` - Main worktree directory name (replaces {{ main_worktree }} in template)/// * `branch` - Branch name (replaces {{ branch }} in template; use `{{ branch | sanitize }}` for paths)- /// * `repo_path` - Repository root path (replaces {{ repo_path }} in template)- /// * `worktree_map` - Branch-to-path lookup for `worktree_path_of_branch()` function+ /// * `repo` - Repository for template function access/// * `project` - Optional project identifier (e.g., "github.com/user/repo") to look up/// project-specific worktree-path templatepub fn format_path(&self,main_worktree: &str,branch: &str,- repo_path: &str,- worktree_map: &HashMap<String, PathBuf>,+ repo: &crate::git::Repository,project: Option<&str>,) -> Result<String, String> {let template = match project {@@ -171,12 +168,13 @@ impl UserConfig {None => self.worktree_path(),};// Use native path format (not POSIX) since this is used for filesystem operations+ let repo_path = repo.repo_path().to_string_lossy().to_string();let mut vars = HashMap::new();vars.insert("main_worktree", main_worktree);vars.insert("repo", main_worktree);vars.insert("branch", branch);- vars.insert("repo_path", repo_path);- expand_template(&template, &vars, false, worktree_map, "worktree-path")+ vars.insert("repo_path", repo_path.as_str());+ expand_template(&template, &vars, false, repo, "worktree-path").map(|p| shellexpand::tilde(&p).into_owned())}}diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex dcdc65ced..ea61cddd6 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -1,14 +1,7 @@-use std::collections::HashMap;-use std::path::PathBuf;-use super::*;use crate::config::HooksConfig;use crate::git::Repository;-fn empty_worktree_map() -> HashMap<String, PathBuf> {- HashMap::new()-}-/// Test fixture that creates a real temporary git repository.struct TestRepo {_dir: tempfile::TempDir,@@ -243,7 +236,7 @@ fn test_worktree_path_for_project_falls_back_to_default() {#[test]fn test_format_path_with_project_override() {- let wt_map = empty_worktree_map();+ let test = test_repo();let mut config = UserConfig {configs: OverridableConfig {worktree_path: Some("../{{ repo }}.{{ branch | sanitize }}".to_string()),@@ -268,8 +261,7 @@ fn test_format_path_with_project_override() {.format_path("myrepo","feature/branch",- "",- &wt_map,+ &test.repo,Some("github.com/user/repo"),).unwrap();@@ -277,7 +269,7 @@ fn test_format_path_with_project_override() {// Without project identifier, should use global templatelet path = config- .format_path("myrepo", "feature/branch", "", &wt_map, None)+ .format_path("myrepo", "feature/branch", &test.repo, None).unwrap();assert_eq!(path, "../myrepo.feature-branch");}@@ -420,11 +412,9 @@ fn test_is_command_approved_normalizes_multiple_vars() {#[test]fn test_worktrunk_config_format_path() {let test = test_repo();- let wt_map = empty_worktree_map();- let repo_path_str = test.repo.repo_path().to_string_lossy().to_string();let config = UserConfig::default();let path = config- .format_path("myrepo", "feature/branch", &repo_path_str, &wt_map, None)+ .format_path("myrepo", "feature/branch", &test.repo, None).unwrap();// Default path is now absolute: {{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}// The template uses forward slashes which work on all platforms@@ -439,15 +429,16 @@ fn test_worktrunk_config_format_path() {"Expected path containing parent navigation, got: {path}");// The path should start with the repo path (absolute)+ let repo_path = test.repo.repo_path().to_string_lossy();assert!(- path.starts_with(&repo_path_str),- "Expected path starting with repo path '{repo_path_str}', got: {path}"+ path.starts_with(repo_path.as_ref()),+ "Expected path starting with repo path '{repo_path}', got: {path}");}#[test]fn test_worktrunk_config_format_path_custom_template() {- let wt_map = empty_worktree_map();+ let test = test_repo();let config = UserConfig {configs: OverridableConfig {worktree_path: Some(".worktrees/{{ branch }}".to_string()),@@ -456,7 +447,7 @@ fn test_worktrunk_config_format_path_custom_template() {..Default::default()};let path = config- .format_path("myrepo", "feature", "", &wt_map, None)+ .format_path("myrepo", "feature", &test.repo, None).unwrap();assert_eq!(path, ".worktrees/feature");}@@ -464,8 +455,6 @@ fn test_worktrunk_config_format_path_custom_template() {#[test]fn test_worktrunk_config_format_path_repo_path_variable() {let test = test_repo();- let wt_map = empty_worktree_map();- let repo_path_str = test.repo.repo_path().to_string_lossy().to_string();let config = UserConfig {configs: OverridableConfig {// Use forward slashes in template (works on all platforms)@@ -475,7 +464,7 @@ fn test_worktrunk_config_format_path_repo_path_variable() {..Default::default()};let path = config- .format_path("myrepo", "feature/branch", &repo_path_str, &wt_map, None)+ .format_path("myrepo", "feature/branch", &test.repo, None).unwrap();// Path should contain the expected componentsassert!(@@ -483,9 +472,10 @@ fn test_worktrunk_config_format_path_repo_path_variable() {"Expected path containing 'worktrees' and 'feature-branch', got: {path}");// The path should start with the repo path+ let repo_path = test.repo.repo_path().to_string_lossy();assert!(- path.starts_with(&repo_path_str),- "Expected path starting with repo path '{repo_path_str}', got: {path}"+ path.starts_with(repo_path.as_ref()),+ "Expected path starting with repo path '{repo_path}', got: {path}");// The path should be absolute since repo_path is absoluteassert!(@@ -496,7 +486,7 @@ fn test_worktrunk_config_format_path_repo_path_variable() {#[test]fn test_worktrunk_config_format_path_tilde_expansion() {- let wt_map = empty_worktree_map();+ let test = test_repo();let config = UserConfig {configs: OverridableConfig {worktree_path: Some("~/worktrees/{{ repo }}/{{ branch | sanitize }}".to_string()),@@ -505,7 +495,7 @@ fn test_worktrunk_config_format_path_tilde_expansion() {..Default::default()};let path = config- .format_path("myrepo", "feature/branch", "", &wt_map, None)+ .format_path("myrepo", "feature/branch", &test.repo, None).unwrap();// Tilde should be expanded to home directoryassert!(diff --git a/src/git/diff.rs b/src/git/diff.rsindex d3e52adcd..5e9eaab9d 100644--- a/src/git/diff.rs+++ b/src/git/diff.rs@@ -3,8 +3,12 @@use ansi_str::AnsiStr;use color_print::cformat;-// Re-export LineDiff from its canonical location for backward compatibility.-pub use crate::workspace::types::LineDiff;+/// Line-level diff totals (added/deleted counts) used across git operations.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]+pub struct LineDiff {+ pub added: usize,+ pub deleted: usize,+}/// Parse a git numstat line and extract insertions/deletions.///@@ -47,6 +51,25 @@ impl LineDiff {Ok(totals)}++ pub fn is_empty(&self) -> bool {+ self.added == 0 && self.deleted == 0+ }+}++impl From<LineDiff> for (usize, usize) {+ fn from(diff: LineDiff) -> Self {+ (diff.added, diff.deleted)+ }+}++impl From<(usize, usize)> for LineDiff {+ fn from(value: (usize, usize)) -> Self {+ Self {+ added: value.0,+ deleted: value.1,+ }+ }}/// Diff statistics (files changed, insertions, deletions).diff --git a/src/git/mod.rs b/src/git/mod.rsindex 0c91b4280..e5836ccc4 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -48,15 +48,85 @@ pub use error::{exit_code,};pub use parse::{parse_porcelain_z, parse_untracked_files};-pub(crate) use repository::path_to_logging_context;-pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree};+pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};pub use url::GitRemoteUrl;pub use url::{parse_owner_repo, parse_remote_owner};+/// Why branch content is considered integrated into the target branch.+///+/// Used by both `wt list` (for status symbols) and `wt remove` (for messages).+/// Each variant corresponds to a specific integration check. In `wt list`,+/// three symbols represent these checks:+/// - `_` for [`SameCommit`](Self::SameCommit) with clean working tree (empty)+/// - `–` for [`SameCommit`](Self::SameCommit) with dirty working tree+/// - `⊂` for all others (content integrated via different history)+///+/// The checks are ordered by cost (cheapest first):+/// 1. [`SameCommit`](Self::SameCommit) - commit SHA comparison (~1ms)+/// 2. [`Ancestor`](Self::Ancestor) - ancestor check (~1ms)+/// 3. [`NoAddedChanges`](Self::NoAddedChanges) - three-dot diff (~50-100ms)+/// 4. [`TreesMatch`](Self::TreesMatch) - tree SHA comparison (~100-300ms)+/// 5. [`MergeAddsNothing`](Self::MergeAddsNothing) - merge simulation (~500ms-2s)+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, strum::IntoStaticStr)]+#[serde(rename_all = "kebab-case")]+#[strum(serialize_all = "kebab-case")]+pub enum IntegrationReason {+ /// Branch HEAD is literally the same commit as target.+ ///+ /// Used by `wt remove` to determine if branch is safely deletable.+ /// In `wt list`, same-commit state is shown via `MainState::Empty` (`_`) or+ /// `MainState::SameCommit` (`–`) depending on working tree cleanliness.+ SameCommit,++ /// Branch HEAD is an ancestor of target (target has moved past this branch).+ ///+ /// Symbol in `wt list`: `⊂`+ Ancestor,++ /// Three-dot diff (`main...branch`) shows no files.+ /// The branch has no file changes beyond the merge-base.+ ///+ /// Symbol in `wt list`: `⊂`+ NoAddedChanges,++ /// Branch tree SHA equals target tree SHA.+ /// Commit history differs but file contents are identical.+ ///+ /// Symbol in `wt list`: `⊂`+ TreesMatch,++ /// Simulated merge (`git merge-tree`) produces the same tree as target.+ /// The branch has changes, but they're already in target via a different path.+ ///+ /// Symbol in `wt list`: `⊂`+ MergeAddsNothing,+}++impl IntegrationReason {+ /// Human-readable description for use in messages (e.g., `wt remove` output).+ ///+ /// Returns a phrase that expects the target branch name to follow+ /// (e.g., "same commit as" + "main" → "same commit as main").+ pub fn description(&self) -> &'static str {+ match self {+ Self::SameCommit => "same commit as",+ Self::Ancestor => "ancestor of",+ Self::NoAddedChanges => "no added changes on",+ Self::TreesMatch => "tree matches",+ Self::MergeAddsNothing => "all changes in",+ }+ }-// Re-export shared types from workspace::types for backward compatibility.-// These types are VCS-agnostic and defined in workspace::types, but historically-// lived here. All existing `use crate::git::LineDiff` imports continue working.-pub use crate::workspace::types::{IntegrationReason, path_dir_name};+ /// Status symbol used in `wt list` for this integration reason.+ ///+ /// - `SameCommit` → `_` (matches `MainState::Empty`)+ /// - Others → `⊂` (matches `MainState::Integrated`)+ pub fn symbol(&self) -> &'static str {+ match self {+ Self::SameCommit => "_",+ _ => "⊂",+ }+ }+}/// Integration signals for checking if a branch is integrated into target.///@@ -362,6 +432,16 @@ pub struct WorktreeInfo {pub prunable: Option<String>,}+/// Extract the directory name from a path for display purposes.+///+/// Returns the last component of the path as a string, or "(unknown)" if+/// the path has no filename or contains invalid UTF-8.+pub fn path_dir_name(path: &std::path::Path) -> &str {+ path.file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("(unknown)")+}+impl WorktreeInfo {/// Returns true if this worktree is prunable (directory deleted but git still tracks metadata).///diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex c1ee836f4..863778a61 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -308,28 +308,6 @@ impl Repository {LineDiff::from_numstat(&stdout)}- /// Whether HEAD is linearly rebased onto `target`.- ///- /// Returns `true` when merge-base equals the target SHA and there are no- /// merge commits between target and HEAD (i.e., history is linear).- pub fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {- let Some(merge_base) = self.merge_base("HEAD", target)? else {- return Ok(false);- };- let target_sha = self.run_command(&["rev-parse", target])?.trim().to_string();-- if merge_base != target_sha {- return Ok(false);- }-- let merge_commits = self- .run_command(&["rev-list", "--merges", &format!("{target}..HEAD")])?- .trim()- .to_string();-- Ok(merge_commits.is_empty())- }-/// Get formatted diff stats summary for display.////// Returns a vector of formatted strings like ["3 files", "+45", "-12"].diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex ab891cc59..cb2b16bc5 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -20,7 +20,7 @@ use std::io::{BufRead, BufReader, Write};use std::path::{Path, PathBuf};use std::process::Stdio;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, Mutex};+use std::sync::{Arc, LazyLock, Mutex, OnceLock};use std::thread;use std::time::{Duration, Instant};@@ -54,7 +54,7 @@ mod worktrees;// Re-export WorkingTree and Branchpub use branch::Branch;pub use working_tree::WorkingTree;-pub(crate) use working_tree::path_to_logging_context;+pub(super) use working_tree::path_to_logging_context;/// Structured error from [`Repository::run_command_delayed_stream`].///@@ -150,6 +150,25 @@ pub enum ResolvedWorktree {},}+/// Global base path for repository operations, set by -C flag.+static BASE_PATH: OnceLock<PathBuf> = OnceLock::new();++/// Default base path when -C flag is not provided.+static DEFAULT_BASE_PATH: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("."));++/// Initialize the global base path for repository operations.+///+/// This should be called once at program startup from main().+/// If not called, defaults to "." (current directory).+pub fn set_base_path(path: PathBuf) {+ BASE_PATH.set(path).ok();+}++/// Get the base path for repository operations.+fn base_path() -> &'static PathBuf {+ BASE_PATH.get().unwrap_or(&DEFAULT_BASE_PATH)+}+/// Repository state for git operations.////// Represents the shared state of a git repository (the `.git` directory).@@ -194,7 +213,7 @@ impl Repository {/// For worktree-specific operations on paths other than cwd, use/// `repo.worktree_at(path)` to get a [`WorkingTree`].pub fn current() -> anyhow::Result<Self> {- Self::at(".")+ Self::at(base_path().clone())}/// Discover the repository from the specified path.@@ -270,7 +289,7 @@ impl Repository {////// This is the primary way to get a [`WorkingTree`] for worktree-specific operations.pub fn current_worktree(&self) -> WorkingTree<'_> {- self.worktree_at(".")+ self.worktree_at(base_path().clone())}/// Get a worktree view at a specific path.diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex fdaf373f6..d88f403a9 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -59,7 +59,7 @@ impl<'a> WorkingTree<'a> {/// Get the path this WorkingTree was created with.///- /// This is the path passed to `worktree_at()` (or `"."` for `current_worktree()`).+ /// This is the path passed to `worktree_at()` or `base_path()` for `current_worktree()`./// For the canonical git-determined root, use [`root()`](Self::root) instead.pub fn path(&self) -> &Path {&self.pathdiff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex f8f2cb967..b446b83d1 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -99,33 +99,6 @@ impl Repository {Ok(())}- /// Create a new worktree with a new branch.- ///- /// Runs `git worktree add -b <branch> <path> [<base>]` to create a worktree- /// at `path` on a new branch `branch`, optionally starting from `base`.- pub fn create_worktree(- &self,- branch: &str,- base: Option<&str>,- path: &Path,- ) -> anyhow::Result<()> {- let path_str = path.to_str().ok_or_else(|| {- anyhow::Error::from(GitError::Other {- message: format!(- "Worktree path contains invalid UTF-8: {}",- format_path_for_display(path)- ),- })- })?;-- let mut args = vec!["worktree", "add", "-b", branch, path_str];- if let Some(base_ref) = base {- args.push(base_ref);- }- self.run_command(&args)?;- Ok(())- }-/// Remove a worktree at the specified path.////// When `force` is true, passes `--force` to `git worktree remove`,diff --git a/src/lib.rs b/src/lib.rsindex 90fd29e93..0b744b8dd 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -16,7 +16,6 @@ pub mod styling;pub mod sync;pub mod trace;pub mod utils;-pub mod workspace;// Re-export HookType for conveniencepub use git::HookType;diff --git a/src/llm.rs b/src/llm.rsindex 300acadfd..76b099917 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -1,9 +1,10 @@use anyhow::Context;use shell_escape::escape;use std::borrow::Cow;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use worktrunk::config::CommitGenerationConfig;+use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;use worktrunk::shell_exec::{Cmd, ShellConfig};use worktrunk::styling::{eprintln, warning_message};@@ -288,7 +289,7 @@ const DEFAULT_SQUASH_TEMPLATE: &str = r#"Combine these commits into a single com////// This is the canonical way to execute LLM commands in this codebase./// All LLM execution should go through this function to maintain consistency.-pub(crate) fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result<String> {+fn execute_llm_command(command: &str, prompt: &str) -> anyhow::Result<String> {// Log prompt for debugging (Cmd logs the command itself)log::debug!(" Prompt (stdin):");for line in prompt.lines() {@@ -459,24 +460,14 @@ fn build_prompt(Ok(rendered)}-/// Pre-computed VCS-agnostic data needed for commit prompt/message generation.-pub(crate) struct CommitInput<'a> {- pub diff: &'a str,- pub diff_stat: &'a str,- pub branch: &'a str,- pub repo_name: &'a str,- pub recent_commits: Option<&'a Vec<String>>,-}-pub(crate) fn generate_commit_message(- input: &CommitInput<'_>,commit_generation_config: &CommitGenerationConfig,) -> anyhow::Result<String> {// Check if commit generation is configured (non-empty command)if commit_generation_config.is_configured() {let command = commit_generation_config.command.as_ref().unwrap();- let prompt = build_commit_prompt(input, commit_generation_config)?;- return execute_llm_command(command, &prompt).map_err(|e| {+ // Commit generation is explicitly configured - fail if it doesn't work+ return try_generate_commit_message(command, commit_generation_config).map_err(|e| {worktrunk::git::GitError::LlmCommandFailed {command: command.clone(),error: e.to_string(),@@ -489,71 +480,111 @@ pub(crate) fn generate_commit_message(});}- // Fallback: generate a descriptive commit message based on changed files.- // Parses diffstat lines (e.g. " src/foo.rs | 3 +") — works for both git and jj- // but may mis-parse filenames containing '|' (rare, low-stakes fallback).- let files: Vec<&str> = input- .diff_stat- .lines()- .filter(|l| l.contains('|'))- .map(|l| l.split('|').next().unwrap_or("").trim())+ // Fallback: generate a descriptive commit message based on changed files+ let repo = Repository::current()?;+ // Use -z for NUL-separated output to handle filenames with spaces/newlines+ let file_list = repo.run_command(&["diff", "--staged", "--name-only", "-z"])?;+ let staged_files = file_list+ .split('\0')+ .map(|s| s.trim()).filter(|s| !s.is_empty())- .map(|path| path.rsplit('/').next().unwrap_or(path))- .collect();-- let message = match files.len() {+ .map(|path| {+ Path::new(path)+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or(path)+ })+ .collect::<Vec<_>>();++ let message = match staged_files.len() {0 => "WIP: Changes".to_string(),- 1 => format!("Changes to {}", files[0]),- 2 => format!("Changes to {} & {}", files[0], files[1]),- 3 => format!("Changes to {}, {} & {}", files[0], files[1], files[2]),+ 1 => format!("Changes to {}", staged_files[0]),+ 2 => format!("Changes to {} & {}", staged_files[0], staged_files[1]),+ 3 => format!(+ "Changes to {}, {} & {}",+ staged_files[0], staged_files[1], staged_files[2]+ ),n => format!("Changes to {} files", n),};Ok(message)}-/// Build the commit prompt from pre-computed VCS-agnostic data.-///-/// Accepts diff, branch name, repo name, and recent commits, then renders-/// the prompt template. Used by both normal commit generation and `--show-prompt`.-pub(crate) fn build_commit_prompt(- input: &CommitInput<'_>,+fn try_generate_commit_message(+ command: &str,config: &CommitGenerationConfig,) -> anyhow::Result<String> {- let prepared = prepare_diff(input.diff.to_string(), input.diff_stat.to_string());+ let prompt = build_commit_prompt(config)?;+ execute_llm_command(command, &prompt)+}++/// Build the commit prompt from staged changes.+///+/// Gathers the staged diff, branch name, repo name, and recent commits, then renders+/// the prompt template. Used by both normal commit generation and `--show-prompt`.+pub(crate) fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<String> {+ let repo = Repository::current()?;++ // Get staged diff and diffstat+ // Use -c flags to ensure consistent format regardless of user's git config+ // (diff.noprefix, diff.mnemonicPrefix, etc. could break our parsing)+ let diff_output = repo.run_command(&[+ "-c",+ "diff.noprefix=false",+ "-c",+ "diff.mnemonicPrefix=false",+ "--no-pager",+ "diff",+ "--staged",+ ])?;+ let diff_stat = repo.run_command(&["--no-pager", "diff", "--staged", "--stat"])?;++ // Prepare diff (may filter if too large)+ let prepared = prepare_diff(diff_output, diff_stat);++ // Get current branch and repo root+ let wt = repo.current_worktree();+ let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());+ let repo_root = wt.root()?;+ let repo_name = repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let recent_commits = repo.recent_commit_subjects(None, 5);let context = TemplateContext {git_diff: &prepared.diff,git_diff_stat: &prepared.stat,- branch: input.branch,- recent_commits: input.recent_commits,- repo_name: input.repo_name,+ branch: ¤t_branch,+ recent_commits: recent_commits.as_ref(),+ repo_name,commits: &[],target_branch: None,};build_prompt(config, TemplateType::Commit, &context)}-/// Pre-computed VCS-agnostic data needed for squash prompt/message generation.-pub(crate) struct SquashInput<'a> {- pub target_branch: &'a str,- pub diff: &'a str,- pub diff_stat: &'a str,- pub subjects: &'a [String],- pub current_branch: &'a str,- pub repo_name: &'a str,- pub recent_commits: Option<&'a Vec<String>>,-}-pub(crate) fn generate_squash_message(- input: &SquashInput<'_>,+ target_branch: &str,+ merge_base: &str,+ subjects: &[String],+ current_branch: &str,+ repo_name: &str,commit_generation_config: &CommitGenerationConfig,) -> anyhow::Result<String> {// Check if commit generation is configured (non-empty command)if commit_generation_config.is_configured() {let command = commit_generation_config.command.as_ref().unwrap();- let prompt = build_squash_prompt(input, commit_generation_config)?;+ let prompt = build_squash_prompt(+ target_branch,+ merge_base,+ subjects,+ current_branch,+ repo_name,+ commit_generation_config,+ )?;return execute_llm_command(command, &prompt).map_err(|e| {worktrunk::git::GitError::LlmCommandFailed {@@ -569,9 +600,9 @@ pub(crate) fn generate_squash_message(}// Fallback: deterministic commit message (only when not configured)- let mut commit_message = format!("Squash commits from {}\n\n", input.target_branch);+ let mut commit_message = format!("Squash commits from {}\n\n", target_branch);commit_message.push_str("Combined commits:\n");- for subject in input.subjects.iter().rev() {+ for subject in subjects.iter().rev() {// Reverse so they're in chronological ordercommit_message.push_str(&format!("- {}\n", subject));}@@ -580,23 +611,44 @@ pub(crate) fn generate_squash_message(/// Build the squash prompt from commits being squashed.///-/// Accepts pre-computed diff data (from the Workspace trait), making this-/// VCS-agnostic. Used by both normal squash generation and `--show-prompt`.+/// Gathers the combined diff, commit subjects, branch names, and recent commits, then+/// renders the prompt template. Used by both normal squash generation and `--show-prompt`.pub(crate) fn build_squash_prompt(- input: &SquashInput<'_>,+ target_branch: &str,+ merge_base: &str,+ subjects: &[String],+ current_branch: &str,+ repo_name: &str,config: &CommitGenerationConfig,) -> anyhow::Result<String> {+ let repo = Repository::current()?;++ // Get the combined diff and diffstat for all commits being squashed+ // Use -c flags to ensure consistent format regardless of user's git config+ let diff_output = repo.run_command(&[+ "-c",+ "diff.noprefix=false",+ "-c",+ "diff.mnemonicPrefix=false",+ "--no-pager",+ "diff",+ merge_base,+ "HEAD",+ ])?;+ let diff_stat = repo.run_command(&["--no-pager", "diff", merge_base, "HEAD", "--stat"])?;+// Prepare diff (may filter if too large)- let prepared = prepare_diff(input.diff.to_string(), input.diff_stat.to_string());+ let prepared = prepare_diff(diff_output, diff_stat);+ let recent_commits = repo.recent_commit_subjects(Some(merge_base), 5);let context = TemplateContext {git_diff: &prepared.diff,git_diff_stat: &prepared.stat,- branch: input.current_branch,- recent_commits: input.recent_commits,- repo_name: input.repo_name,- commits: input.subjects,- target_branch: Some(input.target_branch),+ branch: current_branch,+ recent_commits: recent_commits.as_ref(),+ repo_name,+ commits: subjects,+ target_branch: Some(target_branch),};build_prompt(config, TemplateType::Squash, &context)}@@ -1364,91 +1416,4 @@ diff --git a/Cargo.lock b/Cargo.lockassert!(!is_lock_file("README.md"));assert!(!is_lock_file("config.toml"));}-- #[test]- fn test_build_commit_prompt_with_commit_input() {- let config = CommitGenerationConfig::default();- let input = CommitInput {- diff: "+++ new_file.rs\n+fn main() {}\n",- diff_stat: "new_file.rs | 1 +\n1 file changed, 1 insertion(+)",- branch: "feature-ws",- repo_name: "myrepo",- recent_commits: None,- };- let result = build_commit_prompt(&input, &config);- assert!(result.is_ok());- let prompt = result.unwrap();- assert!(prompt.contains("new_file.rs"));- assert!(prompt.contains("feature-ws"));- }-- #[test]- fn test_generate_commit_message_fallback_single_file() {- let config = CommitGenerationConfig::default();- let input = CommitInput {- diff: "",- diff_stat: " src/main.rs | 3 +++\n 1 file changed, 3 insertions(+)",- branch: "main",- repo_name: "test",- recent_commits: None,- };- let msg = generate_commit_message(&input, &config).unwrap();- assert_eq!(msg, "Changes to main.rs");- }-- #[test]- fn test_generate_commit_message_fallback_two_files() {- let config = CommitGenerationConfig::default();- let input = CommitInput {- diff: "",- diff_stat: " src/lib.rs | 1 +\n src/main.rs | 2 ++\n 2 files changed",- branch: "main",- repo_name: "test",- recent_commits: None,- };- let msg = generate_commit_message(&input, &config).unwrap();- assert_eq!(msg, "Changes to lib.rs & main.rs");- }-- #[test]- fn test_generate_commit_message_fallback_three_files() {- let config = CommitGenerationConfig::default();- let input = CommitInput {- diff: "",- diff_stat: " src/lib.rs | 1 +\n src/main.rs | 2 ++\n src/util.rs | 5 ++---\n 3 files changed",- branch: "main",- repo_name: "test",- recent_commits: None,- };- let msg = generate_commit_message(&input, &config).unwrap();- assert_eq!(msg, "Changes to lib.rs, main.rs & util.rs");- }-- #[test]- fn test_generate_commit_message_fallback_no_files() {- let config = CommitGenerationConfig::default();- let input = CommitInput {- diff: "",- diff_stat: "",- branch: "main",- repo_name: "test",- recent_commits: None,- };- let msg = generate_commit_message(&input, &config).unwrap();- assert_eq!(msg, "WIP: Changes");- }-- #[test]- fn test_generate_commit_message_fallback_many_files() {- let config = CommitGenerationConfig::default();- let input = CommitInput {- diff: "",- diff_stat: " a.rs | 1 +\n b.rs | 1 +\n c.rs | 1 +\n d.rs | 1 +\n 4 files changed",- branch: "main",- repo_name: "test",- recent_commits: None,- };- let msg = generate_commit_message(&input, &config).unwrap();- assert_eq!(msg, "Changes to 4 files");- }}diff --git a/src/main.rs b/src/main.rsindex e0d7c24bf..f0a5a8bad 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,3 +1,4 @@+use std::collections::HashSet;use std::io::Write;use anyhow::Context;@@ -6,7 +7,7 @@ use clap::error::ErrorKind as ClapErrorKind;use color_print::{ceprintln, cformat};use std::process;use worktrunk::config::{UserConfig, set_config_path};-use worktrunk::git::exit_code;+use worktrunk::git::{Repository, ResolvedWorktree, exit_code, set_base_path};use worktrunk::path::format_path_for_display;use worktrunk::shell::extract_filename_from_path;use worktrunk::styling::{@@ -14,7 +15,10 @@ use worktrunk::styling::{warning_message,};+use commands::command_approval::approve_hooks;+use commands::context::CommandEnv;use commands::list::progressive::RenderMode;+use commands::worktree::RemoveResult;mod cli;mod commands;@@ -39,15 +43,18 @@ pub(crate) use crate::cli::OutputFormat;#[cfg(unix)]use commands::handle_select;+use commands::worktree::handle_push;use commands::{- MergeOptions, RebaseResult, RemoveOptions, SquashResult, SwitchOptions, add_approvals,+ MergeOptions, OperationMode, RebaseResult, SquashResult, SwitchOptions, add_approvals,clear_approvals, handle_completions, handle_config_create, handle_config_show,handle_configure_shell, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,- handle_list, handle_logs_get, handle_merge, handle_rebase, handle_remove_command,- handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,- handle_state_set, handle_state_show, handle_switch, handle_unconfigure_shell, run_hook,- step_commit, step_copy_ignored, step_for_each, step_push, step_relocate,+ handle_list, handle_logs_get, handle_merge, handle_rebase, handle_remove,+ handle_remove_current, handle_show_theme, handle_squash, handle_state_clear,+ handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show, handle_switch,+ handle_unconfigure_shell, resolve_worktree_arg, run_hook, step_commit, step_copy_ignored,+ step_for_each, step_relocate,};+use output::handle_remove_output;use cli::{ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigCommand, ConfigShellCommand,@@ -123,23 +130,9 @@ fn main() {});let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());- // Change working directory from -C flag if provided.- // This affects ALL code (git, jj, etc.) that uses relative paths or current_dir().- // Note: $PWD (used for symlink-aware path display) is not updated because set_var- // is unsafe. This means paths may display canonically when -C targets a symlinked- // directory. The symlink mapping code handles stale $PWD gracefully (returns None).- if let Some(ref path) = cli.directory {- std::env::set_current_dir(path).unwrap_or_else(|e| {- eprintln!(- "{}",- error_message(format!(- "Cannot change to directory '{}': {}",- path.display(),- e- ))- );- process::exit(1);- });+ // Initialize base path from -C flag if provided+ if let Some(path) = cli.directory {+ set_base_path(path);}// Initialize config path from --config flag if provided@@ -504,6 +497,7 @@ fn main() {stage,show_prompt,} => {+ // Handle --show-prompt early: just build and output the promptif show_prompt {commands::step_show_squash_prompt(target.as_deref())} else {@@ -528,7 +522,7 @@ fn main() {})}}- StepCommand::Push { target } => step_push(target.as_deref()),+ StepCommand::Push { target } => handle_push(target.as_deref(), "Pushed to", None),StepCommand::Rebase { target } => {handle_rebase(target.as_deref()).map(|result| match result {RebaseResult::Rebased => (),@@ -641,10 +635,21 @@ fn main() {warning_message("wt select is deprecated; use wt switch instead"));- // handle_select resolves project-specific settings internallyUserConfig::load().context("Failed to load config")- .and_then(|config| handle_select(branches, remotes, &config))+ .and_then(|config| {+ // Get effective settings (project-specific merged with global, defaults applied)+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());+ let resolved = config.resolved(project_id.as_deref());++ // CLI flags override config+ let show_branches = branches || resolved.list.branches();+ let show_remotes = remotes || resolved.list.remotes();++ handle_select(show_branches, show_remotes, &config)+ })}#[cfg(not(unix))]Commands::Select { .. } => {@@ -687,17 +692,36 @@ fn main() {commands::statusline::run(effective_format)}None => {- // Load config; handle_list resolves project-specific settings internally+ // Load config and merge with CLI flags (CLI flags take precedence)UserConfig::load().context("Failed to load config").and_then(|config| {+ // Get resolved config (project-specific merged with global, defaults applied)+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());+ let resolved = config.resolved(project_id.as_deref());++ // CLI flags override config+ let show_branches = branches || resolved.list.branches();+ let show_remotes = remotes || resolved.list.remotes();+ let show_full = full || resolved.list.full();++ // Convert two bools to Option<bool>: Some(true), Some(false), or Nonelet progressive_opt = match (progressive, no_progressive) {(true, _) => Some(true),(_, true) => Some(false),_ => None,};let render_mode = RenderMode::detect(progressive_opt);- handle_list(format, branches, remotes, full, render_mode, &config)+ handle_list(+ format,+ show_branches,+ show_remotes,+ show_full,+ render_mode,+ &config,+ )})}},@@ -720,8 +744,22 @@ fn main() {let Some(branch) = branch else {#[cfg(unix)]{- // handle_select resolves project-specific settings internally- return handle_select(branches, remotes, &config);+ // Get project ID for per-project config lookup+ let project_id = Repository::current()+ .ok()+ .and_then(|r| r.project_identifier().ok());++ // Get effective list config (merges project-specific with global)+ let (show_branches_config, show_remotes_config) = config+ .list(project_id.as_deref())+ .map(|l| (l.branches.unwrap_or(false), l.remotes.unwrap_or(false)))+ .unwrap_or((false, false));++ // CLI flags override config+ let show_branches = branches || show_branches_config;+ let show_remotes = remotes || show_remotes_config;++ return handle_select(show_branches, show_remotes, &config);}#[cfg(not(unix))]@@ -768,16 +806,201 @@ fn main() {verify,yes,force,- } => handle_remove_command(RemoveOptions {- branches,- delete_branch,- force_delete,- foreground,- no_background,- verify,- yes,- force,- }),+ } => UserConfig::load()+ .context("Failed to load config")+ .and_then(|config| {+ // Handle deprecated --no-background flag+ if no_background {+ eprintln!(+ "{}",+ warning_message("--no-background is deprecated; use --foreground instead")+ );+ }+ let background = !(foreground || no_background);++ // Validate conflicting flags+ if !delete_branch && force_delete {+ return Err(worktrunk::git::GitError::Other {+ message: "Cannot use --force-delete with --no-delete-branch".into(),+ }+ .into());+ }++ let repo = Repository::current().context("Failed to remove worktree")?;++ // Helper: approve remove hooks using current worktree context+ // Returns true if hooks should run (user approved)+ let approve_remove = |yes: bool| -> anyhow::Result<bool> {+ let env = CommandEnv::for_action_branchless()?;+ let ctx = env.context(yes);+ let approved = approve_hooks(+ &ctx,+ &[+ HookType::PreRemove,+ HookType::PostRemove,+ HookType::PostSwitch,+ ],+ )?;+ if !approved {+ eprintln!("{}", info_message("Commands declined, continuing removal"));+ }+ Ok(approved)+ };++ if branches.is_empty() {+ // Single worktree removal: validate FIRST, then approve, then execute+ let result =+ handle_remove_current(!delete_branch, force_delete, force, &config)+ .context("Failed to remove worktree")?;++ // Early exit for benchmarking time-to-first-output+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ return Ok(());+ }++ // "Approve at the Gate": approval happens AFTER validation passes+ let run_hooks = verify && approve_remove(yes)?;++ handle_remove_output(&result, background, run_hooks)+ } else {+ // Multi-worktree removal: validate ALL first, then approve, then execute+ // This supports partial success - some may fail validation while others succeed.+ let current_worktree = repo+ .current_worktree()+ .root()+ .ok()+ .and_then(|p| dunce::canonicalize(&p).ok());++ // Dedupe inputs to avoid redundant planning/execution+ let branches: Vec<_> = {+ let mut seen = HashSet::new();+ branches+ .into_iter()+ .filter(|b| seen.insert(b.clone()))+ .collect()+ };++ // Phase 1: Validate all targets (resolution + preparation)+ // Store successful plans for execution after approval+ let mut plans_others: Vec<RemoveResult> = Vec::new();+ let mut plans_branch_only: Vec<RemoveResult> = Vec::new();+ let mut plan_current: Option<RemoveResult> = None;+ let mut all_errors: Vec<anyhow::Error> = Vec::new();++ // Helper: record error and continue+ let mut record_error = |e: anyhow::Error| {+ eprintln!("{}", e);+ all_errors.push(e);+ };++ for branch_name in &branches {+ // Resolve the target+ let resolved = match resolve_worktree_arg(+ &repo,+ branch_name,+ &config,+ OperationMode::Remove,+ ) {+ Ok(r) => r,+ Err(e) => {+ record_error(e);+ continue;+ }+ };++ match resolved {+ ResolvedWorktree::Worktree { path, branch } => {+ // Use canonical paths to avoid symlink/normalization mismatches+ let path_canonical = dunce::canonicalize(&path).unwrap_or(path);+ let is_current = current_worktree.as_ref() == Some(&path_canonical);++ if is_current {+ // Current worktree - use handle_remove_current for detached HEAD+ match handle_remove_current(+ !delete_branch,+ force_delete,+ force,+ &config,+ ) {+ Ok(result) => plan_current = Some(result),+ Err(e) => record_error(e),+ }+ continue;+ }++ // Non-current worktree - branch is always Some because:+ // - "@" resolves to current worktree (handled by is_current branch above)+ // - Other names resolve via resolve_worktree_arg which always sets branch: Some(...)+ let branch_for_remove = branch.as_ref().unwrap();++ match handle_remove(+ branch_for_remove,+ !delete_branch,+ force_delete,+ force,+ &config,+ ) {+ Ok(result) => plans_others.push(result),+ Err(e) => record_error(e),+ }+ }+ ResolvedWorktree::BranchOnly { branch } => {+ match handle_remove(+ &branch,+ !delete_branch,+ force_delete,+ force,+ &config,+ ) {+ Ok(result) => plans_branch_only.push(result),+ Err(e) => record_error(e),+ }+ }+ }+ }++ // If no valid plans, bail early (all failed validation)+ let has_valid_plans = !plans_others.is_empty()+ || !plans_branch_only.is_empty()+ || plan_current.is_some();+ if !has_valid_plans {+ anyhow::bail!("");+ }++ // Early exit for benchmarking time-to-first-output+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {+ return Ok(());+ }++ // Phase 2: Approve hooks (only if we have valid plans)+ // TODO(pre-remove-context): Approval context uses current worktree,+ // but hooks execute in each target worktree.+ let run_hooks = verify && approve_remove(yes)?;++ // Phase 3: Execute all validated plans+ // Remove other worktrees first+ for result in plans_others {+ handle_remove_output(&result, background, run_hooks)?;+ }++ // Handle branch-only cases+ for result in plans_branch_only {+ handle_remove_output(&result, background, run_hooks)?;+ }++ // Remove current worktree last (if it was in the list)+ if let Some(result) = plan_current {+ handle_remove_output(&result, background, run_hooks)?;+ }++ // Exit with failure if any validation errors occurred+ if !all_errors.is_empty() {+ anyhow::bail!("");+ }++ Ok(())+ }+ }),Commands::Merge {target,squash,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 4c8eaa0aa..43ef769cf 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -955,7 +955,7 @@ fn handle_removed_worktree_output();let remove_command = build_remove_command(worktree_path, None, force_worktree);spawn_detached(- &repo.wt_logs_dir(),+ &repo,main_path,&remove_command,"detached",@@ -1024,7 +1024,7 @@ fn handle_removed_worktree_output(// Spawn the removal in background - runs from main_path (where we cd'd to)spawn_detached(- &repo.wt_logs_dir(),+ &repo,main_path,&remove_command,branch_name,diff --git a/src/workspace/detect.rs b/src/workspace/detect.rsdeleted file mode 100644index 14fa14af3..000000000--- a/src/workspace/detect.rs+++ /dev/null@@ -1,89 +0,0 @@-//! VCS detection by filesystem markers.-//!-//! Walks ancestor directories looking for `.jj/` or `.git/` to determine-//! which VCS manages the repository. Co-located repos (both markers present)-//! prefer jj.--use std::path::Path;--use super::VcsKind;--/// Detect which VCS manages the repository containing `path`.-///-/// Walks ancestors looking for `.jj/` and `.git/` markers. At each level:-/// - `.jj/` present → jj (even if `.git/` also exists, since co-located repos-/// have both and jj is the primary VCS)-/// - `.git/` present (file or directory) → git-///-/// Returns `None` if no VCS markers are found.-pub fn detect_vcs(path: &Path) -> Option<VcsKind> {- let mut current = Some(path);- while let Some(dir) = current {- if dir.join(".jj").is_dir() {- return Some(VcsKind::Jj);- }- // .git can be a directory (normal repo) or file (worktree link)- if dir.join(".git").exists() {- return Some(VcsKind::Git);- }- current = dir.parent();- }- None-}--#[cfg(test)]-mod tests {- use std::fs;-- use super::*;-- #[test]- fn test_detect_git_repo() {- let dir = tempfile::tempdir().unwrap();- fs::create_dir(dir.path().join(".git")).unwrap();-- assert_eq!(detect_vcs(dir.path()), Some(VcsKind::Git));- }-- #[test]- fn test_detect_jj_repo() {- let dir = tempfile::tempdir().unwrap();- fs::create_dir(dir.path().join(".jj")).unwrap();-- assert_eq!(detect_vcs(dir.path()), Some(VcsKind::Jj));- }-- #[test]- fn test_detect_colocated_prefers_jj() {- let dir = tempfile::tempdir().unwrap();- fs::create_dir(dir.path().join(".jj")).unwrap();- fs::create_dir(dir.path().join(".git")).unwrap();-- assert_eq!(detect_vcs(dir.path()), Some(VcsKind::Jj));- }-- #[test]- fn test_detect_no_vcs() {- let dir = tempfile::tempdir().unwrap();- assert_eq!(detect_vcs(dir.path()), None);- }-- #[test]- fn test_detect_in_subdirectory() {- let dir = tempfile::tempdir().unwrap();- fs::create_dir(dir.path().join(".git")).unwrap();- let sub = dir.path().join("src").join("lib");- fs::create_dir_all(&sub).unwrap();-- assert_eq!(detect_vcs(&sub), Some(VcsKind::Git));- }-- #[test]- fn test_detect_git_worktree_file() {- let dir = tempfile::tempdir().unwrap();- // Git worktrees use a .git file (not directory) pointing to the main repo- fs::write(dir.path().join(".git"), "gitdir: /some/path").unwrap();-- assert_eq!(detect_vcs(dir.path()), Some(VcsKind::Git));- }-}diff --git a/src/workspace/git.rs b/src/workspace/git.rsdeleted file mode 100644index 30524fca5..000000000--- a/src/workspace/git.rs+++ /dev/null@@ -1,1024 +0,0 @@-//! Git implementation of the [`Workspace`] trait.-//!-//! Implements [`Workspace`] directly on [`Repository`], mapping git-specific-//! types to the VCS-agnostic [`WorkspaceItem`] and [`Workspace`] interface.-//!-//! Commands that need git-specific features (staging, interactive squash)-//! can downcast via `workspace.as_any().downcast_ref::<Repository>()`.--use std::any::Any;-use std::path::{Path, PathBuf};--use anyhow::Context;-use color_print::cformat;--use crate::git::{- GitError, Repository, check_integration, compute_integration_lazy, parse_porcelain_z,-};-use crate::path::format_path_for_display;--use super::types::{IntegrationReason, LineDiff, LocalPushDisplay, path_dir_name};-use crate::styling::{- GUTTER_OVERHEAD, eprintln, format_with_gutter, get_terminal_width, progress_message,- warning_message,-};--use super::{LocalPushResult, RebaseOutcome, SquashOutcome, VcsKind, Workspace, WorkspaceItem};--impl Workspace for Repository {- fn kind(&self) -> VcsKind {- VcsKind::Git- }-- fn list_workspaces(&self) -> anyhow::Result<Vec<WorkspaceItem>> {- let worktrees = self.list_worktrees()?;- let primary_path = self.primary_worktree()?;-- Ok(worktrees- .into_iter()- .map(|wt| {- let is_default = primary_path- .as_ref()- .is_some_and(|primary| *primary == wt.path);- WorkspaceItem::from_worktree(wt, is_default)- })- .collect())- }-- fn workspace_path(&self, name: &str) -> anyhow::Result<PathBuf> {- // Single pass: list worktrees once, check both branch name and dir name- let worktrees = self.list_worktrees()?;-- // Prefer branch name match- if let Some(wt) = worktrees- .iter()- .find(|wt| wt.branch.as_deref() == Some(name))- {- return Ok(wt.path.clone());- }-- // Fall back to directory name match- worktrees- .iter()- .find(|wt| path_dir_name(&wt.path) == name)- .map(|wt| wt.path.clone())- .ok_or_else(|| {- GitError::WorktreeNotFound {- branch: name.to_string(),- }- .into()- })- }-- fn default_workspace_path(&self) -> anyhow::Result<Option<PathBuf>> {- self.primary_worktree()- }-- fn default_branch_name(&self) -> Option<String> {- self.default_branch()- }-- fn set_default_branch(&self, name: &str) -> anyhow::Result<()> {- Repository::set_default_branch(self, name)- }-- fn clear_default_branch(&self) -> anyhow::Result<bool> {- self.clear_default_branch_cache()- }-- fn is_dirty(&self, path: &Path) -> anyhow::Result<bool> {- self.worktree_at(path).is_dirty()- }-- fn working_diff(&self, path: &Path) -> anyhow::Result<LineDiff> {- self.worktree_at(path).working_tree_diff_stats()- }-- fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {- // Note: this calls Repository::ahead_behind inherent method directly- Repository::ahead_behind(self, base, head)- }-- fn is_integrated(&self, id: &str, target: &str) -> anyhow::Result<Option<IntegrationReason>> {- let signals = compute_integration_lazy(self, id, target)?;- Ok(check_integration(&signals))- }-- fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff> {- Repository::branch_diff_stats(self, base, head)- }-- fn create_workspace(&self, name: &str, base: Option<&str>, path: &Path) -> anyhow::Result<()> {- self.create_worktree(name, base, path)- }-- fn remove_workspace(&self, name: &str) -> anyhow::Result<()> {- let path = Workspace::workspace_path(self, name)?;- self.remove_worktree(&path, false)- }-- fn resolve_integration_target(&self, target: Option<&str>) -> anyhow::Result<String> {- self.require_target_ref(target)- }-- fn is_rebased_onto(&self, target: &str, _path: &Path) -> anyhow::Result<bool> {- // Call the inherent method via fully-qualified syntax- Repository::is_rebased_onto(self, target)- }-- fn rebase_onto(&self, target: &str, _path: &Path) -> anyhow::Result<RebaseOutcome> {- // Detect fast-forward: merge-base == HEAD means HEAD is behind target- let merge_base = self- .merge_base("HEAD", target)?- .context("Cannot rebase: no common ancestor with target branch")?;- let head_sha = self.run_command(&["rev-parse", "HEAD"])?.trim().to_string();- let is_fast_forward = merge_base == head_sha;-- // Only show progress for true rebases (fast-forwards are instant)- if !is_fast_forward {- eprintln!(- "{}",- progress_message(cformat!("Rebasing onto <bold>{target}</>..."))- );- }-- let rebase_result = self.run_command(&["rebase", target]);-- if let Err(e) = rebase_result {- let is_rebasing = self- .worktree_state()?- .is_some_and(|s| s.starts_with("REBASING"));- if is_rebasing {- let git_output = e.to_string();- return Err(crate::git::GitError::RebaseConflict {- target_branch: target.to_string(),- git_output,- }- .into());- }- return Err(crate::git::GitError::Other {- message: format!("Failed to rebase onto {target}: {e}"),- }- .into());- }-- // Verify rebase completed successfully- if self.worktree_state()?.is_some() {- return Err(crate::git::GitError::RebaseConflict {- target_branch: target.to_string(),- git_output: String::new(),- }- .into());- }-- if is_fast_forward {- Ok(RebaseOutcome::FastForward)- } else {- Ok(RebaseOutcome::Rebased)- }- }-- fn root_path(&self) -> anyhow::Result<PathBuf> {- Ok(self.repo_path().to_path_buf())- }-- fn current_workspace_path(&self) -> anyhow::Result<PathBuf> {- Ok(self.current_worktree().path().to_path_buf())- }-- fn current_name(&self, path: &Path) -> anyhow::Result<Option<String>> {- self.worktree_at(path).branch()- }-- fn project_identifier(&self) -> anyhow::Result<String> {- // Call the inherent method via fully-qualified syntax- Repository::project_identifier(self)- }-- fn commit(&self, message: &str, path: &Path) -> anyhow::Result<String> {- self.worktree_at(path)- .run_command(&["commit", "-m", message])- .context("Failed to create commit")?;- let sha = self- .worktree_at(path)- .run_command(&["rev-parse", "HEAD"])?- .trim()- .to_string();- Ok(sha)- }-- fn commit_subjects(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>> {- let range = format!("{base}..{head}");- let output = self.run_command(&["log", "--format=%s", &range])?;- Ok(output.lines().map(|l| l.to_string()).collect())- }-- fn push_to_target(&self, target: &str, _path: &Path) -> anyhow::Result<()> {- self.run_command(&["push", "origin", &format!("HEAD:{target}")])?;- Ok(())- }-- fn local_push(- &self,- target: &str,- _path: &Path,- display: LocalPushDisplay<'_>,- ) -> anyhow::Result<LocalPushResult> {- // Check fast-forward- if !self.is_ancestor(target, "HEAD")? {- let commits_formatted = self- .run_command(&[- "log",- "--color=always",- "--graph",- "--oneline",- &format!("HEAD..{target}"),- ])?- .trim()- .to_string();- return Err(GitError::NotFastForward {- target_branch: target.to_string(),- commits_formatted,- in_merge_context: false,- }- .into());- }-- let commit_count = self.count_commits(target, "HEAD")?;- if commit_count == 0 {- return Ok(LocalPushResult {- commit_count: 0,- stats_summary: Vec::new(),- });- }-- // Collect display data before push (diffstat, stats summary)- let range = format!("{target}..HEAD");- let stats_summary = self.diff_stats_summary(&["diff", "--shortstat", &range]);-- // Auto-stash non-conflicting changes in the target worktree (if present)- let target_wt_path = self.worktree_for_branch(target)?;- let stash_info = stash_target_if_dirty(self, target_wt_path.as_ref(), target)?;-- // Show progress message, commit graph, and diffstat (between stash and restore)- show_push_preview(self, target, commit_count, &range, &display);-- // Local push: advance the target branch ref via git push to local path- let git_common_dir = self.git_common_dir();- let push_target = format!("HEAD:{target}");- let push_result = self.run_command(&[- "push",- "--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",- &git_common_dir.to_string_lossy(),- &push_target,- ]);-- // Restore stash regardless of push result- if let Some((wt_path, stash_ref)) = stash_info {- restore_stash(self, &wt_path, &stash_ref);- }-- push_result.map_err(|e| GitError::PushFailed {- target_branch: target.to_string(),- error: e.to_string(),- })?;-- Ok(LocalPushResult {- commit_count,- stats_summary,- })- }-- fn feature_head(&self, _path: &Path) -> anyhow::Result<String> {- Ok("HEAD".to_string())- }-- fn diff_for_prompt(- &self,- base: &str,- head: &str,- _path: &Path,- ) -> anyhow::Result<(String, String)> {- let diff = self.run_command(&[- "-c",- "diff.noprefix=false",- "-c",- "diff.mnemonicPrefix=false",- "--no-pager",- "diff",- base,- head,- ])?;- let stat = self.run_command(&["--no-pager", "diff", base, head, "--stat"])?;- Ok((diff, stat))- }-- fn recent_subjects(&self, start_ref: Option<&str>, count: usize) -> Option<Vec<String>> {- self.recent_commit_subjects(start_ref, count)- }-- fn squash_commits(- &self,- target: &str,- message: &str,- _path: &Path,- ) -> anyhow::Result<SquashOutcome> {- let merge_base = self- .merge_base("HEAD", target)?- .context("Cannot squash: no common ancestor with target branch")?;-- self.run_command(&["reset", "--soft", &merge_base])- .context("Failed to reset to merge base")?;-- // Check if there are actually any changes to commit (commits may cancel out)- if !self.current_worktree().has_staged_changes()? {- return Ok(SquashOutcome::NoNetChanges);- }-- self.run_command(&["commit", "-m", message])- .context("Failed to create squash commit")?;-- let sha = self- .run_command(&["rev-parse", "--short", "HEAD"])?- .trim()- .to_string();-- Ok(SquashOutcome::Squashed(sha))- }-- fn committable_diff_for_prompt(&self, _path: &Path) -> anyhow::Result<(String, String)> {- let diff = self.run_command(&[- "-c",- "diff.noprefix=false",- "-c",- "diff.mnemonicPrefix=false",- "--no-pager",- "diff",- "--staged",- ])?;- let stat = self.run_command(&["--no-pager", "diff", "--staged", "--stat"])?;- Ok((diff, stat))- }-- fn list_ignored_entries(&self, path: &Path) -> anyhow::Result<Vec<(PathBuf, bool)>> {- let output = crate::shell_exec::Cmd::new("git")- .args([- "ls-files",- "--ignored",- "--exclude-standard",- "-o",- "--directory",- ])- .current_dir(path)- .context(crate::git::path_to_logging_context(path))- .run()- .context("Failed to run git ls-files")?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- anyhow::bail!("git ls-files failed: {}", stderr.trim());- }-- Ok(String::from_utf8_lossy(&output.stdout)- .lines()- .map(|line| {- let is_dir = line.ends_with('/');- let entry_path = path.join(line.trim_end_matches('/'));- (entry_path, is_dir)- })- .collect())- }-- fn has_staging_area(&self) -> bool {- true- }-- fn load_project_config(&self) -> anyhow::Result<Option<crate::config::ProjectConfig>> {- Repository::load_project_config(self)- }-- fn wt_logs_dir(&self) -> PathBuf {- Repository::wt_logs_dir(self)- }-- fn switch_previous(&self) -> Option<String> {- Repository::switch_previous(self)- }-- fn set_switch_previous(&self, name: Option<&str>) -> anyhow::Result<()> {- Repository::set_switch_previous(self, name)- }-- fn as_any(&self) -> &dyn Any {- self- }-}--/// Print push progress: commit count, graph, and diffstat.-///-/// Emits the `◎ {verb} N commit(s) to TARGET @ SHA{notes}` progress message,-/// followed by the commit graph and diffstat with gutter formatting.-fn show_push_preview(- repo: &Repository,- target: &str,- commit_count: usize,- range: &str,- display: &LocalPushDisplay<'_>,-) {- let commit_text = if commit_count == 1 {- "commit"- } else {- "commits"- };- let head_sha = repo- .run_command(&["rev-parse", "--short", "HEAD"])- .unwrap_or_default();- let head_sha = head_sha.trim();- let verb = display.verb;- let notes = display.notes;-- eprintln!(- "{}",- progress_message(cformat!(- "{verb} {commit_count} {commit_text} to <bold>{target}</> @ <dim>{head_sha}</>{notes}"- ))- );-- // Commit graph- if let Ok(log_output) =- repo.run_command(&["log", "--color=always", "--graph", "--oneline", range])- {- eprintln!("{}", format_with_gutter(&log_output, None));- }-- // Diffstat- let term_width = get_terminal_width();- let stat_width = term_width.saturating_sub(GUTTER_OVERHEAD);- if let Ok(diff_stat) = repo.run_command(&[- "diff",- "--color=always",- "--stat",- &format!("--stat-width={stat_width}"),- range,- ]) {- let diff_stat = diff_stat.trim_end();- if !diff_stat.is_empty() {- eprintln!("{}", format_with_gutter(diff_stat, None));- }- }-}--/// Auto-stash non-conflicting dirty changes in the target worktree.-///-/// Returns `Some((path, stash_ref))` if changes were stashed, `None` otherwise.-/// Errors if the target worktree has dirty files that overlap with the push range.-fn stash_target_if_dirty(- repo: &Repository,- target_wt_path: Option<&PathBuf>,- target: &str,-) -> anyhow::Result<Option<(PathBuf, String)>> {- let Some(wt_path) = target_wt_path else {- return Ok(None);- };- if !wt_path.exists() {- return Ok(None);- }-- let wt = repo.worktree_at(wt_path);- if !wt.is_dirty()? {- return Ok(None);- }-- // Check for overlapping files- let push_files = repo.changed_files(target, "HEAD")?;- let wt_status = wt.run_command(&["status", "--porcelain", "-z"])?;- let wt_files = parse_porcelain_z(&wt_status);-- let overlapping: Vec<String> = push_files- .iter()- .filter(|f| wt_files.contains(f))- .cloned()- .collect();-- if !overlapping.is_empty() {- return Err(GitError::ConflictingChanges {- target_branch: target.to_string(),- files: overlapping,- worktree_path: wt_path.clone(),- }- .into());- }-- // Stash non-conflicting changes- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let stash_name = format!(- "worktrunk autostash::{}::{}::{}",- target,- std::process::id(),- nanos- );-- eprintln!(- "{}",- progress_message(cformat!(- "Stashing changes in <bold>{}</>...",- format_path_for_display(wt_path)- ))- );-- wt.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;-- // Find the stash ref- let list_output = wt.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;- let mut parts = list_output.split('\0');- while let Some(id) = parts.next() {- if id.is_empty() {- continue;- }- if let Some(message) = parts.next()- && (message == stash_name || message.ends_with(&stash_name))- {- return Ok(Some((wt_path.clone(), id.to_string())));- }- }-- // Stash entry not found — verify worktree is clean (stash may have been empty)- if wt.is_dirty()? {- anyhow::bail!(- "Failed to stash changes in {}; worktree still has uncommitted changes",- format_path_for_display(wt_path)- );- }-- // Worktree is clean and no stash entry — nothing needed to be stashed- Ok(None)-}--/// Restore a previously created stash (best-effort).-fn restore_stash(repo: &Repository, wt_path: &Path, stash_ref: &str) {- eprintln!(- "{}",- progress_message(cformat!(- "Restoring stashed changes in <bold>{}</>...",- format_path_for_display(wt_path)- ))- );-- let success = repo- .worktree_at(wt_path)- .run_command(&["stash", "pop", stash_ref])- .is_ok();-- if !success {- eprintln!(- "{}",- warning_message(cformat!(- "Failed to restore stash <bold>{stash_ref}</>; run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",- path = format_path_for_display(wt_path),- ))- );- }-}--#[cfg(test)]-mod tests {- use std::path::PathBuf;-- use crate::git::WorktreeInfo;-- use super::super::WorkspaceItem;-- #[test]- fn test_from_worktree_with_branch() {- let wt = WorktreeInfo {- path: PathBuf::from("/repos/myrepo.feature"),- head: "abc123".into(),- branch: Some("feature".into()),- bare: false,- detached: false,- locked: None,- prunable: None,- };-- let item = WorkspaceItem::from_worktree(wt, false);-- assert_eq!(item.name, "feature");- assert_eq!(item.head, "abc123");- assert_eq!(item.branch, Some("feature".into()));- assert_eq!(item.path, PathBuf::from("/repos/myrepo.feature"));- assert!(!item.is_default);- }-- #[test]- fn test_from_worktree_detached() {- let wt = WorktreeInfo {- path: PathBuf::from("/repos/myrepo.detached"),- head: "def456".into(),- branch: None,- bare: false,- detached: true,- locked: None,- prunable: None,- };-- let item = WorkspaceItem::from_worktree(wt, true);-- // Falls back to directory name when no branch- assert_eq!(item.name, "myrepo.detached");- assert_eq!(item.head, "def456");- assert_eq!(item.branch, None);- assert!(item.is_default);- }-- #[test]- fn test_from_worktree_locked() {- let wt = WorktreeInfo {- path: PathBuf::from("/repos/myrepo.locked"),- head: "789abc".into(),- branch: Some("locked-branch".into()),- bare: false,- detached: false,- locked: Some("in use".into()),- prunable: None,- };-- let item = WorkspaceItem::from_worktree(wt, false);-- assert_eq!(item.locked, Some("in use".into()));- assert_eq!(item.prunable, None);- }-- #[test]- fn test_from_worktree_prunable() {- let wt = WorktreeInfo {- path: PathBuf::from("/repos/myrepo.gone"),- head: "000000".into(),- branch: Some("gone-branch".into()),- bare: false,- detached: false,- locked: None,- prunable: Some("directory missing".into()),- };-- let item = WorkspaceItem::from_worktree(wt, false);-- assert_eq!(item.prunable, Some("directory missing".into()));- }-- /// Exercise all `Workspace` trait methods on a real git repository.- ///- /// This covers the `Workspace for Repository` implementation which- /// maps `Repository` methods into the VCS-agnostic trait.- #[test]- fn test_workspace_trait_on_real_repo() {- use std::process::Command;-- use super::super::{VcsKind, Workspace};- use crate::git::Repository;-- let temp = tempfile::tempdir().unwrap();- let repo_path = temp.path().join("repo");- std::fs::create_dir(&repo_path).unwrap();-- let git = |args: &[&str]| {- let output = Command::new("git")- .args(args)- .current_dir(&repo_path)- .env("GIT_AUTHOR_NAME", "Test")- .env("GIT_AUTHOR_EMAIL", "[email protected]")- .env("GIT_COMMITTER_NAME", "Test")- .env("GIT_COMMITTER_EMAIL", "[email protected]")- .output()- .unwrap();- assert!(- output.status.success(),- "{}",- String::from_utf8_lossy(&output.stderr)- );- };-- git(&["init", "-b", "main"]);- git(&["config", "user.name", "Test"]);- git(&["config", "user.email", "[email protected]"]);- std::fs::write(repo_path.join("file.txt"), "hello\n").unwrap();- git(&["add", "."]);- git(&["commit", "-m", "initial"]);-- let repo = Repository::at(&repo_path).unwrap();- let ws: &dyn Workspace = &repo;-- // kind- assert_eq!(ws.kind(), VcsKind::Git);-- // has_staging_area- assert!(ws.has_staging_area());-- // list_workspaces- let items = ws.list_workspaces().unwrap();- assert_eq!(items.len(), 1);- assert_eq!(items[0].name, "main");- assert!(items[0].is_default);-- // default_workspace_path- assert!(ws.default_workspace_path().unwrap().is_some());-- // default_branch_name- let _ = ws.default_branch_name();-- // is_dirty — clean state- assert!(!ws.is_dirty(&repo_path).unwrap());-- // working_diff — clean- let diff = ws.working_diff(&repo_path).unwrap();- assert_eq!(diff.added, 0);- assert_eq!(diff.deleted, 0);-- // root_path- let root = ws.root_path().unwrap();- assert!(root.exists());-- // current_workspace_path- let cur_path = ws.current_workspace_path().unwrap();- assert!(cur_path.exists());-- // current_name- let name = ws.current_name(&repo_path).unwrap();- assert_eq!(name, Some("main".to_string()));-- // project_identifier — derived from path without remote- assert!(ws.project_identifier().is_ok());-- // feature_head — always "HEAD" for git- assert_eq!(ws.feature_head(&repo_path).unwrap(), "HEAD");-- // recent_subjects- let subjects = ws.recent_subjects(None, 5).unwrap();- assert!(subjects.contains(&"initial".to_string()));-- // load_project_config — no .config/wt.toml in the test tempdir- // (may find one from parent project when run inside worktrunk repo)- let _ = ws.load_project_config();-- // wt_logs_dir- let logs_dir = ws.wt_logs_dir();- assert!(!logs_dir.as_os_str().is_empty());-- // Make dirty- std::fs::write(repo_path.join("file.txt"), "modified\n").unwrap();- assert!(ws.is_dirty(&repo_path).unwrap());- let diff = ws.working_diff(&repo_path).unwrap();- assert!(diff.added > 0 || diff.deleted > 0);- git(&["checkout", "--", "."]);-- // Create feature branch with a commit- git(&["checkout", "-b", "feature"]);- std::fs::write(repo_path.join("feature.txt"), "feature\n").unwrap();- git(&["add", "."]);- git(&["commit", "-m", "feature commit"]);-- // ahead_behind- let (ahead, behind) = ws.ahead_behind("main", "feature").unwrap();- assert_eq!(ahead, 1);- assert_eq!(behind, 0);-- // is_integrated — feature is NOT an ancestor of main- let integrated = ws.is_integrated("feature", "main").unwrap();- assert!(integrated.is_none());-- // branch_diff_stats- let diff = ws.branch_diff_stats("main", "feature").unwrap();- assert!(diff.added > 0);-- // Switch back to main for workspace mutation tests- git(&["checkout", "main"]);-- // create_workspace (also covers Repository::create_worktree)- let wt_path = temp.path().join("test-wt");- ws.create_workspace("test-branch", None, &wt_path).unwrap();-- // workspace_path — found by branch name- let path = ws.workspace_path("test-branch").unwrap();- assert_eq!(- dunce::canonicalize(&path).unwrap(),- dunce::canonicalize(&wt_path).unwrap()- );-- // remove_workspace- ws.remove_workspace("test-branch").unwrap();-- // workspace_path — not found- assert!(ws.workspace_path("nonexistent").is_err());-- // create_workspace with base revision (covers the `if let Some(base_ref)` branch)- let wt_path2 = temp.path().join("test-wt2");- ws.create_workspace("from-feature", Some("feature"), &wt_path2)- .unwrap();- ws.remove_workspace("from-feature").unwrap();-- // commit via Workspace trait — create a worktree, stage a file, commit- let commit_wt = temp.path().join("commit-test");- ws.create_workspace("commit-branch", Some("main"), &commit_wt)- .unwrap();- std::fs::write(commit_wt.join("new.txt"), "new content\n").unwrap();- Command::new("git")- .args(["add", "."])- .current_dir(&commit_wt)- .output()- .unwrap();- let sha = ws.commit("trait commit", &commit_wt).unwrap();- assert!(!sha.is_empty());-- // commit_subjects — verify the commit we just made- let subjects = ws.commit_subjects("main", "commit-branch").unwrap();- assert!(subjects.contains(&"trait commit".to_string()));-- // local_push via Workspace trait — local push of feature onto main- let repo_at_wt = Repository::at(&commit_wt).unwrap();- let ws_at_wt: &dyn Workspace = &repo_at_wt;- let push_result = ws_at_wt- .local_push("main", &commit_wt, Default::default())- .unwrap();- assert_eq!(push_result.commit_count, 1);-- // local_push with zero commits ahead — returns early- let push_result = ws_at_wt- .local_push("main", &commit_wt, Default::default())- .unwrap();- assert_eq!(push_result.commit_count, 0);-- // Helper for git commands in linked worktrees- let git_at = |args: &[&str], dir: &std::path::Path| {- let output = Command::new("git")- .args(args)- .current_dir(dir)- .env("GIT_AUTHOR_NAME", "Test")- .env("GIT_AUTHOR_EMAIL", "[email protected]")- .env("GIT_COMMITTER_NAME", "Test")- .env("GIT_COMMITTER_EMAIL", "[email protected]")- .output()- .unwrap();- assert!(- output.status.success(),- "{}",- String::from_utf8_lossy(&output.stderr)- );- };-- // committable_diff_for_prompt — stage a file in the worktree- let staged_wt = temp.path().join("staged-test");- ws.create_workspace("staged-branch", Some("main"), &staged_wt)- .unwrap();- std::fs::write(staged_wt.join("staged.txt"), "staged content\n").unwrap();- git_at(&["add", "."], &staged_wt);- let repo_at_staged = Repository::at(&staged_wt).unwrap();- let ws_staged: &dyn Workspace = &repo_at_staged;- let (diff_text, stat_text) = ws_staged.committable_diff_for_prompt(&staged_wt).unwrap();- assert!(!diff_text.is_empty());- assert!(!stat_text.is_empty());- git_at(&["commit", "-m", "staged commit"], &staged_wt);- ws.remove_workspace("staged-branch").unwrap();-- ws.remove_workspace("commit-branch").unwrap();-- // diff_for_prompt — feature has changes vs main- let (diff_text, stat_text) = ws.diff_for_prompt("main", "feature", &repo_path).unwrap();- assert!(diff_text.contains("feature.txt"));- assert!(stat_text.contains("feature.txt"));-- // is_rebased_onto — branch created from main is rebased onto main- let rb_wt = temp.path().join("rb-check");- ws.create_workspace("rb-check", Some("main"), &rb_wt)- .unwrap();- git_at(&["commit", "--allow-empty", "-m", "ahead of main"], &rb_wt);- let repo_at_rb = Repository::at(&rb_wt).unwrap();- let ws_rb: &dyn Workspace = &repo_at_rb;- assert!(ws_rb.is_rebased_onto("main", &rb_wt).unwrap());- ws.remove_workspace("rb-check").unwrap();-- // resolve_integration_target with explicit target- assert_eq!(ws.resolve_integration_target(Some("main")).unwrap(), "main");-- // rebase_onto — fast-forward case: create branch at main~1, rebase onto main- git(&["checkout", "main"]);- std::fs::write(repo_path.join("main-only.txt"), "main content\n").unwrap();- git(&["add", "."]);- git(&["commit", "-m", "advance main"]);-- let rebase_wt = temp.path().join("rebase-test");- ws.create_workspace("rebase-ff", Some("main~1"), &rebase_wt)- .unwrap();- let repo_at_rebase = Repository::at(&rebase_wt).unwrap();- let ws_rebase: &dyn Workspace = &repo_at_rebase;- let outcome = ws_rebase.rebase_onto("main", &rebase_wt).unwrap();- assert!(matches!(outcome, super::super::RebaseOutcome::FastForward));- ws.remove_workspace("rebase-ff").unwrap();-- // rebase_onto — real rebase case: diverged branches- let rebase_wt2 = temp.path().join("rebase-test2");- ws.create_workspace("rebase-diverged", Some("feature"), &rebase_wt2)- .unwrap();- std::fs::write(rebase_wt2.join("diverge.txt"), "diverged\n").unwrap();- git_at(&["add", "."], &rebase_wt2);- git_at(&["commit", "-m", "diverged commit"], &rebase_wt2);- let repo_at_rebase2 = Repository::at(&rebase_wt2).unwrap();- let ws_rebase2: &dyn Workspace = &repo_at_rebase2;- let outcome = ws_rebase2.rebase_onto("main", &rebase_wt2).unwrap();- assert!(matches!(outcome, super::super::RebaseOutcome::Rebased));- ws.remove_workspace("rebase-diverged").unwrap();-- // local_push with dirty target worktree — exercises stash/restore path- // Make main worktree dirty with a non-conflicting file- std::fs::write(repo_path.join("dirty.txt"), "dirty\n").unwrap();- // Create a new branch with a commit to push onto main- let stash_wt = temp.path().join("stash-push-test");- ws.create_workspace("stash-push-branch", Some("main"), &stash_wt)- .unwrap();- std::fs::write(stash_wt.join("push-me.txt"), "push content\n").unwrap();- git_at(&["add", "."], &stash_wt);- git_at(&["commit", "-m", "push with stash"], &stash_wt);- let repo_at_stash = Repository::at(&stash_wt).unwrap();- let ws_stash: &dyn Workspace = &repo_at_stash;- let push_result = ws_stash- .local_push("main", &stash_wt, Default::default())- .unwrap();- assert_eq!(push_result.commit_count, 1);- // Verify dirty file in main worktree was preserved after stash/restore- assert!(repo_path.join("dirty.txt").exists());- // Clean up- git(&["checkout", "--", "."]);- std::fs::remove_file(repo_path.join("dirty.txt")).ok();- ws.remove_workspace("stash-push-branch").unwrap();-- // rebase_onto — conflict case: both branches modify the same file- // First, create a branch from the current main- let conflict_wt = temp.path().join("conflict-test");- ws.create_workspace("conflict-branch", Some("main"), &conflict_wt)- .unwrap();- // On the branch, modify file.txt- std::fs::write(conflict_wt.join("file.txt"), "branch version\n").unwrap();- git_at(&["add", "."], &conflict_wt);- git_at(&["commit", "-m", "branch modifies file.txt"], &conflict_wt);- // On main, also modify file.txt differently (creating divergence)- git(&["checkout", "main"]);- std::fs::write(repo_path.join("file.txt"), "main version\n").unwrap();- git(&["add", "."]);- git(&["commit", "-m", "main modifies file.txt"]);- // Now rebase conflict-branch onto main → should conflict- let repo_at_conflict = Repository::at(&conflict_wt).unwrap();- let ws_conflict: &dyn Workspace = &repo_at_conflict;- let err = ws_conflict.rebase_onto("main", &conflict_wt).unwrap_err();- // Verify it's a rebase conflict error, then abort the rebase- assert!(- err.to_string().contains("conflict")- || err.downcast_ref::<crate::git::GitError>().is_some()- );- // Abort the in-progress rebase to clean up- let _ = repo_at_conflict.run_command(&["rebase", "--abort"]);- ws.remove_workspace("conflict-branch").unwrap();-- // workspace_path by directory name — fallback when branch name doesn't match- // Create a worktree and look it up by its directory name (not branch name)- let dirname_wt = temp.path().join("dir-lookup-test");- ws.create_workspace("dir-lookup-branch", Some("main"), &dirname_wt)- .unwrap();- // Look up by the directory name (not the branch name)- let found_path = ws.workspace_path("dir-lookup-test").unwrap();- assert_eq!(- dunce::canonicalize(&found_path).unwrap(),- dunce::canonicalize(&dirname_wt).unwrap()- );- ws.remove_workspace("dir-lookup-branch").unwrap();-- // feature_head via Workspace trait — should return "HEAD" for git- let fh_wt = temp.path().join("fh-test");- ws.create_workspace("fh-branch", Some("main"), &fh_wt)- .unwrap();- let repo_at_fh = Repository::at(&fh_wt).unwrap();- let ws_fh: &dyn Workspace = &repo_at_fh;- assert_eq!(ws_fh.feature_head(&fh_wt).unwrap(), "HEAD");- ws.remove_workspace("fh-branch").unwrap();-- // switch_previous — initially None (no history set yet)- assert!(ws.switch_previous().is_none());-- // set_switch_previous — set a value- ws.set_switch_previous(Some("feature")).unwrap();- assert_eq!(ws.switch_previous(), Some("feature".to_string()));-- // set_switch_previous(None) is a no-op for git (preserves history on detached HEAD)- ws.set_switch_previous(None).unwrap();- assert_eq!(ws.switch_previous(), Some("feature".to_string()));-- // as_any downcast- let repo_ref = ws.as_any().downcast_ref::<Repository>();- assert!(repo_ref.is_some());-- // build_worktree_map — covers the map-building logic in mod.rs- let map = super::super::build_worktree_map(ws);- assert!(!map.is_empty());- assert!(map.contains_key("main"));- }-}diff --git a/src/workspace/jj.rs b/src/workspace/jj.rsdeleted file mode 100644index b5ece0971..000000000--- a/src/workspace/jj.rs+++ /dev/null@@ -1,736 +0,0 @@-//! Jujutsu (jj) implementation of the [`Workspace`] trait.-//!-//! Implements workspace operations by shelling out to `jj` commands-//! and parsing their output.--use std::any::Any;-use std::path::{Path, PathBuf};--use anyhow::Context;-use color_print::cformat;--use super::types::{IntegrationReason, LineDiff, LocalPushDisplay};-use crate::shell_exec::Cmd;-use crate::styling::{eprintln, progress_message};--use super::{LocalPushResult, RebaseOutcome, SquashOutcome, VcsKind, Workspace, WorkspaceItem};--/// Jujutsu-backed workspace implementation.-///-/// Wraps a jj repository root path and implements [`Workspace`] by running-/// `jj` CLI commands. Each method shells out to the appropriate `jj` subcommand.-#[derive(Debug, Clone)]-pub struct JjWorkspace {- /// Root directory of the jj repository.- root: PathBuf,-}--impl JjWorkspace {- /// Create a new `JjWorkspace` rooted at the given path.- pub fn new(root: PathBuf) -> Self {- Self { root }- }-- /// Detect and create a `JjWorkspace` from the current directory.- ///- /// Runs `jj root` to find the repository root.- pub fn from_current_dir() -> anyhow::Result<Self> {- let stdout = run_jj_command(Path::new("."), &["root"])?;- Ok(Self::new(PathBuf::from(stdout.trim())))- }-- /// The repository root path.- pub fn root(&self) -> &Path {- &self.root- }-- /// Run a jj command in this repository's root directory.- fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {- run_jj_command(&self.root, args)- }-- /// Run a jj command in the specified directory.- ///- /// Unlike `run_command` which runs in the repo root, this runs in the given- /// directory — needed when commands must execute in a specific workspace.- pub fn run_in_dir(&self, dir: &Path, args: &[&str]) -> anyhow::Result<String> {- run_jj_command(dir, args)- }-- /// Find which workspace contains the given directory.- ///- /// Returns the `WorkspaceItem` whose path is an ancestor of `cwd`.- pub fn current_workspace(&self, cwd: &Path) -> anyhow::Result<WorkspaceItem> {- let workspaces = self.list_workspaces()?;- let cwd = dunce::canonicalize(cwd)?;- workspaces- .into_iter()- .find(|ws| {- dunce::canonicalize(&ws.path)- .map(|p| cwd.starts_with(&p))- .unwrap_or(false)- })- .ok_or_else(|| anyhow::anyhow!("Not inside a jj workspace"))- }-- /// Detect the bookmark name associated with `trunk()`.- ///- /// Falls back to `"main"` if no bookmark is found.- pub fn trunk_bookmark(&self) -> anyhow::Result<String> {- let output = self.run_command(&[- "log",- "-r",- "trunk()",- "--no-graph",- "-T",- r#"self.bookmarks().map(|b| b.name()).join("\n")"#,- ])?;- let bookmarks: Vec<&str> = output.trim().lines().filter(|l| !l.is_empty()).collect();-- // Prefer "main", then "master", then first found- if bookmarks.contains(&"main") {- Ok("main".to_string())- } else if bookmarks.contains(&"master") {- Ok("master".to_string())- } else {- Ok(bookmarks- .first()- .map(|s| s.to_string())- .unwrap_or_else(|| "main".to_string()))- }- }-- /// Determine the feature tip change ID.- ///- /// In jj, the working copy (@) is often an empty auto-snapshot commit.- /// When @ is empty, the real feature tip is @- (the parent).- pub fn feature_tip(&self, ws_path: &Path) -> anyhow::Result<String> {- let empty_check = run_jj_command(- ws_path,- &[- "log",- "-r",- "@",- "--no-graph",- "-T",- r#"if(self.empty(), "empty", "content")"#,- ],- )?;-- let revset = if empty_check.trim() == "empty" {- "@-"- } else {- "@"- };-- let output = run_jj_command(- ws_path,- &[- "log",- "-r",- revset,- "--no-graph",- "-T",- r#"self.change_id().short(12)"#,- ],- )?;-- Ok(output.trim().to_string())- }-- /// Get commit details (timestamp, description) for the working-copy commit- /// in a specific workspace directory.- ///- /// Returns `(unix_timestamp, first_line_of_description)`.- pub fn commit_details(&self, ws_path: &Path) -> anyhow::Result<(i64, String)> {- let template = r#"self.committer().timestamp().utc().format("%s") ++ "\t" ++ self.description().first_line()"#;- let output = run_jj_command(ws_path, &["log", "-r", "@", "--no-graph", "-T", template])?;- let line = output.trim();- let (timestamp_str, message) = line- .split_once('\t')- .ok_or_else(|| anyhow::anyhow!("unexpected commit details format: {line}"))?;- let timestamp = timestamp_str- .parse::<i64>()- .with_context(|| format!("invalid timestamp: {timestamp_str}"))?;- Ok((timestamp, message.to_string()))- }-}--/// Run a jj command at the given directory, returning stdout on success.-fn run_jj_command(dir: &Path, args: &[&str]) -> anyhow::Result<String> {- let mut cmd_args = vec!["--no-pager", "--color", "never"];- cmd_args.extend_from_slice(args);-- let output = Cmd::new("jj")- .args(cmd_args.iter().copied())- .current_dir(dir)- .run()- .with_context(|| format!("Failed to execute: jj {}", args.join(" ")))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- let stdout = String::from_utf8_lossy(&output.stdout);- let error_msg = [stderr.trim(), stdout.trim()]- .into_iter()- .filter(|s| !s.is_empty())- .collect::<Vec<_>>()- .join("\n");- anyhow::bail!("{}", error_msg);- }-- Ok(String::from_utf8_lossy(&output.stdout).into_owned())-}--/// Parse the summary line from `jj diff --stat` output.-///-/// Format: `N files changed, N insertions(+), N deletions(-)`-/// Returns `(insertions, deletions)`.-fn parse_diff_stat_summary(output: &str) -> LineDiff {- // The summary line is the last non-empty line- let summary = output.lines().rev().find(|l| !l.is_empty()).unwrap_or("");-- let mut added = 0usize;- let mut deleted = 0usize;-- // Parse "N insertions(+)" and "N deletions(-)"- for part in summary.split(", ") {- let part = part.trim();- if part.contains("insertion")- && let Some(n) = part.split_whitespace().next().and_then(|s| s.parse().ok())- {- added = n;- } else if part.contains("deletion")- && let Some(n) = part.split_whitespace().next().and_then(|s| s.parse().ok())- {- deleted = n;- }- }-- LineDiff { added, deleted }-}--impl Workspace for JjWorkspace {- fn kind(&self) -> VcsKind {- VcsKind::Jj- }-- fn list_workspaces(&self) -> anyhow::Result<Vec<WorkspaceItem>> {- // Template outputs: name\tchange_id_short\n- let template = r#"name ++ "\t" ++ target.change_id().short(12) ++ "\n""#;- let output = self.run_command(&["workspace", "list", "-T", template])?;-- let mut items = Vec::new();- for line in output.lines() {- if line.is_empty() {- continue;- }- let Some((name, change_id)) = line.split_once('\t') else {- continue;- };-- // Get workspace path- let path_output = self.run_command(&["workspace", "root", "--name", name])?;- let path = PathBuf::from(path_output.trim());-- let is_default = name == "default";-- items.push(WorkspaceItem {- path,- name: name.to_string(),- head: change_id.to_string(),- branch: None,- is_default,- locked: None,- prunable: None,- });- }-- Ok(items)- }-- fn workspace_path(&self, name: &str) -> anyhow::Result<PathBuf> {- let output = self.run_command(&["workspace", "root", "--name", name])?;- Ok(PathBuf::from(output.trim()))- }-- fn default_workspace_path(&self) -> anyhow::Result<Option<PathBuf>> {- // Try "default" workspace; if it doesn't exist, return None- match self.run_command(&["workspace", "root", "--name", "default"]) {- Ok(output) => Ok(Some(PathBuf::from(output.trim()))),- Err(_) => Ok(None),- }- }-- fn default_branch_name(&self) -> Option<String> {- // Check explicit config override first- if let Some(name) = self- .run_command(&["config", "get", "worktrunk.default-branch"])- .ok()- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty())- {- return Some(name);- }- // Fall back to trunk() revset detection- self.trunk_bookmark().ok()- }-- fn set_default_branch(&self, name: &str) -> anyhow::Result<()> {- self.run_command(&["config", "set", "--repo", "worktrunk.default-branch", name])?;- Ok(())- }-- fn clear_default_branch(&self) -> anyhow::Result<bool> {- Ok(self- .run_command(&["config", "unset", "--repo", "worktrunk.default-branch"])- .is_ok())- }-- fn is_dirty(&self, path: &Path) -> anyhow::Result<bool> {- // jj auto-snapshots the working copy, so "dirty" means the working-copy- // commit has file changes (is not empty)- let output = run_jj_command(- path,- &[- "log",- "-r",- "@",- "--no-graph",- "-T",- r#"if(self.empty(), "clean", "dirty")"#,- ],- )?;- Ok(output.trim() == "dirty")- }-- fn working_diff(&self, path: &Path) -> anyhow::Result<LineDiff> {- let output = run_jj_command(path, &["diff", "--stat"])?;- Ok(parse_diff_stat_summary(&output))- }-- fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {- // Count commits in head that aren't in base (ahead)- let ahead_revset = format!("{base}..{head}");- let ahead_output =- self.run_command(&["log", "-r", &ahead_revset, "--no-graph", "-T", r#""x\n""#])?;- let ahead = ahead_output.lines().filter(|l| !l.is_empty()).count();-- // Count commits in base that aren't in head (behind)- let behind_revset = format!("{head}..{base}");- let behind_output =- self.run_command(&["log", "-r", &behind_revset, "--no-graph", "-T", r#""x\n""#])?;- let behind = behind_output.lines().filter(|l| !l.is_empty()).count();-- Ok((ahead, behind))- }-- fn is_integrated(&self, id: &str, target: &str) -> anyhow::Result<Option<IntegrationReason>> {- // Check if the change is an ancestor of (or same as) the target- let revset = format!("{id} & ::{target}");- let output = self.run_command(&["log", "-r", &revset, "--no-graph", "-T", r#""x""#])?;-- if !output.trim().is_empty() {- return Ok(Some(IntegrationReason::Ancestor));- }-- Ok(None)- }-- fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff> {- let output = self.run_command(&["diff", "--stat", "--from", base, "--to", head])?;- Ok(parse_diff_stat_summary(&output))- }-- fn create_workspace(&self, name: &str, base: Option<&str>, path: &Path) -> anyhow::Result<()> {- let path_str = path.to_str().ok_or_else(|| {- anyhow::anyhow!("Workspace path contains invalid UTF-8: {}", path.display())- })?;-- let mut args = vec!["workspace", "add", "--name", name, path_str];- if let Some(revision) = base {- args.extend_from_slice(&["--revision", revision]);- }- self.run_command(&args)?;- Ok(())- }-- fn remove_workspace(&self, name: &str) -> anyhow::Result<()> {- self.run_command(&["workspace", "forget", name])?;- Ok(())- }-- fn resolve_integration_target(&self, target: Option<&str>) -> anyhow::Result<String> {- match target {- Some(t) => Ok(t.to_string()),- None => self.trunk_bookmark(),- }- }-- fn is_rebased_onto(&self, target: &str, path: &Path) -> anyhow::Result<bool> {- let feature_tip = self.feature_tip(path)?;- // target is ancestor of feature tip iff "target & ::feature_tip" is non-empty- let check = run_jj_command(- path,- &[- "log",- "-r",- &format!("{target} & ::{feature_tip}"),- "--no-graph",- "-T",- r#""x""#,- ],- )?;- Ok(!check.trim().is_empty())- }-- fn rebase_onto(&self, target: &str, path: &Path) -> anyhow::Result<RebaseOutcome> {- eprintln!(- "{}",- progress_message(cformat!("Rebasing onto <bold>{target}</>..."))- );- run_jj_command(path, &["rebase", "-b", "@", "-d", target])?;- // jj doesn't distinguish fast-forward from true rebase- Ok(RebaseOutcome::Rebased)- }-- fn root_path(&self) -> anyhow::Result<PathBuf> {- Ok(self.root.clone())- }-- fn current_workspace_path(&self) -> anyhow::Result<PathBuf> {- let cwd = std::env::current_dir()?;- Ok(self.current_workspace(&cwd)?.path)- }-- fn current_name(&self, path: &Path) -> anyhow::Result<Option<String>> {- Ok(Some(self.current_workspace(path)?.name))- }-- fn project_identifier(&self) -> anyhow::Result<String> {- // Most jj repos are git-backed. Try to get the git remote URL for a stable- // project identifier (same clone = same ID, regardless of directory name).- if let Ok(output) = self.run_command(&["git", "remote", "list"]) {- // Format: "remote_name url\n" — prefer "origin" if present- let url = output- .lines()- .find(|l| l.starts_with("origin "))- .or_else(|| output.lines().next())- .and_then(|l| l.split_whitespace().nth(1));- if let Some(url) = url {- return Ok(url.to_string());- }- }- // Fallback: use directory name- self.root- .file_name()- .and_then(|n| n.to_str())- .map(|s| s.to_string())- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename"))- }-- fn commit(&self, message: &str, path: &Path) -> anyhow::Result<String> {- run_jj_command(path, &["describe", "-m", message])?;- run_jj_command(path, &["new"])?;- // Return the change ID of the just-described commit (now @-)- let output = run_jj_command(- path,- &[- "log",- "-r",- "@-",- "--no-graph",- "-T",- r#"self.change_id().short(12)"#,- ],- )?;- Ok(output.trim().to_string())- }-- fn commit_subjects(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>> {- let revset = format!("{base}..{head}");- let output = run_jj_command(- &self.root,- &[- "log",- "-r",- &revset,- "--no-graph",- "-T",- r#"self.description().first_line() ++ "\n""#,- ],- )?;- Ok(output- .lines()- .filter(|l| !l.is_empty())- .map(|l| l.to_string())- .collect())- }-- fn push_to_target(&self, target: &str, path: &Path) -> anyhow::Result<()> {- run_jj_command(path, &["git", "push", "--bookmark", target])?;- Ok(())- }-- fn local_push(- &self,- target: &str,- path: &Path,- _display: LocalPushDisplay<'_>,- ) -> anyhow::Result<LocalPushResult> {- // Guard: target must be an ancestor of the feature tip.- // Prevents moving the bookmark sideways or backward (which would lose commits).- if !self.is_rebased_onto(target, path)? {- anyhow::bail!(- "Cannot push: feature is not ahead of {target}. Rebase first with `wt step rebase`."- );- }-- let feature_tip = self.feature_tip(path)?;-- // Count commits ahead of target- let revset = format!("{target}..{feature_tip}");- let count_output = run_jj_command(- path,- &["log", "-r", &revset, "--no-graph", "-T", r#""x\n""#],- )?;- let commit_count = count_output.lines().filter(|l| !l.is_empty()).count();-- if commit_count == 0 {- return Ok(LocalPushResult {- commit_count: 0,- stats_summary: Vec::new(),- });- }-- // Move bookmark to feature tip (local only)- run_jj_command(path, &["bookmark", "set", target, "-r", &feature_tip])?;-- Ok(LocalPushResult {- commit_count,- stats_summary: Vec::new(),- })- }-- fn feature_head(&self, path: &Path) -> anyhow::Result<String> {- self.feature_tip(path)- }-- fn diff_for_prompt(- &self,- base: &str,- head: &str,- path: &Path,- ) -> anyhow::Result<(String, String)> {- let diff = run_jj_command(path, &["diff", "--from", base, "--to", head])?;- let stat = run_jj_command(path, &["diff", "--stat", "--from", base, "--to", head])?;- Ok((diff, stat))- }-- fn recent_subjects(&self, start_ref: Option<&str>, count: usize) -> Option<Vec<String>> {- let count_str = count.to_string();- // ..@- = ancestors of parent (skip empty working-copy commit)- // ..{ref} = ancestors of the given ref (e.g., trunk bookmark)- let rev = match start_ref {- Some(r) => format!("..{r}"),- None => "..@-".to_string(),- };- let output = self- .run_command(&[- "log",- "--no-graph",- "-r",- &rev,- "--limit",- &count_str,- "-T",- r#"description.first_line() ++ "\n""#,- ])- .ok()?;-- let subjects: Vec<String> = output- .lines()- .filter(|l| !l.is_empty())- .map(String::from)- .collect();-- if subjects.is_empty() {- None- } else {- Some(subjects)- }- }-- fn squash_commits(- &self,- target: &str,- message: &str,- path: &Path,- ) -> anyhow::Result<SquashOutcome> {- let feature_tip = self.feature_tip(path)?;- let from_revset = format!("{target}..{feature_tip}");-- // Create empty commit on target, squash feature into it- run_jj_command(path, &["new", target])?;- run_jj_command(- path,- &[- "squash",- "--from",- &from_revset,- "--into",- "@",- "-m",- message,- ],- )?;-- // Update bookmark- run_jj_command(path, &["bookmark", "set", target, "-r", "@"])?;-- // Return the change ID of the squashed commit- let output = run_jj_command(- path,- &[- "log",- "-r",- "@",- "--no-graph",- "-T",- r#"self.change_id().short(12)"#,- ],- )?;-- Ok(SquashOutcome::Squashed(output.trim().to_string()))- }-- fn committable_diff_for_prompt(&self, path: &Path) -> anyhow::Result<(String, String)> {- let diff = run_jj_command(path, &["diff", "-r", "@"])?;- let stat = run_jj_command(path, &["diff", "-r", "@", "--stat"])?;- Ok((diff, stat))- }-- fn list_ignored_entries(&self, path: &Path) -> anyhow::Result<Vec<(PathBuf, bool)>> {- // jj repos have a git backend — find the git dir- let git_dir = self.root.join(".git");- if !git_dir.exists() {- anyhow::bail!(- "No git backend found at {}; copy-ignored requires a git backend",- git_dir.display()- );- }-- let output = crate::shell_exec::Cmd::new("git")- .args([- &format!("--git-dir={}", git_dir.display()),- &format!("--work-tree={}", path.display()),- "ls-files",- "--ignored",- "--exclude-standard",- "-o",- "--directory",- ])- .current_dir(path)- .run()- .context("Failed to run git ls-files in jj workspace")?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- anyhow::bail!("git ls-files failed: {}", stderr.trim());- }-- Ok(String::from_utf8_lossy(&output.stdout)- .lines()- .filter(|line| {- // Filter out .jj/ entries (jj internal directory, gitignored in default workspace)- let trimmed = line.trim_end_matches('/');- trimmed != ".jj" && !trimmed.starts_with(".jj/")- })- .map(|line| {- let is_dir = line.ends_with('/');- let entry_path = path.join(line.trim_end_matches('/'));- (entry_path, is_dir)- })- .collect())- }-- fn has_staging_area(&self) -> bool {- false- }-- fn load_project_config(&self) -> anyhow::Result<Option<crate::config::ProjectConfig>> {- crate::config::ProjectConfig::load_from_root(&self.root).map_err(|e| anyhow::anyhow!("{e}"))- }-- fn wt_logs_dir(&self) -> PathBuf {- self.root.join(".jj").join("wt-logs")- }-- fn switch_previous(&self) -> Option<String> {- // Best-effort: read from jj repo config- self.run_command(&["config", "get", "worktrunk.history"])- .ok()- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty())- }-- fn set_switch_previous(&self, name: Option<&str>) -> anyhow::Result<()> {- match name {- Some(name) => {- self.run_command(&["config", "set", "--repo", "worktrunk.history", name])?;- }- None => {- // Best-effort unset — jj config unset may not exist in older versions- let _ = self.run_command(&["config", "unset", "--repo", "worktrunk.history"]);- }- }- Ok(())- }-- fn as_any(&self) -> &dyn Any {- self- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_parse_diff_stat_summary_with_changes() {- let output = "file.txt | 3 ++-\nnew.txt | 1 +\n2 files changed, 3 insertions(+), 1 deletion(-)";- let diff = parse_diff_stat_summary(output);- assert_eq!(diff.added, 3);- assert_eq!(diff.deleted, 1);- }-- #[test]- fn test_parse_diff_stat_summary_no_changes() {- let output = "0 files changed, 0 insertions(+), 0 deletions(-)";- let diff = parse_diff_stat_summary(output);- assert_eq!(diff.added, 0);- assert_eq!(diff.deleted, 0);- }-- #[test]- fn test_parse_diff_stat_summary_empty() {- let diff = parse_diff_stat_summary("");- assert_eq!(diff.added, 0);- assert_eq!(diff.deleted, 0);- }-- #[test]- fn test_parse_diff_stat_summary_insertions_only() {- let output = "1 file changed, 5 insertions(+)";- let diff = parse_diff_stat_summary(output);- assert_eq!(diff.added, 5);- assert_eq!(diff.deleted, 0);- }-- #[test]- fn test_parse_diff_stat_summary_deletions_only() {- let output = "1 file changed, 3 deletions(-)";- let diff = parse_diff_stat_summary(output);- assert_eq!(diff.added, 0);- assert_eq!(diff.deleted, 3);- }-}diff --git a/src/workspace/mod.rs b/src/workspace/mod.rsdeleted file mode 100644index 523fb5b78..000000000--- a/src/workspace/mod.rs+++ /dev/null@@ -1,361 +0,0 @@-//! VCS-agnostic workspace abstraction.-//!-//! This module provides the [`Workspace`] trait that captures the operations-//! commands need, independent of the underlying VCS (git, jj, etc.).-//!-//! The git implementation is on [`Repository`](crate::git::Repository) directly.-//! The jj implementation ([`JjWorkspace`]) shells out to `jj` CLI commands.-//! Commands that need git-specific features can downcast via-//! `workspace.as_any().downcast_ref::<Repository>()`.-//!-//! Use [`detect_vcs`] to determine which VCS manages a given path.--pub(crate) mod detect;-mod git;-pub(crate) mod jj;-pub mod types;--use std::any::Any;-use std::collections::HashMap;-use std::path::{Path, PathBuf};--use crate::git::WorktreeInfo;-pub use types::{IntegrationReason, LineDiff, LocalPushDisplay, LocalPushResult, path_dir_name};--pub use detect::detect_vcs;-pub use jj::JjWorkspace;--/// Outcome of a rebase operation on the VCS level.-#[derive(Debug)]-pub enum RebaseOutcome {- /// True rebase (history rewritten).- Rebased,- /// Fast-forward (HEAD moved forward, no rewrite).- FastForward,-}--/// Outcome of a squash operation on the VCS level.-pub enum SquashOutcome {- /// Commits were squashed into one. Contains the new commit identifier (short SHA or change ID).- Squashed(String),- /// Squash completed but resulted in no net changes (commits canceled out).- /// Git-only: detected after `reset --soft` when staging area is empty.- NoNetChanges,-}--/// Version control system type.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum VcsKind {- Git,- Jj,-}--/// VCS-agnostic workspace item (worktree in git, workspace in jj).-#[derive(Debug, Clone)]-pub struct WorkspaceItem {- /// Filesystem path to the workspace root.- pub path: PathBuf,- /// Workspace name. In git: derived from branch name (or directory name for- /// detached HEAD). In jj: the native workspace name.- pub name: String,- /// Commit identifier. In git: commit SHA. In jj: change ID.- pub head: String,- /// Branch name (git) or bookmark name (jj). None for detached HEAD (git)- /// or workspaces without bookmarks (jj).- pub branch: Option<String>,- /// Whether this is the default/primary workspace.- pub is_default: bool,- /// Lock reason, if locked.- pub locked: Option<String>,- /// Prunable reason, if prunable (directory deleted but VCS still tracks it).- pub prunable: Option<String>,-}--impl WorkspaceItem {- /// Create a `WorkspaceItem` from a git [`WorktreeInfo`].- ///- /// The `name` field uses the branch name when available, falling back- /// to the directory name for detached HEAD worktrees.- pub fn from_worktree(wt: WorktreeInfo, is_default: bool) -> Self {- let name = wt- .branch- .clone()- .unwrap_or_else(|| path_dir_name(&wt.path).to_string());-- Self {- path: wt.path,- name,- head: wt.head,- branch: wt.branch,- is_default,- locked: wt.locked,- prunable: wt.prunable,- }- }-}--/// VCS-agnostic workspace operations.-///-/// Captures what commands need at the workspace-operation level, not the-/// VCS-command level. Each VCS implementation translates these operations-/// into the appropriate commands.-pub trait Workspace: Send + Sync {- /// Which VCS backs this workspace.- fn kind(&self) -> VcsKind;-- // ====== Discovery ======-- /// List all workspaces in the repository.- fn list_workspaces(&self) -> anyhow::Result<Vec<WorkspaceItem>>;-- /// Resolve a workspace name to its filesystem path.- fn workspace_path(&self, name: &str) -> anyhow::Result<PathBuf>;-- /// Path to the default/primary workspace.- fn default_workspace_path(&self) -> anyhow::Result<Option<PathBuf>>;-- /// Name of the default/trunk branch. Returns `None` if unknown.- /// Git: detected from remote or local heuristics. Jj: from config or `trunk()` revset.- fn default_branch_name(&self) -> Option<String>;-- /// Override the default branch name (persisted to VCS-specific config).- fn set_default_branch(&self, name: &str) -> anyhow::Result<()>;-- /// Clear the configured default branch override. Returns `true` if a value was cleared.- fn clear_default_branch(&self) -> anyhow::Result<bool>;-- // ====== Status per workspace ======-- /// Whether the workspace has uncommitted changes.- fn is_dirty(&self, path: &Path) -> anyhow::Result<bool>;-- /// Line-level diff of uncommitted changes.- fn working_diff(&self, path: &Path) -> anyhow::Result<LineDiff>;-- // ====== Comparison against trunk ======-- /// Commits ahead/behind between two refs.- fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)>;-- /// Check if content identified by `id` is integrated into `target`.- /// Returns the integration reason if integrated, `None` if not.- fn is_integrated(&self, id: &str, target: &str) -> anyhow::Result<Option<IntegrationReason>>;-- /// Line-level diff stats between two refs (committed changes only).- fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff>;-- // ====== Mutations ======-- /// Create a new workspace.- /// - `name`: workspace/branch name- /// - `base`: starting point (branch, commit, or None for default)- /// - `path`: filesystem path for the new workspace- fn create_workspace(&self, name: &str, base: Option<&str>, path: &Path) -> anyhow::Result<()>;-- /// Remove a workspace by name.- fn remove_workspace(&self, name: &str) -> anyhow::Result<()>;-- // ====== Rebase ======-- /// Resolve the integration target (branch/bookmark to rebase onto).- /// Git: validates ref exists, falls back to default branch.- /// Jj: detects trunk bookmark.- fn resolve_integration_target(&self, target: Option<&str>) -> anyhow::Result<String>;-- /// Whether the current workspace is already rebased onto `target`.- /// Git: merge-base == target SHA, no merge commits between.- /// Jj: target is ancestor of feature tip.- fn is_rebased_onto(&self, target: &str, path: &Path) -> anyhow::Result<bool>;-- /// Rebase the current workspace onto `target`.- /// Returns the outcome (Rebased vs FastForward).- /// Implementations emit their own progress message when appropriate.- fn rebase_onto(&self, target: &str, path: &Path) -> anyhow::Result<RebaseOutcome>;-- // ====== Identity ======-- /// Root path of the repository (git dir or jj repo root).- fn root_path(&self) -> anyhow::Result<PathBuf>;-- /// Filesystem path of the current workspace/worktree.- ///- /// Git: uses `current_worktree().path()` (respects `-C` flag via cwd).- /// Jj: uses `current_workspace().path` (found via cwd).- fn current_workspace_path(&self) -> anyhow::Result<PathBuf>;-- /// Current workspace/branch name at the given path.- /// Returns `None` for detached HEAD (git) or workspaces without bookmarks (jj).- fn current_name(&self, path: &Path) -> anyhow::Result<Option<String>>;-- /// Project identifier for approval/hook scoping.- /// Uses remote URL if available, otherwise the canonical repository path.- fn project_identifier(&self) -> anyhow::Result<String>;-- // ====== Commit ======-- /// Commit staged/working changes with the given message.- /// Returns the new commit identifier (SHA for git, change ID for jj).- fn commit(&self, message: &str, path: &Path) -> anyhow::Result<String>;-- /// Subject lines of commits between `base` and `head`.- fn commit_subjects(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>>;-- // ====== Push ======-- /// Push current branch/bookmark to remote, fast-forward only.- /// `target` is the branch/bookmark to update on the remote.- fn push_to_target(&self, target: &str, path: &Path) -> anyhow::Result<()>;-- /// Advance the target branch ref to include current feature commits (local only).- ///- /// "Local push" means moving the target branch pointer forward — no remote- /// interaction. This is the git term for advancing a ref locally via- /// `git push <local-path>`.- ///- /// Git: fast-forward the target branch to HEAD, with auto-stash/restore of- /// non-conflicting changes in the target worktree. Emits progress messages- /// (commit graph, diffstat) to stderr.- /// Jj: `jj bookmark set` to move the target bookmark to the feature tip.- ///- /// Returns a [`LocalPushResult`] with commit count and optional stats for- /// the command handler to format the final success message.- fn local_push(- &self,- target: &str,- path: &Path,- display: LocalPushDisplay<'_>,- ) -> anyhow::Result<LocalPushResult>;-- // ====== Squash ======-- /// The current feature head reference for squash/diff operations.- ///- /// Git: `"HEAD"` (literal string — git resolves it).- /// Jj: the feature tip change ID (@ if non-empty, @- otherwise).- fn feature_head(&self, path: &Path) -> anyhow::Result<String>;-- /// Produce a diff and diffstat between two refs, suitable for LLM prompt consumption.- ///- /// Returns `(raw_diff, diffstat)`.- /// Git: `git diff base..head` with consistent prefix settings.- /// Jj: `jj diff --from base --to head`.- fn diff_for_prompt(- &self,- base: &str,- head: &str,- path: &Path,- ) -> anyhow::Result<(String, String)>;-- /// Recent commit subjects for LLM style reference.- ///- /// Returns up to `count` recent commit subjects, starting from `start_ref` if given.- /// Returns `None` if no commits are available.- fn recent_subjects(&self, start_ref: Option<&str>, count: usize) -> Option<Vec<String>>;-- /// Squash all commits between target and HEAD/feature-tip into a single commit.- ///- /// Git: `git reset --soft <merge-base> && git commit -m <message>`- /// Jj: `jj new {target} && jj squash --from '{target}..{tip}' --into @ -m <message>`- ///- /// The message is generated by the command handler (LLM, template, or fallback).- /// Returns `SquashOutcome::Squashed(id)` on success, or `NoNetChanges` if the- /// commits cancel out (git-only: empty staging area after soft reset).- fn squash_commits(- &self,- target: &str,- message: &str,- path: &Path,- ) -> anyhow::Result<SquashOutcome>;-- // ====== Commit prompt ======-- /// Diff and diffstat of changes that would be committed, for LLM prompt consumption.- ///- /// Returns `(raw_diff, diffstat)` representing "what's about to be committed."- /// Git: staged changes (`git diff --staged`).- /// Jj: working-copy changes (`jj diff -r @`).- fn committable_diff_for_prompt(&self, path: &Path) -> anyhow::Result<(String, String)>;-- // ====== Copy-ignored ======-- /// List ignored (by `.gitignore`) entries in the given workspace directory.- ///- /// Returns `(absolute_path, is_directory)` pairs. Uses directory-level- /// granularity — stops at directory boundaries so `target/` is one entry,- /// not thousands of files.- ///- /// Git: `git ls-files --ignored --exclude-standard -o --directory`- /// Jj: same command with explicit `--git-dir` pointing to the git backend.- fn list_ignored_entries(&self, path: &Path) -> anyhow::Result<Vec<(PathBuf, bool)>>;-- // ====== Capabilities ======-- /// Whether this VCS has a staging area (index).- /// Git: true. Jj: false.- fn has_staging_area(&self) -> bool;-- // ====== Hooks & Configuration ======-- /// Load project configuration (`.config/wt.toml`) from the repository root.- fn load_project_config(&self) -> anyhow::Result<Option<crate::config::ProjectConfig>>;-- /// Directory for background hook log files.- /// Git: `.git/wt-logs/`. Jj: `.jj/wt-logs/`.- fn wt_logs_dir(&self) -> PathBuf;-- /// Previously-switched-from workspace name (for `wt switch -`).- fn switch_previous(&self) -> Option<String>;-- /// Record the current workspace name before switching away.- fn set_switch_previous(&self, name: Option<&str>) -> anyhow::Result<()>;-- /// Downcast to concrete type for VCS-specific operations.- fn as_any(&self) -> &dyn Any;-}--/// Build a branch→path lookup map from workspace items.-///-/// Used by `expand_template` for the `worktree_path_of_branch()` template function.-/// Maps both workspace names and branch names to their filesystem paths, so lookups-/// work with either identifier.-pub fn build_worktree_map(workspace: &dyn Workspace) -> HashMap<String, PathBuf> {- workspace- .list_workspaces()- .unwrap_or_default()- .into_iter()- .flat_map(|ws| {- let mut entries = vec![(ws.name.clone(), ws.path.clone())];- if let Some(branch) = &ws.branch- && branch != &ws.name- {- entries.push((branch.clone(), ws.path.clone()));- }- entries- })- .collect()-}--/// Detect VCS and open the appropriate workspace for the current directory.-///-/// The `-C` flag is handled by `std::env::set_current_dir()` in main.rs before-/// any commands run, so `current_dir()` already reflects the right path.-///-/// Falls back to `Repository::current()` when filesystem markers aren't found,-/// which handles bare repos and other non-standard layouts that git itself can discover.-pub fn open_workspace() -> anyhow::Result<Box<dyn Workspace>> {- let detect_path = std::env::current_dir()?;- match detect_vcs(&detect_path) {- Some(VcsKind::Jj) => Ok(Box::new(JjWorkspace::from_current_dir()?)),- Some(VcsKind::Git) => {- let repo = crate::git::Repository::current()?;- Ok(Box::new(repo))- }- None => {- // Fallback: try git discovery (handles bare repos, -C flag, etc.)- match crate::git::Repository::current() {- Ok(repo) => Ok(Box::new(repo)),- Err(_) => anyhow::bail!("Not in a repository"),- }- }- }-}diff --git a/src/workspace/types.rs b/src/workspace/types.rsdeleted file mode 100644index faca98bd8..000000000--- a/src/workspace/types.rs+++ /dev/null@@ -1,241 +0,0 @@-//! Shared types used by both VCS implementations.-//!-//! These types are VCS-agnostic and shared between git and jj workspace-//! implementations. They are re-exported from [`crate::git`] for backward-//! compatibility.--use std::path::Path;--/// Line-level diff totals (added/deleted counts) used across VCS operations.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]-pub struct LineDiff {- pub added: usize,- pub deleted: usize,-}--impl LineDiff {- pub fn is_empty(&self) -> bool {- self.added == 0 && self.deleted == 0- }-}--impl From<LineDiff> for (usize, usize) {- fn from(diff: LineDiff) -> Self {- (diff.added, diff.deleted)- }-}--impl From<(usize, usize)> for LineDiff {- fn from(value: (usize, usize)) -> Self {- Self {- added: value.0,- deleted: value.1,- }- }-}--/// Why branch content is considered integrated into the target branch.-///-/// Used by both `wt list` (for status symbols) and `wt remove` (for messages).-/// Each variant corresponds to a specific integration check. In `wt list`,-/// three symbols represent these checks:-/// - `_` for [`SameCommit`](Self::SameCommit) with clean working tree (empty)-/// - `–` for [`SameCommit`](Self::SameCommit) with dirty working tree-/// - `⊂` for all others (content integrated via different history)-///-/// The checks are ordered by cost (cheapest first):-/// 1. [`SameCommit`](Self::SameCommit) - commit SHA comparison (~1ms)-/// 2. [`Ancestor`](Self::Ancestor) - ancestor check (~1ms)-/// 3. [`NoAddedChanges`](Self::NoAddedChanges) - three-dot diff (~50-100ms)-/// 4. [`TreesMatch`](Self::TreesMatch) - tree SHA comparison (~100-300ms)-/// 5. [`MergeAddsNothing`](Self::MergeAddsNothing) - merge simulation (~500ms-2s)-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, strum::IntoStaticStr)]-#[serde(rename_all = "kebab-case")]-#[strum(serialize_all = "kebab-case")]-pub enum IntegrationReason {- /// Branch HEAD is literally the same commit as target.- ///- /// Used by `wt remove` to determine if branch is safely deletable.- /// In `wt list`, same-commit state is shown via `MainState::Empty` (`_`) or- /// `MainState::SameCommit` (`–`) depending on working tree cleanliness.- SameCommit,-- /// Branch HEAD is an ancestor of target (target has moved past this branch).- ///- /// Symbol in `wt list`: `⊂`- Ancestor,-- /// Three-dot diff (`main...branch`) shows no files.- /// The branch has no file changes beyond the merge-base.- ///- /// Symbol in `wt list`: `⊂`- NoAddedChanges,-- /// Branch tree SHA equals target tree SHA.- /// Commit history differs but file contents are identical.- ///- /// Symbol in `wt list`: `⊂`- TreesMatch,-- /// Simulated merge (`git merge-tree`) produces the same tree as target.- /// The branch has changes, but they're already in target via a different path.- ///- /// Symbol in `wt list`: `⊂`- MergeAddsNothing,-}--impl IntegrationReason {- /// Human-readable description for use in messages (e.g., `wt remove` output).- ///- /// Returns a phrase that expects the target branch name to follow- /// (e.g., "same commit as" + "main" → "same commit as main").- pub fn description(&self) -> &'static str {- match self {- Self::SameCommit => "same commit as",- Self::Ancestor => "ancestor of",- Self::NoAddedChanges => "no added changes on",- Self::TreesMatch => "tree matches",- Self::MergeAddsNothing => "all changes in",- }- }-- /// Status symbol used in `wt list` for this integration reason.- ///- /// - `SameCommit` → `_` (matches `MainState::Empty`)- /// - Others → `⊂` (matches `MainState::Integrated`)- pub fn symbol(&self) -> &'static str {- match self {- Self::SameCommit => "_",- _ => "⊂",- }- }-}--/// Display context for the local push progress message.-///-/// Controls the verb and optional notes in the progress line emitted by-/// `local_push`. E.g. merge passes `verb: "Merging"` and notes like-/// "(no commit/squash needed)", while step push uses the default "Pushing".-///-/// "Local push" means advancing a target branch ref to include feature commits —-/// no remote interaction. Git implements this via `git push <local-path>`,-/// jj via `jj bookmark set`.-pub struct LocalPushDisplay<'a> {- /// Verb in -ing form for the progress line.- pub verb: &'a str,- /// Optional parenthetical notes appended after the SHA- /// (e.g., " (no commit/squash needed)"). Include the leading space.- /// Empty string = omitted.- pub notes: &'a str,-}--impl Default for LocalPushDisplay<'_> {- fn default() -> Self {- Self {- verb: "Pushing",- notes: "",- }- }-}--/// Result of a local push operation, with enough data for the command handler-/// to format the final success/info message.-///-/// "Local push" means advancing a target branch ref — no remote interaction.-#[derive(Debug, Clone)]-pub struct LocalPushResult {- /// Number of commits pushed locally (0 = already up-to-date).- pub commit_count: usize,- /// Summary parts for the success message parenthetical.- /// E.g. `["1 commit", "1 file", "+1"]`. Empty for jj or when count is 0.- pub stats_summary: Vec<String>,-}--/// Extract the directory name from a path for display purposes.-///-/// Returns the last component of the path as a string, or "(unknown)" if-/// the path has no filename or contains invalid UTF-8.-pub fn path_dir_name(path: &Path) -> &str {- path.file_name()- .and_then(|n| n.to_str())- .unwrap_or("(unknown)")-}--#[cfg(test)]-mod tests {- use super::*;- use std::path::Path;-- #[test]- fn test_line_diff_is_empty() {- assert!(LineDiff::default().is_empty());- assert!(- !LineDiff {- added: 1,- deleted: 0- }- .is_empty()- );- assert!(- !LineDiff {- added: 0,- deleted: 1- }- .is_empty()- );- }-- #[test]- fn test_integration_reason_symbol() {- assert_eq!(IntegrationReason::SameCommit.symbol(), "_");- assert_eq!(IntegrationReason::Ancestor.symbol(), "⊂");- assert_eq!(IntegrationReason::NoAddedChanges.symbol(), "⊂");- assert_eq!(IntegrationReason::TreesMatch.symbol(), "⊂");- assert_eq!(IntegrationReason::MergeAddsNothing.symbol(), "⊂");- }-- #[test]- fn test_path_dir_name() {- assert_eq!(- path_dir_name(Path::new("/repos/myrepo.feature")),- "myrepo.feature"- );- assert_eq!(path_dir_name(Path::new("/")), "(unknown)");- }-- #[test]- fn test_line_diff_conversions() {- let diff = LineDiff {- added: 10,- deleted: 5,- };- let tuple: (usize, usize) = diff.into();- assert_eq!(tuple, (10, 5));- let back: LineDiff = (3, 7).into();- assert_eq!(- back,- LineDiff {- added: 3,- deleted: 7- }- );- }-- #[test]- fn test_integration_reason_description() {- assert_eq!(- IntegrationReason::SameCommit.description(),- "same commit as"- );- assert_eq!(IntegrationReason::Ancestor.description(), "ancestor of");- assert_eq!(- IntegrationReason::NoAddedChanges.description(),- "no added changes on"- );- assert_eq!(IntegrationReason::TreesMatch.description(), "tree matches");- assert_eq!(- IntegrationReason::MergeAddsNothing.description(),- "all changes in"- );- }-}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex f4c2b4677..6346a3334 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -2839,52 +2839,6 @@ pub fn setup_temp_snapshot_settings(temp_path: &std::path::Path) -> insta::Settisettings}-/// Create configured insta Settings for jj integration test snapshots.-///-/// Reuses the core snapshot settings pipeline (ANSI cleanup, path normalization)-/// but adapted for jj repos where the "repo root" is the default workspace path.-///-/// Filters applied:-/// - Repo root → `_REPO_`-/// - Workspace paths → `_REPO_.{name}`-/// - Change IDs (12-char hex) → `[CHANGE_ID]`-/// - Standard env/temp/project redactions-pub fn setup_snapshot_settings_for_jj(- root: &Path,- workspaces: &HashMap<String, PathBuf>,-) -> insta::Settings {- let mut settings = setup_snapshot_settings_for_paths(root, workspaces);-- // jj change IDs vary between runs. They are lowercase-only alphabetic strings- // that appear in several forms:- // - 12-char IDs in plain text (e.g., "Showing 1 xyzwabcdklmn")- // - 8-char IDs in the Commit column (wrapped in ANSI dim)- // - 12-char IDs in ANSI dim context (e.g., "Squashed @ <dim>id</dim>")- //- // The ANSI-wrapped forms need explicit matching because \b word boundaries- // don't work at ANSI code boundaries (the trailing 'm' of \x1b[2m is a word char).- //- // Match 8-char IDs in ANSI dim context (\x1b[2m...\x1b[0m — list output)- settings.add_filter(- r"\x1b\[2m([a-z]{8})\x1b\[0m",- "\x1b[2m[CHANGE_ID_SHORT]\x1b[0m",- );- // Match 12-char IDs in ANSI dim context (\x1b[2m...\x1b[22m — squash output)- settings.add_filter(- r"\x1b\[2m([a-z]{12})\x1b\[22m",- "\x1b[2m[CHANGE_ID]\x1b[22m",- );- // Match 12-char IDs in plain text (e.g., "Showing 1 xyzwabcdklmn")- settings.add_filter(r"\b[a-z]{12}\b", "[CHANGE_ID]");- // Match 8-char IDs in plain text (fallback for non-ANSI contexts)- settings.add_filter(r"\b[a-z]{8}\b", "[CHANGE_ID_SHORT]");- // Match git commit hashes (hex, 12 chars) in jj output (e.g., "to 26009b197b6c").- // Applied after the [a-z]-only filters so pure-alpha IDs are caught as change IDs first.- settings.add_filter(r"\b[0-9a-f]{12}\b", "[COMMIT_HASH]");-- settings-}-// =============================================================================// PTY Test Filters// =============================================================================diff --git a/tests/integration_tests/config_init.rs b/tests/integration_tests/config_init.rsindex 56ca40fef..52fb9f5f5 100644--- a/tests/integration_tests/config_init.rs+++ b/tests/integration_tests/config_init.rs@@ -77,7 +77,7 @@ fn test_config_create_project_creates_file(repo: TestRepo) {----- stdout ---------- stderr ------ [32m✓[39m [32mCreated project config: [1m./.config/wt.toml[22m[39m+ [32m✓[39m [32mCreated project config: [1m_REPO_/.config/wt.toml[22m[39m[2m↳[22m [2mEdit this file to configure hooks for this repository[22m[2m↳[22m [2mSee https://worktrunk.dev/hook/ for hook documentation[22m@@ -114,7 +114,7 @@ run = "echo hello"----- stdout ---------- stderr ------ [2m○[22m Project config already exists: [1m./.config/wt.toml[22m+ [2m○[22m Project config already exists: [1m_REPO_/.config/wt.toml[22m[2m↳[22m [2mTo view, run [90mwt config show[39m. To create a user config, run [90mwt config create[39m[22m");});diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rsindex f4e75a792..aa6d0da09 100644--- a/tests/integration_tests/doc_templates.rs+++ b/tests/integration_tests/doc_templates.rs@@ -7,19 +7,13 @@//! Run with: `cargo test --test integration doc_templates`use std::collections::HashMap;-use std::path::PathBuf;use rstest::rstest;use worktrunk::config::expand_template;use worktrunk::git::Repository;-use worktrunk::workspace::build_worktree_map;use crate::common::{TestRepo, repo};-fn empty_map() -> HashMap<String, PathBuf> {- HashMap::new()-}-/// Helper to compute hash_port for a string.////// Must match `string_to_port()` in `src/config/expansion.rs`.@@ -34,9 +28,9 @@ fn hash_port(s: &str) -> u16 {// Basic Variables (docs/content/hook.md: Template variables table)// =============================================================================-#[test]-fn test_doc_basic_variables() {- let worktree_map = empty_map();+#[rstest]+fn test_doc_basic_variables(repo: TestRepo) {+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("repo", "myproject");vars.insert("branch", "feature/auth");@@ -45,19 +39,19 @@ fn test_doc_basic_variables() {// Each variable substitutes correctlyassert_eq!(- expand_template("{{ repo }}", &vars, false, &worktree_map, "test").unwrap(),+ expand_template("{{ repo }}", &vars, false, &repository, "test").unwrap(),"myproject");assert_eq!(- expand_template("{{ branch }}", &vars, false, &worktree_map, "test").unwrap(),+ expand_template("{{ branch }}", &vars, false, &repository, "test").unwrap(),"feature/auth");assert_eq!(- expand_template("{{ worktree }}", &vars, false, &worktree_map, "test").unwrap(),+ expand_template("{{ worktree }}", &vars, false, &repository, "test").unwrap(),"/home/user/myproject.feature-auth");assert_eq!(- expand_template("{{ default_branch }}", &vars, false, &worktree_map, "test").unwrap(),+ expand_template("{{ default_branch }}", &vars, false, &repository, "test").unwrap(),"main");}@@ -67,36 +61,22 @@ fn test_doc_basic_variables() {// "Replace `/` and `\` with `-`"// =============================================================================-#[test]-fn test_doc_sanitize_filter() {+#[rstest]+fn test_doc_sanitize_filter(repo: TestRepo) {let mut vars = HashMap::new();- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();// From docs: {{ branch | sanitize }} replaces / and \ with -vars.insert("branch", "feature/foo");assert_eq!(- expand_template(- "{{ branch | sanitize }}",- &vars,- false,- &worktree_map,- "test"- )- .unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),"feature-foo","sanitize should replace / with -");vars.insert("branch", "user\\task");assert_eq!(- expand_template(- "{{ branch | sanitize }}",- &vars,- false,- &worktree_map,- "test"- )- .unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),"user-task","sanitize should replace \\ with -");@@ -104,14 +84,7 @@ fn test_doc_sanitize_filter() {// Nested pathsvars.insert("branch", "user/feature/task");assert_eq!(- expand_template(- "{{ branch | sanitize }}",- &vars,- false,- &worktree_map,- "test"- )- .unwrap(),+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap(),"user-feature-task","sanitize should handle multiple slashes");@@ -122,10 +95,10 @@ fn test_doc_sanitize_filter() {// "Transform to database-safe identifier ([a-z0-9_], max 63 chars)"// =============================================================================-#[test]-fn test_doc_sanitize_db_filter() {+#[rstest]+fn test_doc_sanitize_db_filter(repo: TestRepo) {let mut vars = HashMap::new();- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();// From docs: {{ branch | sanitize_db }} transforms to database-safe identifier// Output includes a 3-character hash suffix for uniqueness@@ -134,7 +107,7 @@ fn test_doc_sanitize_db_filter() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -149,7 +122,7 @@ fn test_doc_sanitize_db_filter() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -164,7 +137,7 @@ fn test_doc_sanitize_db_filter() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -179,7 +152,7 @@ fn test_doc_sanitize_db_filter() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -194,7 +167,7 @@ fn test_doc_sanitize_db_filter() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -203,7 +176,7 @@ fn test_doc_sanitize_db_filter() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -213,9 +186,9 @@ fn test_doc_sanitize_db_filter() {);}-#[test]-fn test_doc_sanitize_db_truncation() {- let worktree_map = empty_map();+#[rstest]+fn test_doc_sanitize_db_truncation(repo: TestRepo) {+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();// Truncates to 63 characters (PostgreSQL limit)@@ -225,7 +198,7 @@ fn test_doc_sanitize_db_truncation() {"{{ branch | sanitize_db }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -241,17 +214,17 @@ fn test_doc_sanitize_db_truncation() {// "Hash to port 10000-19999"// =============================================================================-#[test]-fn test_doc_hash_port_filter() {+#[rstest]+fn test_doc_hash_port_filter(repo: TestRepo) {let mut vars = HashMap::new();vars.insert("branch", "feature-foo");- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let result = expand_template("{{ branch | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -267,7 +240,7 @@ fn test_doc_hash_port_filter() {"{{ branch | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -279,8 +252,8 @@ fn test_doc_hash_port_filter() {// CRITICAL: These test the operator precedence issue from PR #373// =============================================================================-#[test]-fn test_doc_hash_port_concatenation_precedence() {+#[rstest]+fn test_doc_hash_port_concatenation_precedence(repo: TestRepo) {// From docs/content/tips-patterns.md:// "The `'db-' ~ branch` concatenation hashes differently than plain `branch`"//@@ -289,14 +262,14 @@ fn test_doc_hash_port_concatenation_precedence() {let mut vars = HashMap::new();vars.insert("branch", "feature");- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();// With parentheses (correct, as documented)let with_parens = expand_template("{{ ('db-' ~ branch) | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -314,7 +287,7 @@ fn test_doc_hash_port_concatenation_precedence() {"{{ 'db-' ~ branch | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -335,12 +308,12 @@ fn test_doc_hash_port_concatenation_precedence() {);}-#[test]-fn test_doc_hash_port_repo_branch_concatenation() {+#[rstest]+fn test_doc_hash_port_repo_branch_concatenation(repo: TestRepo) {// From docs/content/hook.md line 176:// dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("repo", "myapp");vars.insert("branch", "feature");@@ -349,7 +322,7 @@ fn test_doc_hash_port_repo_branch_concatenation() {"{{ (repo ~ '-' ~ branch) | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -368,12 +341,12 @@ fn test_doc_hash_port_repo_branch_concatenation() {// These test complete template strings from the documentation// =============================================================================-#[test]-fn test_doc_example_docker_postgres() {+#[rstest]+fn test_doc_example_docker_postgres(repo: TestRepo) {// From docs/content/tips-patterns.md lines 75-84:// docker run ... -p {{ ('db-' ~ branch) | hash_port }}:5432- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("repo", "myproject");vars.insert("branch", "feature-auth");@@ -383,7 +356,7 @@ fn test_doc_example_docker_postgres() {-p {{ ('db-' ~ branch) | hash_port }}:5432 \postgres:16"#;- let result = expand_template(template, &vars, false, &worktree_map, "test").unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();// Check the container name uses sanitized branchassert!(@@ -399,19 +372,19 @@ fn test_doc_example_docker_postgres() {);}-#[test]-fn test_doc_example_database_url() {+#[rstest]+fn test_doc_example_database_url(repo: TestRepo) {// From docs/content/tips-patterns.md lines 96-101:// DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("repo", "myproject");vars.insert("branch", "feature");let template = "DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}";- let result = expand_template(template, &vars, false, &worktree_map, "test").unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();let expected_port = hash_port("db-feature");assert_eq!(@@ -420,18 +393,18 @@ fn test_doc_example_database_url() {);}-#[test]-fn test_doc_example_dev_server() {+#[rstest]+fn test_doc_example_dev_server(repo: TestRepo) {// From docs/content/hook.md lines 168-170:// dev = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}"- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("branch", "feature-auth");let template = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}";- let result = expand_template(template, &vars, false, &worktree_map, "test").unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();let expected_port = hash_port("feature-auth");assert_eq!(@@ -440,19 +413,19 @@ fn test_doc_example_dev_server() {);}-#[test]-fn test_doc_example_worktree_path_sanitize() {+#[rstest]+fn test_doc_example_worktree_path_sanitize(repo: TestRepo) {// From docs/content/tips-patterns.md line 217:// worktree-path = "{{ branch | sanitize }}"- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("branch", "feature/user/auth");vars.insert("main_worktree", "/home/user/project");let template = "{{ main_worktree }}.{{ branch | sanitize }}";- let result = expand_template(template, &vars, false, &worktree_map, "test").unwrap();+ let result = expand_template(template, &vars, false, &repository, "test").unwrap();assert_eq!(result, "/home/user/project.feature-user-auth");}@@ -460,9 +433,9 @@ fn test_doc_example_worktree_path_sanitize() {// Edge Cases// =============================================================================-#[test]-fn test_doc_hash_port_empty_string() {- let worktree_map = empty_map();+#[rstest]+fn test_doc_hash_port_empty_string(repo: TestRepo) {+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("branch", "");@@ -470,7 +443,7 @@ fn test_doc_hash_port_empty_string() {"{{ branch | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -482,30 +455,24 @@ fn test_doc_hash_port_empty_string() {);}-#[test]-fn test_doc_sanitize_no_slashes() {- let worktree_map = empty_map();+#[rstest]+fn test_doc_sanitize_no_slashes(repo: TestRepo) {+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("branch", "simple-branch");- let result = expand_template(- "{{ branch | sanitize }}",- &vars,- false,- &worktree_map,- "test",- )- .unwrap();+ let result =+ expand_template("{{ branch | sanitize }}", &vars, false, &repository, "test").unwrap();assert_eq!(result, "simple-branch","sanitize should be no-op without slashes");}-#[test]-fn test_doc_combined_filters() {+#[rstest]+fn test_doc_combined_filters(repo: TestRepo) {// sanitize then hash_port (not currently documented, but should work)- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let mut vars = HashMap::new();vars.insert("branch", "feature/auth");@@ -513,7 +480,7 @@ fn test_doc_combined_filters() {"{{ branch | sanitize | hash_port }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -528,16 +495,16 @@ fn test_doc_combined_filters() {// worktree_path_of_branch Function// =============================================================================-#[test]-fn test_worktree_path_of_branch_function_registered() {+#[rstest]+fn test_worktree_path_of_branch_function_registered(repo: TestRepo) {// Test that worktree_path_of_branch function is callable and returns empty for nonexistent branch- let worktree_map = empty_map();+ let repository = Repository::at(repo.root_path()).unwrap();let vars: HashMap<&str, &str> = HashMap::new();let result = expand_template("{{ worktree_path_of_branch('nonexistent') }}",&vars,false,- &worktree_map,+ &repository,"test",);assert_eq!(result.unwrap(), "");@@ -562,9 +529,7 @@ fn test_worktree_path_of_branch_shell_escape(repo: TestRepo) {"test-branch",]);- // Build worktree map from the repo (after worktree creation so it's included)let repository = Repository::at(repo.root_path()).unwrap();- let worktree_map = build_worktree_map(&repository);let vars: HashMap<&str, &str> = HashMap::new();// With shell_escape=false, path is returned literally@@ -572,7 +537,7 @@ fn test_worktree_path_of_branch_shell_escape(repo: TestRepo) {"{{ worktree_path_of_branch('test-branch') }}",&vars,false,- &worktree_map,+ &repository,"test",).unwrap();@@ -587,7 +552,7 @@ fn test_worktree_path_of_branch_shell_escape(repo: TestRepo) {"{{ worktree_path_of_branch('test-branch') }}",&vars,true,- &worktree_map,+ &repository,"test",).unwrap();diff --git a/tests/integration_tests/jj.rs b/tests/integration_tests/jj.rsdeleted file mode 100644index 8569e696d..000000000--- a/tests/integration_tests/jj.rs+++ /dev/null@@ -1,1467 +0,0 @@-//! Integration tests for jj (Jujutsu) workspace support.-//!-//! These tests exercise the `wt` CLI against real jj repositories.-//! They require `jj` to be installed (0.38.0+). Gated behind the-//! `shell-integration-tests` feature flag (alongside shell/PTY tests).-#![cfg(all(unix, feature = "shell-integration-tests"))]--use crate::common::{- canonicalize, configure_cli_command, configure_directive_file, directive_file,- setup_snapshot_settings_for_jj, wt_bin,-};-use insta_cmd::assert_cmd_snapshot;-use rstest::{fixture, rstest};-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::process::Command;-use tempfile::TempDir;--// ============================================================================-// JjTestRepo — test fixture for jj repositories-// ============================================================================--pub struct JjTestRepo {- _temp_dir: TempDir,- root: PathBuf,- workspaces: HashMap<String, PathBuf>,- /// Snapshot settings guard — keeps insta filters active for this repo's lifetime.- _snapshot_guard: insta::internals::SettingsBindDropGuard,-}--impl JjTestRepo {- /// Create a new jj repository with deterministic configuration.- ///- /// The repo includes:- /// - A `jj git init` repository at `{temp}/repo/`- /// - Deterministic user config (Test User / [email protected])- /// - An initial commit with README.md- /// - A `main` bookmark on trunk so `trunk()` resolves- pub fn new() -> Self {- let temp_dir = TempDir::new().unwrap();- let repo_dir = temp_dir.path().join("repo");-- // jj git init repo- let output = Command::new("jj")- .args(["git", "init", "repo"])- .current_dir(temp_dir.path())- .output()- .expect("Failed to run jj git init");- assert!(- output.status.success(),- "jj git init failed: {}",- String::from_utf8_lossy(&output.stderr)- );-- let root = canonicalize(&repo_dir).unwrap();-- // Configure deterministic user identity- run_jj_in(- &root,- &["config", "set", "--repo", "user.name", "Test User"],- );- run_jj_in(- &root,- &["config", "set", "--repo", "user.email", "[email protected]"],- );-- // Create initial commit with a file so trunk() resolves- std::fs::write(root.join("README.md"), "# Test repo\n").unwrap();- run_jj_in(&root, &["describe", "-m", "Initial commit"]);- // Create new empty commit on top so @ is separate from trunk- run_jj_in(&root, &["new"]);- // Set main bookmark on the initial commit (trunk)- run_jj_in(&root, &["bookmark", "set", "main", "-r", "@-"]);-- let workspaces = HashMap::new();- let snapshot_guard = setup_snapshot_settings_for_jj(&root, &workspaces).bind_to_scope();-- Self {- _temp_dir: temp_dir,- root,- workspaces,- _snapshot_guard: snapshot_guard,- }- }-- /// Root path of the default workspace.- pub fn root_path(&self) -> &Path {- &self.root- }-- /// The temp directory containing the repo (used as HOME in tests).- pub fn home_path(&self) -> &Path {- self._temp_dir.path()- }-- /// Add a new workspace with the given name.- ///- /// Creates the workspace as a sibling directory: `{temp}/repo.{name}`- pub fn add_workspace(&mut self, name: &str) -> PathBuf {- if let Some(path) = self.workspaces.get(name) {- return path.clone();- }-- let ws_path = self.root.parent().unwrap().join(format!("repo.{name}"));- let ws_path_str = ws_path.to_str().unwrap();-- run_jj_in(- &self.root,- &["workspace", "add", "--name", name, ws_path_str],- );-- let canonical = canonicalize(&ws_path).unwrap();- self.workspaces.insert(name.to_string(), canonical.clone());- canonical- }-- /// Make a commit in a specific workspace directory.- pub fn commit_in(&self, dir: &Path, filename: &str, content: &str, message: &str) {- std::fs::write(dir.join(filename), content).unwrap();- run_jj_in(dir, &["describe", "-m", message]);- run_jj_in(dir, &["new"]);- }-- /// Create a `wt` command pre-configured for this jj test repo.- pub fn wt_command(&self) -> Command {- let mut cmd = Command::new(wt_bin());- self.configure_wt_cmd(&mut cmd);- cmd.current_dir(&self.root);- cmd- }-- /// Configure a wt command with isolated test environment.- pub fn configure_wt_cmd(&self, cmd: &mut Command) {- configure_cli_command(cmd);- // Point to a non-existent config so tests are isolated- let test_config = self.home_path().join("test-config.toml");- cmd.env("WORKTRUNK_CONFIG_PATH", &test_config);- // Set HOME to temp dir so paths normalize- let home = canonicalize(self.home_path()).unwrap();- cmd.env("HOME", &home);- cmd.env("XDG_CONFIG_HOME", home.join(".config"));- cmd.env("USERPROFILE", &home);- cmd.env("APPDATA", home.join(".config"));- }-- /// Write a config file with a mock LLM command and return its path.- ///- /// The command just echoes a fixed commit message, ignoring stdin.- pub fn write_llm_config(&self) -> PathBuf {- let config_path = self.home_path().join("llm-config.toml");- std::fs::write(- &config_path,- "[commit.generation]\ncommand = \"echo LLM-generated-message\"\n",- )- .unwrap();- config_path- }-- /// Write project-specific config (`.config/wt.toml`) under the repo root.- pub fn write_project_config(&self, contents: &str) {- let config_dir = self.root.join(".config");- std::fs::create_dir_all(&config_dir).unwrap();- std::fs::write(config_dir.join("wt.toml"), contents).unwrap();- }-- /// Path to a named workspace.- pub fn workspace_path(&self, name: &str) -> &Path {- self.workspaces- .get(name)- .unwrap_or_else(|| panic!("Workspace '{}' not found", name))- }-}--/// Run a jj command in a directory, panicking on failure.-fn run_jj_in(dir: &Path, args: &[&str]) {- let mut full_args = vec!["--no-pager", "--color", "never"];- full_args.extend_from_slice(args);-- let output = Command::new("jj")- .args(&full_args)- .current_dir(dir)- .output()- .unwrap_or_else(|e| panic!("Failed to execute jj {}: {}", args.join(" "), e));-- if !output.status.success() {- panic!(- "jj {} failed:\nstdout: {}\nstderr: {}",- args.join(" "),- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );- }-}--// ============================================================================-// Snapshot helpers-// ============================================================================--fn make_jj_snapshot_cmd(- repo: &JjTestRepo,- subcommand: &str,- args: &[&str],- cwd: Option<&Path>,-) -> Command {- let mut cmd = Command::new(wt_bin());- repo.configure_wt_cmd(&mut cmd);- cmd.arg(subcommand)- .args(args)- .current_dir(cwd.unwrap_or(repo.root_path()));- cmd-}--/// Like `make_jj_snapshot_cmd` but with a custom config path (e.g., for LLM tests).-fn make_jj_snapshot_cmd_with_config(- repo: &JjTestRepo,- subcommand: &str,- args: &[&str],- cwd: Option<&Path>,- config_path: &Path,-) -> Command {- let mut cmd = make_jj_snapshot_cmd(repo, subcommand, args, cwd);- cmd.env("WORKTRUNK_CONFIG_PATH", config_path);- cmd-}--// ============================================================================-// rstest fixtures-// ============================================================================--#[fixture]-fn jj_repo() -> JjTestRepo {- JjTestRepo::new()-}--/// Repo with one feature workspace containing a commit.-#[fixture]-fn jj_repo_with_feature(mut jj_repo: JjTestRepo) -> JjTestRepo {- let ws = jj_repo.add_workspace("feature");- jj_repo.commit_in(&ws, "feature.txt", "feature content", "Add feature");- jj_repo-}--/// Repo with two feature workspaces.-#[fixture]-fn jj_repo_with_two_features(mut jj_repo: JjTestRepo) -> JjTestRepo {- let ws_a = jj_repo.add_workspace("feature-a");- jj_repo.commit_in(&ws_a, "a.txt", "content a", "Add feature A");- let ws_b = jj_repo.add_workspace("feature-b");- jj_repo.commit_in(&ws_b, "b.txt", "content b", "Add feature B");- jj_repo-}--// ============================================================================-// wt list tests-// ============================================================================--#[rstest]-fn test_jj_list_single_workspace(jj_repo: JjTestRepo) {- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--#[rstest]-fn test_jj_list_multiple_workspaces(jj_repo_with_two_features: JjTestRepo) {- let repo = jj_repo_with_two_features;- assert_cmd_snapshot!(make_jj_snapshot_cmd(&repo, "list", &[], None));-}--#[rstest]-fn test_jj_list_from_feature_workspace(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- assert_cmd_snapshot!(make_jj_snapshot_cmd(&repo, "list", &[], Some(feature_path)));-}--#[rstest]-fn test_jj_list_dirty_workspace(mut jj_repo: JjTestRepo) {- // Add workspace and write a file without committing (jj auto-snapshots)- let ws = jj_repo.add_workspace("dirty");- std::fs::write(ws.join("uncommitted.txt"), "dirty content").unwrap();- // jj auto-snapshots on next command, so the workspace will show as dirty- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--#[rstest]-fn test_jj_list_workspace_with_no_user_commits(mut jj_repo: JjTestRepo) {- // A newly created workspace has no user commits — only the jj workspace- // creation commits (new empty @ on top of trunk). This shows as "ahead"- // due to jj's workspace mechanics, even though no real work has been done.- jj_repo.add_workspace("integrated");- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--// ============================================================================-// wt switch tests-// ============================================================================--#[rstest]-fn test_jj_switch_to_existing_workspace(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- // Switch from default to feature workspace- assert_cmd_snapshot!(make_jj_snapshot_cmd(&repo, "switch", &["feature"], None));-}--#[rstest]-fn test_jj_switch_to_existing_with_directive_file(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let (directive_path, _guard) = directive_file();- assert_cmd_snapshot!({- let mut cmd = make_jj_snapshot_cmd(&repo, "switch", &["feature"], None);- configure_directive_file(&mut cmd, &directive_path);- cmd- });-}--#[rstest]-fn test_jj_switch_create_new_workspace(jj_repo: JjTestRepo) {- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["--create", "new-feature"],- None- ));-}--#[rstest]-fn test_jj_switch_create_with_directive_file(jj_repo: JjTestRepo) {- let (directive_path, _guard) = directive_file();- assert_cmd_snapshot!({- let mut cmd = make_jj_snapshot_cmd(&jj_repo, "switch", &["--create", "new-ws"], None);- configure_directive_file(&mut cmd, &directive_path);- cmd- });-}--#[rstest]-fn test_jj_switch_nonexistent_workspace(jj_repo: JjTestRepo) {- // Without --create, should fail with helpful error- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["nonexistent"],- None- ));-}--#[rstest]-fn test_jj_switch_already_at_workspace(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- // Switch to feature from within feature workspace — should be no-op- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "switch",- &["feature"],- Some(feature_path)- ));-}--// ============================================================================-// wt remove tests-// ============================================================================--#[rstest]-fn test_jj_remove_workspace(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- // Remove feature workspace from within it- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "remove",- &[],- Some(feature_path)- ));-}--#[rstest]-fn test_jj_remove_workspace_by_name(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- // Remove by name from default workspace- assert_cmd_snapshot!(make_jj_snapshot_cmd(&repo, "remove", &["feature"], None));-}--#[rstest]-fn test_jj_remove_default_fails(jj_repo: JjTestRepo) {- // Cannot remove default workspace- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "remove", &["default"], None));-}--#[rstest]-fn test_jj_remove_current_workspace_cds_to_default(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");-- let (directive_path, _guard) = directive_file();- assert_cmd_snapshot!({- let mut cmd = make_jj_snapshot_cmd(&repo, "remove", &[], Some(feature_path));- configure_directive_file(&mut cmd, &directive_path);- cmd- });-}--#[rstest]-fn test_jj_remove_already_on_default(jj_repo: JjTestRepo) {- // Try to remove when already on default (no workspace name given)- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "remove", &[], None));-}--// ============================================================================-// wt merge tests-// ============================================================================--#[rstest]-fn test_jj_merge_squash(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- // Merge feature into main (squash is default for jj)- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "merge",- &["main"],- Some(feature_path)- ));-}--#[rstest]-fn test_jj_merge_squash_with_directive_file(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- let (directive_path, _guard) = directive_file();- assert_cmd_snapshot!({- let mut cmd = make_jj_snapshot_cmd(&repo, "merge", &["main"], Some(feature_path));- configure_directive_file(&mut cmd, &directive_path);- cmd- });-}--#[rstest]-fn test_jj_merge_no_remove(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- // Merge but keep the workspace (--no-remove)- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "merge",- &["main", "--no-remove"],- Some(feature_path)- ));-}--#[rstest]-fn test_jj_merge_workspace_with_no_user_commits(mut jj_repo: JjTestRepo) {- // Workspace has only jj's workspace creation commits (no real work).- // Squash merge is a no-op in terms of content, but still cleans up.- let ws = jj_repo.add_workspace("integrated");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "merge",- &["main"],- Some(&ws)- ));-}--#[rstest]-fn test_jj_merge_from_default_fails(jj_repo: JjTestRepo) {- // Cannot merge the default workspace- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "merge", &["main"], None));-}--#[rstest]-fn test_jj_merge_multi_commit(mut jj_repo: JjTestRepo) {- // Feature with multiple commits- let ws = jj_repo.add_workspace("multi");- jj_repo.commit_in(&ws, "file1.txt", "content 1", "Add file 1");- jj_repo.commit_in(&ws, "file2.txt", "content 2", "Add file 2");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "merge",- &["main"],- Some(&ws)- ));-}--// ============================================================================-// Edge cases-// ============================================================================--#[rstest]-fn test_jj_switch_create_and_then_list(jj_repo: JjTestRepo) {- // Create a workspace via wt switch --create, then verify it appears in list- let mut cmd = jj_repo.wt_command();- cmd.args(["switch", "--create", "via-switch"]);- let output = cmd.output().unwrap();- assert!(- output.status.success(),- "wt switch --create failed:\nstdout: {}\nstderr: {}",- String::from_utf8_lossy(&output.stdout),- String::from_utf8_lossy(&output.stderr)- );-- // List should show the new workspace- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--#[rstest]-fn test_jj_multiple_operations(mut jj_repo: JjTestRepo) {- // Create workspace, commit, remove — full lifecycle- let ws = jj_repo.add_workspace("lifecycle");- jj_repo.commit_in(&ws, "life.txt", "content", "Lifecycle commit");-- // Verify it exists in list output- let output = jj_repo.wt_command().arg("list").output().unwrap();- assert!(output.status.success());- let stdout = String::from_utf8_lossy(&output.stdout);- assert!(- stdout.contains("lifecycle"),- "Expected 'lifecycle' in list output: {stdout}"- );-- // Merge it- let mut cmd = jj_repo.wt_command();- cmd.args(["merge", "main"]).current_dir(&ws);- let merge_output = cmd.output().unwrap();- assert!(- merge_output.status.success(),- "merge failed:\nstdout: {}\nstderr: {}",- String::from_utf8_lossy(&merge_output.stdout),- String::from_utf8_lossy(&merge_output.stderr)- );-}--#[rstest]-fn test_jj_remove_nonexistent_workspace(jj_repo: JjTestRepo) {- // Try to remove a workspace that doesn't exist- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "remove",- &["nonexistent"],- None- ));-}--#[rstest]-fn test_jj_switch_to_default(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- // Switch from feature back to default- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "switch",- &["default"],- Some(feature_path)- ));-}--#[rstest]-fn test_jj_list_after_remove(mut jj_repo: JjTestRepo) {- // Create a workspace, then remove it, then list- let ws = jj_repo.add_workspace("temp");- jj_repo.commit_in(&ws, "temp.txt", "content", "Temp commit");-- // Remove by name- let mut cmd = jj_repo.wt_command();- cmd.args(["remove", "temp"]);- let output = cmd.output().unwrap();- assert!(output.status.success());-- // List should only show default workspace- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--#[rstest]-fn test_jj_merge_with_no_squash(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- // Merge without squash (rebase mode)- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "merge",- &["main", "--no-squash"],- Some(feature_path)- ));-}--// ============================================================================-// wt step commit tests-// ============================================================================--#[rstest]-fn test_jj_step_commit_with_changes(jj_repo: JjTestRepo) {- // Write a file (jj auto-snapshots, so @ will have content)- std::fs::write(jj_repo.root_path().join("new.txt"), "content\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["commit"], None));-}--#[rstest]-fn test_jj_step_commit_nothing_to_commit(jj_repo: JjTestRepo) {- // @ is empty (fresh workspace), so step commit should fail- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["commit"], None));-}--#[rstest]-fn test_jj_step_commit_in_feature_workspace(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("feat");- std::fs::write(ws.join("feat.txt"), "feature content\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["commit"],- Some(&ws)- ));-}--#[rstest]-fn test_jj_step_commit_reuses_existing_description(jj_repo: JjTestRepo) {- // Write a file, then manually describe @ — step commit should reuse that description- std::fs::write(jj_repo.root_path().join("described.txt"), "content\n").unwrap();- run_jj_in(- jj_repo.root_path(),- &["describe", "-m", "My custom message"],- );-- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["commit"], None));-}--#[rstest]-fn test_jj_step_commit_multiple_files(jj_repo: JjTestRepo) {- // Write 4 files — should generate "Changes to 4 files"- for name in &["a.txt", "b.txt", "c.txt", "d.txt"] {- std::fs::write(jj_repo.root_path().join(name), "content\n").unwrap();- }- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["commit"], None));-}--#[rstest]-fn test_jj_step_commit_two_files(jj_repo: JjTestRepo) {- // 2 files — should generate "Changes to X & Y"- std::fs::write(jj_repo.root_path().join("alpha.txt"), "a\n").unwrap();- std::fs::write(jj_repo.root_path().join("beta.txt"), "b\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["commit"], None));-}--#[rstest]-fn test_jj_step_commit_three_files(jj_repo: JjTestRepo) {- // 3 files — should generate "Changes to X, Y & Z"- std::fs::write(jj_repo.root_path().join("alpha.txt"), "a\n").unwrap();- std::fs::write(jj_repo.root_path().join("beta.txt"), "b\n").unwrap();- std::fs::write(jj_repo.root_path().join("gamma.txt"), "c\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["commit"], None));-}--#[rstest]-fn test_jj_step_commit_show_prompt(jj_repo: JjTestRepo) {- // --show-prompt with no LLM configured- std::fs::write(jj_repo.root_path().join("prompt.txt"), "content\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["commit", "--show-prompt"],- None- ));-}--#[rstest]-fn test_jj_step_commit_with_llm(jj_repo: JjTestRepo) {- // Commit with a mock LLM command configured- let config = jj_repo.write_llm_config();- std::fs::write(jj_repo.root_path().join("llm.txt"), "content\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd_with_config(- &jj_repo,- "step",- &["commit"],- None,- &config- ));-}--#[rstest]-fn test_jj_step_commit_show_prompt_with_llm(jj_repo: JjTestRepo) {- // --show-prompt with LLM configured — should print the actual prompt- let config = jj_repo.write_llm_config();- std::fs::write(jj_repo.root_path().join("llm.txt"), "content\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd_with_config(- &jj_repo,- "step",- &["commit", "--show-prompt"],- None,- &config- ));-}--// ============================================================================-// wt step squash tests-// ============================================================================--#[rstest]-fn test_jj_step_squash_multiple_commits(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("squash-test");- jj_repo.commit_in(&ws, "a.txt", "content a", "First commit");- jj_repo.commit_in(&ws, "b.txt", "content b", "Second commit");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["squash"],- Some(&ws)- ));-}--#[rstest]-fn test_jj_step_squash_already_single_commit(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("single");- jj_repo.commit_in(&ws, "only.txt", "only content", "Only commit");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["squash"],- Some(&ws)- ));-}--#[rstest]-fn test_jj_step_squash_no_commits_ahead(jj_repo: JjTestRepo) {- // Default workspace with no feature commits — nothing to squash- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["squash"], None));-}--#[rstest]-fn test_jj_step_squash_already_integrated(mut jj_repo: JjTestRepo) {- // Feature that has already been squash-merged into trunk via wt merge- let ws = jj_repo.add_workspace("integrated");- jj_repo.commit_in(&ws, "i.txt", "content", "Feature commit");-- // Merge it into trunk first- let mut merge_cmd = jj_repo.wt_command();- configure_cli_command(&mut merge_cmd);- merge_cmd- .current_dir(&ws)- .args(["merge", "main", "--no-remove"]);- let merge_result = merge_cmd.output().unwrap();- assert!(- merge_result.status.success(),- "merge failed: {}",- String::from_utf8_lossy(&merge_result.stderr)- );-- // Now step squash should say "nothing to squash" (already integrated)- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["squash"],- Some(&ws)- ));-}--// ============================================================================-// wt step rebase tests-// ============================================================================--#[rstest]-fn test_jj_step_rebase_already_up_to_date(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("rebased");- jj_repo.commit_in(&ws, "r.txt", "content", "Feature commit");-- // Feature is already on trunk — should be up to date- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["rebase"],- Some(&ws)- ));-}--#[rstest]-fn test_jj_step_rebase_onto_advanced_trunk(mut jj_repo: JjTestRepo) {- // Create feature workspace- let ws = jj_repo.add_workspace("rebase-feat");- jj_repo.commit_in(&ws, "feat.txt", "feature", "Feature work");-- // Advance trunk in default workspace- std::fs::write(jj_repo.root_path().join("trunk.txt"), "trunk advance\n").unwrap();- run_jj_in(jj_repo.root_path(), &["describe", "-m", "Advance trunk"]);- run_jj_in(jj_repo.root_path(), &["new"]);- run_jj_in(- jj_repo.root_path(),- &["bookmark", "set", "main", "-r", "@-"],- );-- // Now rebase feature onto the advanced trunk- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["rebase"],- Some(&ws)- ));-}--// ============================================================================-// wt step push tests-// ============================================================================--#[rstest]-fn test_jj_step_push_no_remote(mut jj_repo: JjTestRepo) {- // Push without a remote — should complete (bookmark set) but push fails silently- let ws = jj_repo.add_workspace("push-test");- jj_repo.commit_in(&ws, "p.txt", "push content", "Push commit");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["push"], Some(&ws)));-}--#[rstest]-fn test_jj_step_push_nothing_to_push(jj_repo: JjTestRepo) {- // Default workspace — feature tip IS trunk, nothing to push- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["push"], None));-}--#[rstest]-fn test_jj_step_push_behind_trunk(mut jj_repo: JjTestRepo) {- // Create feature workspace with a commit- let ws = jj_repo.add_workspace("push-behind");- jj_repo.commit_in(&ws, "feat.txt", "feature", "Feature work");-- // Advance trunk past the feature (so feature is behind)- std::fs::write(jj_repo.root_path().join("trunk.txt"), "trunk advance\n").unwrap();- run_jj_in(jj_repo.root_path(), &["describe", "-m", "Advance trunk"]);- run_jj_in(jj_repo.root_path(), &["new"]);- run_jj_in(- jj_repo.root_path(),- &["bookmark", "set", "main", "-r", "@-"],- );-- // Advance trunk again so it's strictly ahead- std::fs::write(jj_repo.root_path().join("trunk2.txt"), "more trunk\n").unwrap();- run_jj_in(jj_repo.root_path(), &["describe", "-m", "More trunk"]);- run_jj_in(jj_repo.root_path(), &["new"]);- run_jj_in(- jj_repo.root_path(),- &["bookmark", "set", "main", "-r", "@-"],- );-- // Push from feature — should detect feature is not ahead and fail- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["push"], Some(&ws)));-}--// ============================================================================-// wt step squash edge cases-// ============================================================================--#[rstest]-fn test_jj_step_squash_single_commit_with_wc_content(mut jj_repo: JjTestRepo) {- // Feature workspace with one commit AND uncommitted content in working copy- let ws = jj_repo.add_workspace("squash-wc");- jj_repo.commit_in(&ws, "first.txt", "first", "First commit");-- // Add more content without committing (jj auto-snapshots into @)- std::fs::write(ws.join("extra.txt"), "uncommitted content\n").unwrap();-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["squash"],- Some(&ws)- ));-}--// ============================================================================-// wt step squash --show-prompt (jj routing)-// ============================================================================--#[rstest]-fn test_jj_step_squash_show_prompt(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("squash-prompt");- jj_repo.commit_in(&ws, "p.txt", "content", "Commit for prompt");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["squash", "--show-prompt"],- Some(&ws)- ));-}--// ============================================================================-// Multi-step workflow tests-// ============================================================================--// ============================================================================-// Coverage gap tests — exercising uncovered code paths-// ============================================================================--/// Clean workspace should report as not dirty (workspace/jj.rs `is_dirty` clean path).-#[rstest]-fn test_jj_list_clean_workspace(jj_repo: JjTestRepo) {- // Default workspace has an empty @ on top of trunk — is_dirty should return false- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--/// Switch to existing workspace without --cd should succeed silently-/// (handle_switch_jj.rs line 28: early return when change_dir is false).-#[rstest]-fn test_jj_switch_existing_no_cd(jj_repo_with_feature: JjTestRepo) {- let mut cmd = jj_repo_with_feature.wt_command();- cmd.args(["switch", "feature", "--no-cd"]);- let output = cmd.output().unwrap();- assert!(output.status.success());- // Should succeed without error, no directory change-}--/// Remove workspace by running `wt remove` from inside the workspace (no name arg)-/// (remove_command.rs: empty branches path resolves current workspace name).-#[rstest]-fn test_jj_remove_current_workspace_no_name(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("removeme");- jj_repo.commit_in(&ws, "x.txt", "x", "commit");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "remove", &[], Some(&ws)));-}--/// Switch --create with --base creates workspace at specific revision-/// (workspace/jj.rs create_workspace with base parameter, line 290).-#[rstest]-fn test_jj_switch_create_with_base(jj_repo: JjTestRepo) {- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["based-ws", "--create", "--base", "main"],- None,- ));-}--/// List workspace with committed changes (exercises branch_diff_stats and ahead/behind).-#[rstest]-fn test_jj_list_workspace_with_commits(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("with-commits");- jj_repo.commit_in(&ws, "a.txt", "a", "First change");- jj_repo.commit_in(&ws, "b.txt", "b", "Second change");-- // List from default workspace — feature workspace should show commits ahead- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "list", &[], None));-}--/// Switch --create when target path already exists should error-/// (handle_switch_jj.rs lines 50-54).-#[rstest]-fn test_jj_switch_create_path_exists(jj_repo: JjTestRepo) {- // Create the directory that would conflict- let conflict_dir = jj_repo.root_path().parent().unwrap().join("repo.conflict");- std::fs::create_dir_all(&conflict_dir).unwrap();-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["conflict", "--create"],- None,- ));-}--/// List workspaces in JSON format (covers handle_list_jj JSON output path).-#[rstest]-fn test_jj_list_json(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("json-test");- jj_repo.commit_in(&ws, "x.txt", "x content", "json test commit");-- let mut cmd = jj_repo.wt_command();- configure_cli_command(&mut cmd);- cmd.current_dir(jj_repo.root_path())- .args(["list", "--format=json"]);- let output = cmd.output().unwrap();- assert!(- output.status.success(),- "wt list --json failed: {}",- String::from_utf8_lossy(&output.stderr)- );-- let stdout = String::from_utf8_lossy(&output.stdout);- let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();- let arr = parsed.as_array().unwrap();- // At least 2 workspaces: default + json-test- assert!(- arr.len() >= 2,- "Expected at least 2 workspaces, got {}",- arr.len()- );- // Each item should have the 'kind' and 'branch' fields- for item in arr {- assert!(item.get("kind").is_some(), "Missing 'kind' field");- assert!(item.get("branch").is_some(), "Missing 'branch' field");- }-}--/// Exercise JjWorkspace Workspace trait methods that aren't called by jj code paths.-///-/// Several trait methods (`kind`, `default_branch_name`, `has_staging_area`, `is_dirty`,-/// `branch_diff_stats`) are required by the Workspace trait but not exercised by-/// the normal `wt list`/`wt merge`/`wt step` flows. This test calls them directly.-#[rstest]-fn test_jj_workspace_trait_methods(mut jj_repo: JjTestRepo) {- use worktrunk::workspace::{JjWorkspace, VcsKind, Workspace};-- let ws = JjWorkspace::new(jj_repo.root_path().to_path_buf());-- // kind- assert_eq!(ws.kind(), VcsKind::Jj);-- // has_staging_area — jj doesn't have one- assert!(!ws.has_staging_area());-- // default_branch_name — jj detects from trunk() revset bookmark- assert_eq!(ws.default_branch_name(), Some("main".to_string()));-- // set_default_branch — override the detected value- ws.set_default_branch("develop").unwrap();- assert_eq!(ws.default_branch_name(), Some("develop".to_string()));-- // clear_default_branch — reverts to trunk() detection- assert!(ws.clear_default_branch().unwrap());- assert_eq!(ws.default_branch_name(), Some("main".to_string()));-- // clear when already clear — returns false- assert!(!ws.clear_default_branch().unwrap());-- // is_dirty — clean workspace (empty @ on top of trunk)- assert!(!ws.is_dirty(jj_repo.root_path()).unwrap());-- // Make dirty: write a file in the working copy- std::fs::write(jj_repo.root_path().join("dirty.txt"), "dirty\n").unwrap();- assert!(ws.is_dirty(jj_repo.root_path()).unwrap());-- // branch_diff_stats — diff between trunk and a feature workspace- let feature_path = jj_repo.add_workspace("trait-test");- jj_repo.commit_in(&feature_path, "f.txt", "feature content", "feature commit");-- // Get the feature workspace's change ID for branch_diff_stats- let items = ws.list_workspaces().unwrap();- let feature_item = items.iter().find(|i| i.name == "trait-test").unwrap();- let diff = ws.branch_diff_stats("trunk()", &feature_item.head).unwrap();- assert!(diff.added > 0, "Expected added lines in branch diff stats");-- // feature_tip — returns a change ID for the workspace- let tip = ws.feature_tip(&feature_path).unwrap();- assert!(!tip.is_empty());-- // commit — describe and advance @ in the feature workspace- std::fs::write(feature_path.join("commit-test.txt"), "via trait\n").unwrap();- let change_id = ws.commit("trait commit message", &feature_path).unwrap();- assert!(!change_id.is_empty());-- // commit_subjects — check the commit we just made- let subjects = ws.commit_subjects("trunk()", &change_id).unwrap();- assert!(- subjects.iter().any(|s| s.contains("trait commit message")),- "Expected 'trait commit message' in subjects: {subjects:?}"- );-- // resolve_integration_target(None) — discovers trunk bookmark- let target = ws.resolve_integration_target(None).unwrap();- assert_eq!(target, "main");-- // resolve_integration_target(Some) — returns as-is- let target = ws.resolve_integration_target(Some("custom")).unwrap();- assert_eq!(target, "custom");-- // wt_logs_dir — returns .jj/wt-logs path- let logs_dir = ws.wt_logs_dir();- assert!(logs_dir.ends_with(".jj/wt-logs"));-- // project_identifier — returns directory name (no git remote in test fixture)- let id = ws.project_identifier().unwrap();- assert!(!id.is_empty());-- // set_switch_previous(None) — exercises the unset path- ws.set_switch_previous(Some("trait-test")).unwrap();- assert_eq!(ws.switch_previous(), Some("trait-test".to_string()));- ws.set_switch_previous(None).unwrap();- assert!(ws.switch_previous().is_none());-- // is_rebased_onto — feature should be rebased onto trunk- let rebased = ws.is_rebased_onto("trunk()", &feature_path).unwrap();- assert!(rebased);-}--/// Remove workspace whose directory was already deleted externally-/// (handle_remove_jj.rs: "already removed" warning path).-#[rstest]-fn test_jj_remove_already_deleted_directory(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("deleted");- jj_repo.commit_in(&ws, "d.txt", "d", "commit");-- // Delete the directory externally before running wt remove- std::fs::remove_dir_all(&ws).unwrap();-- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "remove", &["deleted"], None));-}--// ============================================================================-// wt step push tests (continued)-// ============================================================================--#[rstest]-fn test_jj_step_squash_then_push(mut jj_repo: JjTestRepo) {- // The primary workflow: commit -> squash -> push- let ws = jj_repo.add_workspace("sq-push");- jj_repo.commit_in(&ws, "a.txt", "a", "First");- jj_repo.commit_in(&ws, "b.txt", "b", "Second");-- // Squash- let mut squash_cmd = jj_repo.wt_command();- configure_cli_command(&mut squash_cmd);- squash_cmd.current_dir(&ws).args(["step", "squash"]);- let squash_result = squash_cmd.output().unwrap();- assert!(- squash_result.status.success(),- "squash failed: {}",- String::from_utf8_lossy(&squash_result.stderr)- );-- // Push should still work (not say "nothing to push")- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "step", &["push"], Some(&ws)));-}--// ============================================================================-// Coverage: switch-previous, merge edge cases, hook paths-// ============================================================================--/// Switch to previous workspace with `wt switch -`-/// (handle_switch_jj.rs lines 33-37, workspace/jj.rs switch_previous + set_switch_previous).-#[rstest]-fn test_jj_switch_previous(mut jj_repo: JjTestRepo) {- let _ws_a = jj_repo.add_workspace("alpha");-- // Set config with test HOME so `wt` (which uses test HOME) finds it.- // jj 0.38+ stores per-repo config in the user config dir, not in .jj/.- let home = jj_repo.home_path();- let output = Command::new("jj")- .args([- "--no-pager",- "--color",- "never",- "config",- "set",- "--repo",- "worktrunk.history",- "alpha",- ])- .current_dir(jj_repo.root_path())- .env("XDG_CONFIG_HOME", home.join(".config"))- .env("HOME", home)- .output()- .unwrap();- assert!(- output.status.success(),- "jj config set failed: {}",- String::from_utf8_lossy(&output.stderr)- );-- // `wt switch -` should resolve "-" to "alpha" and switch there- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "switch", &["-"], None));-}--/// Merge workspace whose commits result in no net changes (NoNetChanges path)-/// (handle_merge_jj.rs lines 82-84, step_commands.rs lines 174-180).-#[rstest]-fn test_jj_merge_no_net_changes(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("noop");-- // Add a file, then remove it — net effect is zero changes vs trunk- std::fs::write(ws.join("temp.txt"), "temporary content").unwrap();- run_jj_in(&ws, &["describe", "-m", "Add temp file"]);- run_jj_in(&ws, &["new"]);- std::fs::remove_file(ws.join("temp.txt")).unwrap();- run_jj_in(&ws, &["describe", "-m", "Remove temp file"]);- run_jj_in(&ws, &["new"]);-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "merge",- &["main"],- Some(&ws)- ));-}--/// Merge with --no-squash and --no-remove (rebase-only mode, workspace retained)-/// (handle_merge_jj.rs line 87-89: rebase_onto_trunk path).-#[rstest]-fn test_jj_merge_no_squash_no_remove(jj_repo_with_feature: JjTestRepo) {- let repo = jj_repo_with_feature;- let feature_path = repo.workspace_path("feature");- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &repo,- "merge",- &["main", "--no-squash", "--no-remove"],- Some(feature_path)- ));-}--/// Merge workspace that's at trunk (squash finds 0 commits ahead)-/// (handle_merge_jj.rs line 70: SquashResult::NoCommitsAhead match arm,-/// step_commands.rs lines 131-132: ahead==0 early return).-#[rstest]-fn test_jj_merge_zero_commits_ahead(mut jj_repo: JjTestRepo) {- // Create workspace and move it to exactly trunk (@ = main)- let ws = jj_repo.add_workspace("at-trunk");- // Abandon the auto-created empty commit so @ points to trunk- run_jj_in(&ws, &["edit", "@-"]);-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "merge",- &["main", "--no-remove"],- Some(&ws)- ));-}--/// Merge workspace at trunk with removal (NoCommitsAhead + remove_if_requested)-/// (handle_merge_jj.rs lines 69-77: NoCommitsAhead with workspace removal).-#[rstest]-fn test_jj_merge_zero_commits_ahead_with_remove(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("at-trunk2");- run_jj_in(&ws, &["edit", "@-"]);-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "merge",- &["main"],- Some(&ws)- ));-}--/// Merge no-net-changes workspace with removal (NoNetChanges + remove)-/// (handle_merge_jj.rs line 82-84: NoNetChanges with workspace removal).-#[rstest]-fn test_jj_merge_no_net_changes_with_remove(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("noop2");- std::fs::write(ws.join("temp.txt"), "temporary content").unwrap();- run_jj_in(&ws, &["describe", "-m", "Add temp file"]);- run_jj_in(&ws, &["new"]);- std::fs::remove_file(ws.join("temp.txt")).unwrap();- run_jj_in(&ws, &["describe", "-m", "Remove temp file"]);- run_jj_in(&ws, &["new"]);-- // Without --no-remove, workspace should be removed- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "merge",- &["main"],- Some(&ws)- ));-}--/// Switch records previous workspace for `wt switch -`-/// (handle_switch_jj.rs line 79: record_switch_previous).-#[rstest]-fn test_jj_switch_records_previous(mut jj_repo: JjTestRepo) {- let _ws_a = jj_repo.add_workspace("bravo");-- // Switch to bravo — should record "default" as previous- let mut switch_cmd = jj_repo.wt_command();- configure_cli_command(&mut switch_cmd);- switch_cmd- .current_dir(jj_repo.root_path())- .args(["switch", "bravo"]);- let result = switch_cmd.output().unwrap();- assert!(- result.status.success(),- "switch to bravo failed: {}",- String::from_utf8_lossy(&result.stderr)- );-- // Now `wt switch -` from bravo should switch back to default- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["-"],- Some(jj_repo.workspace_path("bravo"))- ));-}--/// Switch to default from default (exercises is_default path)-/// (handle_switch_jj.rs line 45: existing_path found + already at workspace).-#[rstest]-fn test_jj_switch_default_from_default(jj_repo: JjTestRepo) {- assert_cmd_snapshot!(make_jj_snapshot_cmd(&jj_repo, "switch", &["default"], None));-}--/// Merge with implicit target (no argument) — exercises trunk_bookmark() resolution-/// (workspace/jj.rs resolve_integration_target(None) → trunk_bookmark()).-#[rstest]-fn test_jj_merge_implicit_target(jj_repo_with_feature: JjTestRepo) {- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo_with_feature,- "merge",- &[],- Some(jj_repo_with_feature.workspace_path("feature"))- ));-}--/// Step commit with empty description (no existing description, generates from files)-/// (handle_step_jj.rs generate_jj_commit_message fallback path).-#[rstest]-fn test_jj_step_commit_empty_description(mut jj_repo: JjTestRepo) {- let ws = jj_repo.add_workspace("empty-desc");- // Create a new empty change, then write a file (no existing description)- run_jj_in(&ws, &["new"]);- std::fs::write(ws.join("gen.txt"), "generated msg test\n").unwrap();- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["commit"],- Some(&ws)- ));-}--// ============================================================================-// Hook and execute coverage tests-// ============================================================================--/// Switch --create with project hooks and --yes exercises approve_hooks,-/// post-create blocking hooks, and background post-switch/post-start hooks-/// (handle_switch_jj.rs lines 148-167, 183-186, 211-226).-#[rstest]-fn test_jj_switch_create_with_hooks(jj_repo: JjTestRepo) {- // Write project config with hooks- jj_repo.write_project_config(- r#"post-create = "echo post-create-ran"-post-switch = "echo post-switch-ran"-post-start = "echo post-start-ran"-"#,- );-- // --yes auto-approves hooks- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["--create", "hooked", "--yes"],- None,- ));-}--/// Switch to existing workspace with hooks exercises the existing-switch hook path-/// (handle_switch_jj.rs lines 67-76, 100-112: approve + background for existing switch).-#[rstest]-fn test_jj_switch_existing_with_hooks(mut jj_repo: JjTestRepo) {- let _ws = jj_repo.add_workspace("hookable");-- // Write project config with post-switch hook- jj_repo.write_project_config(r#"post-switch = "echo switched-hook""#);-- // Switch to existing workspace with hooks- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["hookable", "--yes"],- None,- ));-}--/// Switch --create with --execute exercises the execute path-/// (handle_switch_jj.rs lines 229-238: expand_and_execute_command).-#[rstest]-fn test_jj_switch_create_with_execute(jj_repo: JjTestRepo) {- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["--create", "exec-ws", "--execute", "echo hello"],- None,- ));-}--/// Switch to existing workspace with --execute exercises the execute path-/// (handle_switch_jj.rs lines 115-123: expand_and_execute_command for existing).-#[rstest]-fn test_jj_switch_existing_with_execute(mut jj_repo: JjTestRepo) {- let _ws = jj_repo.add_workspace("exec-target");- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "switch",- &["exec-target", "--execute", "echo switched"],- None,- ));-}--// ============================================================================-// step copy-ignored-// ============================================================================--/// Copy ignored files between jj workspaces — basic case.-#[rstest]-fn test_jj_copy_ignored_basic(mut jj_repo: JjTestRepo) {- // Create .gitignore and an ignored file in default workspace- std::fs::write(jj_repo.root_path().join(".gitignore"), "target/\n").unwrap();- std::fs::create_dir_all(jj_repo.root_path().join("target")).unwrap();- std::fs::write(jj_repo.root_path().join("target/debug.o"), "binary content").unwrap();- run_jj_in(jj_repo.root_path(), &["describe", "-m", "add gitignore"]);- run_jj_in(jj_repo.root_path(), &["new"]);-- // Create a feature workspace- let feature_path = jj_repo.add_workspace("feature");-- // Copy from default to feature- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["copy-ignored", "--to", "feature"],- None,- ));-- // Verify file was copied- assert!(- feature_path.join("target/debug.o").exists(),- "Ignored file should be copied to feature workspace"- );-}--/// Copy ignored files with --from flag (copy from feature to default).-#[rstest]-fn test_jj_copy_ignored_from_feature(mut jj_repo: JjTestRepo) {- // Set up gitignore- std::fs::write(jj_repo.root_path().join(".gitignore"), "build/\n").unwrap();- run_jj_in(jj_repo.root_path(), &["describe", "-m", "add gitignore"]);- run_jj_in(jj_repo.root_path(), &["new"]);-- // Create feature workspace with an ignored file- let feature_path = jj_repo.add_workspace("feature");- std::fs::create_dir_all(feature_path.join("build")).unwrap();- std::fs::write(feature_path.join("build/app"), "binary").unwrap();-- // Copy from feature to default- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["copy-ignored", "--from", "feature"],- None,- ));-- // Verify file was copied to default workspace- assert!(- jj_repo.root_path().join("build/app").exists(),- "Ignored file should be copied from feature to default workspace"- );-}--/// Dry run shows what would be copied without actually copying.-#[rstest]-fn test_jj_copy_ignored_dry_run(mut jj_repo: JjTestRepo) {- std::fs::write(jj_repo.root_path().join(".gitignore"), "target/\n").unwrap();- std::fs::create_dir_all(jj_repo.root_path().join("target")).unwrap();- std::fs::write(jj_repo.root_path().join("target/app"), "bin").unwrap();- run_jj_in(jj_repo.root_path(), &["describe", "-m", "add gitignore"]);- run_jj_in(jj_repo.root_path(), &["new"]);-- let feature_path = jj_repo.add_workspace("feature");-- assert_cmd_snapshot!(make_jj_snapshot_cmd(- &jj_repo,- "step",- &["copy-ignored", "--to", "feature", "--dry-run"],- None,- ));-- // Verify nothing was actually copied- assert!(- !feature_path.join("target").exists(),- "Dry run should not copy files"- );-}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 0e8f0bf7d..9c3992574 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -33,7 +33,6 @@ pub mod git_error_display;pub mod help;pub mod hook_show;pub mod init;-pub mod jj;pub mod list;pub mod list_column_alignment;pub mod list_config;diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rsindex 49f607319..e931f2a52 100644--- a/tests/integration_tests/output_system_guard.rs+++ b/tests/integration_tests/output_system_guard.rs@@ -36,8 +36,6 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &["config/hints.rs",// LLM prompt output for wt step commit --show-prompt"step_commands.rs",- // LLM prompt output for jj step commit --show-prompt- "handle_step_jj.rs",];/// Substrings that indicate the line is a special case (e.g., in a comment or test reference)diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_outside_git_repo.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_outside_git_repo.snapindex bc1c8f41f..e6a618257 100644--- a/tests/snapshots/integration__integration_tests__config_show__config_show_outside_git_repo.snap+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_outside_git_repo.snap@@ -36,7 +36,7 @@ exit_code: 0[36mUSER CONFIG[39m ~/.config/worktrunk/config.toml[107m [0m worktree-path = [32m"../{{ repo }}.{{ branch }}"-[2m[36mPROJECT CONFIG[39m Not in a repository[22m+[2m[36mPROJECT CONFIG[39m Not in a git repository[22m[36mSHELL INTEGRATION[39m[33m▲[39m [33mShell integration not active[39mdiff --git a/tests/snapshots/integration__integration_tests__hook_show__error_with_context_formatting.snap b/tests/snapshots/integration__integration_tests__hook_show__error_with_context_formatting.snapindex af62aab60..1259d3e4b 100644--- a/tests/snapshots/integration__integration_tests__hook_show__error_with_context_formatting.snap+++ b/tests/snapshots/integration__integration_tests__hook_show__error_with_context_formatting.snap@@ -30,4 +30,5 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mNot in a repository[39m+[31m✗[39m [31mFailed to remove worktree[39m+[107m [0m fatal: not a git repository (or any of the parent directories): .gitdiff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snapindex cd183b60d..2493b594f 100644--- a/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snap+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_outside_git_repo.snap@@ -31,4 +31,4 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mNot in a repository[39m+[31m✗[39m [31mfatal: not a git repository (or any of the parent directories): .git[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_basic.snap b/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_basic.snapdeleted file mode 100644index 76a9a65d6..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_basic.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - copy-ignored- - "--to"- - feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mCopied 1 entry[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_dry_run.snap b/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_dry_run.snapdeleted file mode 100644index 5e28351dd..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_dry_run.snap+++ /dev/null@@ -1,38 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - copy-ignored- - "--to"- - feature- - "--dry-run"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[2m○[22m Would copy 1 entry:-[107m [0m target (dir)diff --git a/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_from_feature.snap b/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_from_feature.snapdeleted file mode 100644index 138014eca..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_copy_ignored_from_feature.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - copy-ignored- - "--from"- - feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mCopied 1 entry[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_after_remove.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_after_remove.snapdeleted file mode 100644index cbedce176..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_after_remove.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 1 [CHANGE_ID_SHORT], 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_clean_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_clean_workspace.snapdeleted file mode 100644index cbedce176..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_clean_workspace.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 1 [CHANGE_ID_SHORT], 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_dirty_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_dirty_workspace.snapdeleted file mode 100644index 96b75c4e7..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_dirty_workspace.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-+ dirty [2m↑[22m [32m+1[0m [32m↑2[0m ../repo.dirty [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 2 worktrees, 1 ahead, 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_from_feature_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_from_feature_workspace.snapdeleted file mode 100644index 83e9c272c..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_from_feature_workspace.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ feature [2m↑[22m [32m↑3[0m ../repo.feature [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-^ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 2 worktrees, 1 ahead, 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_multiple_workspaces.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_multiple_workspaces.snapdeleted file mode 100644index 4f610e2d9..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_multiple_workspaces.snap+++ /dev/null@@ -1,37 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-+ feature-a [2m↑[22m [32m↑3[0m ../repo.feature-a [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-+ feature-b [2m↑[22m [32m↑3[0m ../repo.feature-b [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 3 worktrees, 2 ahead, 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_single_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_single_workspace.snapdeleted file mode 100644index cbedce176..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_single_workspace.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 1 [CHANGE_ID_SHORT], 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_workspace_with_commits.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_workspace_with_commits.snapdeleted file mode 100644index d6cb9651e..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_workspace_with_commits.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-+ with-commits [2m↑[22m [32m↑4[0m ../repo.with-commits [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 2 worktrees, 1 ahead, 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_list_workspace_with_no_user_commits.snap b/tests/snapshots/integration__integration_tests__jj__jj_list_workspace_with_no_user_commits.snapdeleted file mode 100644index c0c77901a..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_list_workspace_with_no_user_commits.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-+ integrated [2m↑[22m [32m↑2[0m ../repo.integrated [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 2 worktrees, 1 ahead, 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_from_default_fails.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_from_default_fails.snapdeleted file mode 100644index a36e06a53..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_from_default_fails.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mCannot merge the default workspace[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_implicit_target.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_implicit_target.snapdeleted file mode 100644index f8a933192..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_implicit_target.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSquashed workspace [1mfeature[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_multi_commit.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_multi_commit.snapdeleted file mode 100644index b78d5833b..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_multi_commit.snap+++ /dev/null@@ -1,43 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[36m◎[39m [36mGenerating squash commit message...[39m-[2m↳[22m [2mUsing [CHANGE_ID_SHORT] commit message. For LLM setup guide, run [90mwt config --help[39m[22m-[107m [0m [1mSquash commits from main[22m-[107m [0m-[107m [0m Combined commits:-[107m [0m - Add file 1-[107m [0m - Add file 2-[32m✓[39m [32mSquashed @ [2m[CHANGE_ID][22m[39m-[32m✓[39m [32mSquashed workspace [1mmulti[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mmulti[22m @ [1m_REPO_.multi[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_net_changes.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_no_net_changes.snapdeleted file mode 100644index fd13c9fab..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_net_changes.snap+++ /dev/null@@ -1,43 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[36m◎[39m [36mGenerating squash commit message...[39m-[2m↳[22m [2mUsing [CHANGE_ID_SHORT] commit message. For LLM setup guide, run [90mwt config --help[39m[22m-[107m [0m [1mSquash commits from main[22m-[107m [0m-[107m [0m Combined commits:-[107m [0m - Add temp file-[107m [0m - Remove temp file-[32m✓[39m [32mSquashed @ [2m[CHANGE_ID][22m[39m-[32m✓[39m [32mSquashed workspace [1mnoop[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mnoop[22m @ [1m_REPO_.noop[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_net_changes_with_remove.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_no_net_changes_with_remove.snapdeleted file mode 100644index 63a4d6e84..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_net_changes_with_remove.snap+++ /dev/null@@ -1,43 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[36m◎[39m [36mGenerating squash commit message...[39m-[2m↳[22m [2mUsing [CHANGE_ID_SHORT] commit message. For LLM setup guide, run [90mwt config --help[39m[22m-[107m [0m [1mSquash commits from main[22m-[107m [0m-[107m [0m Combined commits:-[107m [0m - Add temp file-[107m [0m - Remove temp file-[32m✓[39m [32mSquashed @ [2m[CHANGE_ID][22m[39m-[32m✓[39m [32mSquashed workspace [1mnoop2[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mnoop2[22m @ [1m_REPO_.noop2[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_remove.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_no_remove.snapdeleted file mode 100644index b8b998d85..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_remove.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- - "--no-remove"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mSquashed workspace [1mfeature[22m into [1mmain[22m[39m-[2m○[22m Workspace preserved (--no-remove)diff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_squash_no_remove.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_no_squash_no_remove.snapdeleted file mode 100644index e64d1976e..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_no_squash_no_remove.snap+++ /dev/null@@ -1,37 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- - "--no-squash"- - "--no-remove"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mMerged workspace [1mfeature[22m into [1mmain[22m[39m-[2m○[22m Workspace preserved (--no-remove)diff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_squash.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_squash.snapdeleted file mode 100644index abec55ea9..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_squash.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mSquashed workspace [1mfeature[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_squash_with_directive_file.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_squash_with_directive_file.snapdeleted file mode 100644index 0e2ce6111..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_squash_with_directive_file.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mSquashed workspace [1mfeature[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_with_no_squash.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_with_no_squash.snapdeleted file mode 100644index 12130026c..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_with_no_squash.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- - "--no-squash"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mMerged workspace [1mfeature[22m into [1mmain[22m[39m-[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_workspace_with_no_user_commits.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_workspace_with_no_user_commits.snapdeleted file mode 100644index ee84efc10..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_workspace_with_no_user_commits.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[2m○[22m Workspace [1mintegrated[22m is already integrated into trunk-[32m✓[39m [32mRemoved workspace [1mintegrated[22m @ [1m_REPO_.integrated[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_zero_commits_ahead.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_zero_commits_ahead.snapdeleted file mode 100644index 31b97efc0..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_zero_commits_ahead.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- - "--no-remove"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[2m○[22m Workspace [1mat-trunk[22m is already integrated into trunk-[2m○[22m Workspace preserved (--no-remove)diff --git a/tests/snapshots/integration__integration_tests__jj__jj_merge_zero_commits_ahead_with_remove.snap b/tests/snapshots/integration__integration_tests__jj__jj_merge_zero_commits_ahead_with_remove.snapdeleted file mode 100644index 596a4ee84..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_merge_zero_commits_ahead_with_remove.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - merge- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[2m○[22m Workspace [1mat-trunk2[22m is already integrated into trunk-[32m✓[39m [32mRemoved workspace [1mat-trunk2[22m @ [1m_REPO_.at-trunk2[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_already_deleted_directory.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_already_deleted_directory.snapdeleted file mode 100644index ce6d5ea7a..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_already_deleted_directory.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-assertion_line: 992-info:- program: wt- args:- - remove- - deleted- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[33m▲[39m [33mWorkspace directory already removed: [1m_REPO_.deleted[22m[39m-[32m✓[39m [32mRemoved workspace [1mdeleted[22m @ [1m_REPO_.deleted[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_already_on_default.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_already_on_default.snapdeleted file mode 100644index 932918f39..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_already_on_default.snap+++ /dev/null@@ -1,33 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mCannot remove the default workspace[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_current_workspace_cds_to_default.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_current_workspace_cds_to_default.snapdeleted file mode 100644index ed2fd0543..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_current_workspace_cds_to_default.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_current_workspace_no_name.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_current_workspace_no_name.snapdeleted file mode 100644index 6ddd51e2b..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_current_workspace_no_name.snap+++ /dev/null@@ -1,33 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mRemoved workspace [1mremoveme[22m @ [1m_REPO_.[CHANGE_ID_SHORT][22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_default_fails.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_default_fails.snapdeleted file mode 100644index 78d72e0de..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_default_fails.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- - default- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mCannot remove the default workspace[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_nonexistent_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_nonexistent_workspace.snapdeleted file mode 100644index 7e0a2ce09..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_nonexistent_workspace.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- - nonexistent- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mError: No such workspace: nonexistent[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_workspace.snapdeleted file mode 100644index 624e42683..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_workspace.snap+++ /dev/null@@ -1,33 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_remove_workspace_by_name.snap b/tests/snapshots/integration__integration_tests__jj__jj_remove_workspace_by_name.snapdeleted file mode 100644index 2d1f9f805..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_remove_workspace_by_name.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - remove- - feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mRemoved workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_empty_description.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_empty_description.snapdeleted file mode 100644index 9922c7b00..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_empty_description.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mCommitted: [2mChanges to gen.txt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_in_feature_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_in_feature_workspace.snapdeleted file mode 100644index a827a1630..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_in_feature_workspace.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mChanges to feat.txt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_multiple_files.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_multiple_files.snapdeleted file mode 100644index af93975dc..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_multiple_files.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mChanges to 4 files[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_nothing_to_commit.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_nothing_to_commit.snapdeleted file mode 100644index 76357c48c..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_nothing_to_commit.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mNothing to commit (working copy is empty)[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_reuses_existing_description.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_reuses_existing_description.snapdeleted file mode 100644index 9252f16af..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_reuses_existing_description.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mMy custom message[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_show_prompt.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_show_prompt.snapdeleted file mode 100644index dcc9d5d45..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_show_prompt.snap+++ /dev/null@@ -1,66 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- - "--show-prompt"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------Write a commit message for the staged changes below.--<format>-- Subject line under 50 chars-- For [CHANGE_ID_SHORT] changes, add a blank line then a body paragraph explaining the change-- Output only the commit message, no quotes or code blocks-</format>--<style>-- Imperative mood: "Add feature" not "Added feature"-- Match recent commit style ([CHANGE_ID] commits if used)-- Describe the change, not the intent or benefit-</style>--<[CHANGE_ID_SHORT]>-prompt.txt | 1 +-1 file changed, 1 insertion(+), 0 deletions(-)--</[CHANGE_ID_SHORT]>--<diff>-Added regular file prompt.txt:- 1: content--</diff>--<context>-Branch: default-<recent_commits>-- Initial commit-</recent_commits>-</context>------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_show_prompt_with_llm.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_show_prompt_with_llm.snapdeleted file mode 100644index c484985e7..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_show_prompt_with_llm.snap+++ /dev/null@@ -1,66 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- - "--show-prompt"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------Write a commit message for the staged changes below.--<format>-- Subject line under 50 chars-- For [CHANGE_ID_SHORT] changes, add a blank line then a body paragraph explaining the change-- Output only the commit message, no quotes or code blocks-</format>--<style>-- Imperative mood: "Add feature" not "Added feature"-- Match recent commit style ([CHANGE_ID] commits if used)-- Describe the change, not the intent or benefit-</style>--<[CHANGE_ID_SHORT]>-llm.txt | 1 +-1 file changed, 1 insertion(+), 0 deletions(-)--</[CHANGE_ID_SHORT]>--<diff>-Added regular file llm.txt:- 1: content--</diff>--<context>-Branch: default-<recent_commits>-- Initial commit-</recent_commits>-</context>------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_three_files.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_three_files.snapdeleted file mode 100644index 2c177a917..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_three_files.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mChanges to alpha.txt, beta.txt & gamma.txt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_two_files.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_two_files.snapdeleted file mode 100644index 33945586a..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_two_files.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mChanges to alpha.txt & beta.txt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_with_changes.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_with_changes.snapdeleted file mode 100644index 8b1dcad51..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_with_changes.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mChanges to new.txt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_with_llm.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_commit_with_llm.snapdeleted file mode 100644index 00e797700..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_commit_with_llm.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - commit- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCommitted: [2mLLM-generated-message[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_push_behind_trunk.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_push_behind_trunk.snapdeleted file mode 100644index 4a8d4d34b..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_push_behind_trunk.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - push- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mFailed to push[39m-[107m [0m Cannot push: feature is not ahead of main. Rebase first with `wt step rebase`.diff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_push_no_remote.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_push_no_remote.snapdeleted file mode 100644index f7d6d8e0f..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_push_no_remote.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - push- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mPushed to [1mmain[22m [90m(1 commit[39m[90m)[39m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_push_nothing_to_push.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_push_nothing_to_push.snapdeleted file mode 100644index 7fe920fc6..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_push_nothing_to_push.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - push- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[2m○[22m Already up to date with [1mmain[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_rebase_already_up_to_date.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_rebase_already_up_to_date.snapdeleted file mode 100644index 2968cbb6a..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_rebase_already_up_to_date.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - rebase- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[2m○[22m Already up to date with [1mmain[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_rebase_onto_advanced_trunk.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_rebase_onto_advanced_trunk.snapdeleted file mode 100644index a8f71557c..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_rebase_onto_advanced_trunk.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - rebase- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[36m◎[39m [36mRebasing onto [1mmain[22m...[39m-[32m✓[39m [32mRebased onto [1mmain[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_already_integrated.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_already_integrated.snapdeleted file mode 100644index 55b875536..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_already_integrated.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - squash- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[2m○[22m Nothing to squash; already a single commitdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_already_single_commit.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_already_single_commit.snapdeleted file mode 100644index c7b49f9f1..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_already_single_commit.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - squash- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[2m○[22m Nothing to squash; already a single commitdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_multiple_commits.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_multiple_commits.snapdeleted file mode 100644index b83b59681..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_multiple_commits.snap+++ /dev/null@@ -1,41 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - squash- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[36m◎[39m [36mGenerating squash commit message...[39m-[2m↳[22m [2mUsing [CHANGE_ID_SHORT] commit message. For LLM setup guide, run [90mwt config --help[39m[22m-[107m [0m [1mSquash commits from main[22m-[107m [0m-[107m [0m Combined commits:-[107m [0m - First commit-[107m [0m - Second commit-[32m✓[39m [32mSquashed @ [2m[CHANGE_ID][22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_no_commits_ahead.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_no_commits_ahead.snapdeleted file mode 100644index 84053f034..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_no_commits_ahead.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - squash- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[2m○[22m Nothing to squash; no commits ahead of maindiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_show_prompt.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_show_prompt.snapdeleted file mode 100644index 30cc3f1a4..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_show_prompt.snap+++ /dev/null@@ -1,63 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - squash- - "--show-prompt"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------Combine these commits into a single commit message.--<format>-- Subject line under 50 chars-- For [CHANGE_ID_SHORT] changes, add a blank line then a body paragraph explaining the change-- Output only the commit message, no quotes or code blocks-</format>--<style>-- Imperative mood: "Add feature" not "Added feature"-- Match the style of commits being [CHANGE_ID_SHORT] ([CHANGE_ID] commits if used)-- Describe the change, not the intent or benefit-</style>--<commits branch="squash-prompt" target="main">-- Commit for prompt-</commits>--<[CHANGE_ID_SHORT]>-p.txt | 1 +-1 file changed, 1 insertion(+), 0 deletions(-)--</[CHANGE_ID_SHORT]>--<diff>-Added regular file p.txt:- 1: content--</diff>------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_single_commit_with_wc_content.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_single_commit_with_wc_content.snapdeleted file mode 100644index eeb501993..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_single_commit_with_wc_content.snap+++ /dev/null@@ -1,40 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - squash- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[36m◎[39m [36mGenerating squash commit message...[39m-[2m↳[22m [2mUsing [CHANGE_ID_SHORT] commit message. For LLM setup guide, run [90mwt config --help[39m[22m-[107m [0m [1mSquash commits from main[22m-[107m [0m-[107m [0m Combined commits:-[107m [0m - First commit-[32m✓[39m [32mSquashed @ [2m[CHANGE_ID][22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_then_push.snap b/tests/snapshots/integration__integration_tests__jj__jj_step_squash_then_push.snapdeleted file mode 100644index 7fe920fc6..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_step_squash_then_push.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - step- - push- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[2m○[22m Already up to date with [1mmain[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_already_at_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_already_at_workspace.snapdeleted file mode 100644index 13c4df772..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_already_at_workspace.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_and_then_list.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_and_then_list.snapdeleted file mode 100644index d46a41b31..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_and_then_list.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - list- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage-@ default [2m^[22m . [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-+ via-switch [2m↑[22m [32m↑2[0m ../repo.via-switch [2m[CHANGE_ID_SHORT][0m [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 2 worktrees, 1 ahead, 1 column hidden------- stderr -----diff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_new_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_new_workspace.snapdeleted file mode 100644index c899fec1b..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_new_workspace.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - "--create"- - new-feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mCreated workspace [1mnew-feature[22m @ [1m_REPO_.new-feature[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_path_exists.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_path_exists.snapdeleted file mode 100644index 7b6a38979..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_path_exists.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - conflict- - "--create"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mPath already exists: _REPO_.[CHANGE_ID_SHORT][39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_base.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_base.snapdeleted file mode 100644index 763c5df5a..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_base.snap+++ /dev/null@@ -1,38 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - based-ws- - "--create"- - "--base"- - main- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mCreated workspace [1mbased-ws[22m @ [1m_REPO_.based-ws[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_directive_file.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_directive_file.snapdeleted file mode 100644index c345c897d..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_directive_file.snap+++ /dev/null@@ -1,36 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - "--create"- - new-ws- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mCreated workspace [1mnew-ws[22m @ [1m_REPO_.new-ws[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_execute.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_execute.snapdeleted file mode 100644index 805abfae9..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_execute.snap+++ /dev/null@@ -1,41 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - "--create"- - exec-ws- - "--execute"- - echo hello- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------hello------- stderr ------[32m✓[39m [32mCreated workspace [1mexec-ws[22m @ [1m_REPO_.exec-ws[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[36m◎[39m [36mExecuting (--execute) @ [1m_REPO_.exec-ws[22m:[39m-[107m [0m [2m[0m[2m[34mecho[0m[2m hellodiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_hooks.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_hooks.snapdeleted file mode 100644index 1b6b7b279..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_create_with_hooks.snap+++ /dev/null@@ -1,41 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - "--create"- - hooked- - "--yes"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[36m◎[39m [36mRunning post-create project hook @ [1m_REPO_.hooked[22m[39m-[107m [0m [2m[0m[2m[34mecho[0m[2m post-create-ran-[0mpost-create-ran-[32m✓[39m [32mCreated workspace [1mhooked[22m @ [1m_REPO_.hooked[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[36m◎[39m [36mRunning post-switch: [1mproject[22m; post-start: [1mproject[22m @ [1m_REPO_.hooked[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_default_from_default.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_default_from_default.snapdeleted file mode 100644index 436678d36..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_default_from_default.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - default- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mdefault[22m @ [1m_REPO_[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_existing_with_execute.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_existing_with_execute.snapdeleted file mode 100644index c500b571e..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_existing_with_execute.snap+++ /dev/null@@ -1,40 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - exec-target- - "--execute"- - echo switched- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------[CHANGE_ID_SHORT]------- stderr ------[32m✓[39m [32mSwitched to workspace [1mexec-target[22m @ [1m_REPO_.exec-target[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[36m◎[39m [36mExecuting (--execute) @ [1m_REPO_.exec-target[22m:[39m-[107m [0m [2m[0m[2m[34mecho[0m[2m [CHANGE_ID_SHORT]diff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_existing_with_hooks.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_existing_with_hooks.snapdeleted file mode 100644index 1461eaa9a..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_existing_with_hooks.snap+++ /dev/null@@ -1,37 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - hookable- - "--yes"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mhookable[22m @ [1m_REPO_.[CHANGE_ID_SHORT][22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m-[36m◎[39m [36mRunning post-switch: [1mproject[22m @ [1m_REPO_.[CHANGE_ID_SHORT][22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_nonexistent_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_nonexistent_workspace.snapdeleted file mode 100644index c833443ca..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_nonexistent_workspace.snap+++ /dev/null@@ -1,34 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - nonexistent- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- WT_TEST_DELAYED_STREAM_MS: "-1"- WT_TEST_EPOCH: "1735776000"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: false-exit_code: 1------ stdout ------------ stderr ------[31m✗[39m [31mWorkspace 'nonexistent' not found. Use --create to create it.[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_previous.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_previous.snapdeleted file mode 100644index 51624fe1f..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_previous.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - "-"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1malpha[22m @ [1m_REPO_.alpha[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_records_previous.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_records_previous.snapdeleted file mode 100644index 3d3b9d39b..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_records_previous.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - "-"- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mdefault[22m @ [1m_REPO_[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_to_default.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_to_default.snapdeleted file mode 100644index 436678d36..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_to_default.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - default- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mdefault[22m @ [1m_REPO_[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_to_existing_with_directive_file.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_to_existing_with_directive_file.snapdeleted file mode 100644index 9d63372d4..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_to_existing_with_directive_file.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- 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 ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__jj__jj_switch_to_existing_workspace.snap b/tests/snapshots/integration__integration_tests__jj__jj_switch_to_existing_workspace.snapdeleted file mode 100644index 13c4df772..000000000--- a/tests/snapshots/integration__integration_tests__jj__jj_switch_to_existing_workspace.snap+++ /dev/null@@ -1,35 +0,0 @@-----source: tests/integration_tests/jj.rs-info:- program: wt- args:- - switch- - feature- env:- APPDATA: "[TEST_CONFIG_HOME]"- CLICOLOR_FORCE: "1"- COLUMNS: "500"- GIT_EDITOR: ""- HOME: "[TEST_HOME]"- LANG: C- LC_ALL: C- PSModulePath: ""- RUST_LOG: warn- SHELL: ""- TERM: alacritty- USERPROFILE: "[TEST_HOME]"- WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"- WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"- WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"- WORKTRUNK_TEST_EPOCH: "1735776000"- WORKTRUNK_TEST_POWERSHELL_ENV: "0"- WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"- XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"-----success: true-exit_code: 0------ stdout ------------ stderr ------[32m✓[39m [32mSwitched to workspace [1mfeature[22m @ [1m_REPO_.feature[22m[39m-[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_outside_git_repo.snap b/tests/snapshots/integration__integration_tests__switch__switch_outside_git_repo.snapindex fbd3b1d96..843053cf1 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_outside_git_repo.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_outside_git_repo.snap@@ -32,4 +32,5 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mNot in a repository[39m+[31m✗[39m [31mFailed to switch worktree[39m+[107m [0m fatal: not a git repository (or any of the parent directories): .git