Skip to content

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

feat: Centralize background operation logs in .git/wt-logs/

Maximilian Roos57cf2eb47ecf
diff --git a/CLAUDE.md b/CLAUDE.md
index 3ecf92d58..405d4a0d4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -379,6 +379,28 @@ for line in reader.lines() {
let lines: Vec<_> = reader.lines().collect();
```
+## Background Operation Logs
+
+### Unified Logging Location
+
+All background operation logs are centralized in `.git/wt-logs/` (primary worktree's git directory):
+
+- **Post-start commands**: `{branch}-post-start-{command}.log`
+- **Background removal**: `{branch}-remove.log`
+
+Examples (where command names are from config):
+- `feature-post-start-npm.log`
+- `bugfix-remove.log`
+
+### Log Behavior
+
+- **Centralized**: All logs go to primary worktree's `.git/wt-logs/`, shared across all worktrees
+- **Overwrites**: Same operation on same branch overwrites previous log (prevents accumulation)
+- **Not tracked**: Logs are in `.git/` directory, which git doesn't track
+- **Manual cleanup**: Stale logs (from deleted branches) persist but are bounded by branch count
+
+Users can clean up old logs manually or use a git hook. No automatic cleanup is provided.
+
## Testing Guidelines
### Testing with --execute Commands
diff --git a/src/cli.rs b/src/cli.rs
index f485a0a86..7b29b9b80 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -378,6 +378,7 @@ post-start (parallel, background):
- Spawned after success message shown
- Typically: dev servers, file watchers, editors
- Run in background, failures logged but don't block
+ - Logs: .git/wt-logs/{branch}-post-start-{name}.log
- Skip with --no-verify
EXAMPLES:
@@ -490,7 +491,7 @@ Switch to default in primary:
#[arg(long = "no-delete-branch")]
no_delete_branch: bool,
- /// Background removal for large repos
+ /// Run removal in background
#[arg(long)]
background: bool,
},
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index c0045fc9b..b230fec42 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -140,7 +140,14 @@ impl<'a> HookPipeline<'a> {
crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
let name = prepared.name.as_deref().unwrap_or("cmd");
- if let Err(err) = spawn_detached(self.ctx.worktree_path, &prepared.expanded, name) {
+ let operation = format!("post-start-{}", name);
+ if let Err(err) = spawn_detached(
+ self.ctx.repo,
+ self.ctx.worktree_path,
+ &prepared.expanded,
+ self.ctx.branch,
+ &operation,
+ ) {
let err_msg = err.to_string();
let message = match &prepared.name {
Some(name) => {
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index cfcdb7c8e..408e53edf 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -59,21 +59,20 @@ impl PrStatus {
/// upstream repositories for forks. This ensures PRs opened against upstream
/// repos are properly detected.
///
- /// # Requirements
- /// The `repo_path` parameter must be a valid git repository (enforced by caller).
+ /// # Arguments
+ /// * `repo_path` - Repository root path from `Repository::worktree_root()`
pub fn detect(branch: &str, local_head: &str, repo_path: &std::path::Path) -> Option<Self> {
- // Get git repo root directory for setting working directory
- // We always run gh commands from the repo directory to let gh auto-detect the correct repo
+ // We run gh/glab commands from the repo directory to let them auto-detect the correct repo
// (including upstream repos for forks)
- let repo_root = Self::get_repo_root(repo_path);
+ let repo_root = repo_path.to_str().expect("repo path is not valid UTF-8");
// Try GitHub PR first
- if let Some(status) = Self::detect_github(branch, local_head, &repo_root) {
+ if let Some(status) = Self::detect_github(branch, local_head, repo_root) {
return Some(status);
}
// Try GitHub workflow runs (for branches without PRs)
- if let Some(status) = Self::detect_github_workflow(branch, local_head, &repo_root) {
+ if let Some(status) = Self::detect_github_workflow(branch, local_head, repo_root) {
return Some(status);
}
@@ -86,30 +85,6 @@ impl PrStatus {
Self::detect_gitlab_pipeline(branch, local_head)
}
- /// Get git repository root directory
- ///
- /// # Panics
- /// Panics if repo_path is not a valid git repository. This should never happen
- /// since repo_path comes from Repository::worktree_root() which validates it.
- fn get_repo_root(repo_path: &std::path::Path) -> String {
- let output = Command::new("git")
- .args(["rev-parse", "--show-toplevel"])
- .current_dir(repo_path)
- .output()
- .expect("failed to run git rev-parse");
-
- assert!(
- output.status.success(),
- "git rev-parse failed - repo_path {:?} is not a valid git repository",
- repo_path
- );
-
- String::from_utf8(output.stdout)
- .unwrap_or_else(|e| panic!("git output is not valid UTF-8 from {:?}: {}", repo_path, e))
- .trim()
- .to_string()
- }
-
fn detect_github(branch: &str, local_head: &str, repo_root: &str) -> Option<Self> {
// Check if gh is available and authenticated
if !Command::new("gh")
diff --git a/src/commands/process.rs b/src/commands/process.rs
index f916aff7d..37ac27511 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -1,7 +1,7 @@
use std::fs;
use std::path::Path;
use std::process::{Command, Stdio};
-use worktrunk::git::{GitError, GitResultExt};
+use worktrunk::git::{GitError, GitResultExt, Repository};
/// Spawn a detached background process with output redirected to a log file
///
@@ -9,40 +9,34 @@ use worktrunk::git::{GitError, GitResultExt};
/// - On Unix: uses double-fork with setsid to create a daemon
/// - On Windows: uses CREATE_NEW_PROCESS_GROUP to detach from console
///
+/// Logs are centralized in the primary worktree's `.git/wt-logs/` directory.
+///
/// # Arguments
+/// * `repo` - Repository instance for accessing git common directory
/// * `worktree_path` - Working directory for the command
/// * `command` - Shell command to execute
-/// * `name` - Name identifier for the process (used in log filename)
+/// * `branch` - Branch name for log organization
+/// * `name` - Operation identifier (e.g., "post-start-npm", "remove")
///
/// # Returns
/// Path to the log file where output is being written
pub fn spawn_detached(
+ repo: &Repository,
worktree_path: &Path,
command: &str,
+ branch: &str,
name: &str,
) -> Result<std::path::PathBuf, GitError> {
- // Resolve the actual .git directory path
- // In a worktree, .git is a file pointing to the real git directory
- let git_path = worktree_path.join(".git");
- let git_dir = if git_path.is_file() {
- // Read the gitdir path from the file
- let content = fs::read_to_string(&git_path).git_context("Failed to read .git file")?;
- // Format is "gitdir: /path/to/git/dir"
- let gitdir_path = content
- .trim()
- .strip_prefix("gitdir: ")
- .ok_or_else(|| GitError::CommandFailed("Invalid .git file format".to_string()))?;
- Path::new(gitdir_path).to_path_buf()
- } else {
- git_path
- };
+ // Get the git common directory (shared across all worktrees)
+ let git_common_dir = repo.git_common_dir()?;
- // Create log directory in the git directory
- let log_dir = git_dir.join("wt-logs");
+ // Create log directory in the common git directory
+ let log_dir = git_common_dir.join("wt-logs");
fs::create_dir_all(&log_dir).git_context("Failed to create log directory")?;
// Generate log filename (no timestamp - overwrites on each run)
- let log_path = log_dir.join(format!("post-start-{}.log", name));
+ // Format: {branch}-{name}.log (e.g., "feature-post-start-npm.log", "bugfix-remove.log")
+ let log_path = log_dir.join(format!("{}-{}.log", branch, name));
// Create log file
let log_file = fs::File::create(&log_path).git_context("Failed to create log file")?;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index dd0fb029d..b4b158293 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -372,6 +372,7 @@ pub fn handle_switch(
pub fn handle_remove(
worktree_name: Option<&str>,
no_delete_branch: bool,
+ background: bool,
) -> Result<RemoveResult, GitError> {
let repo = Repository::current();
@@ -382,13 +383,15 @@ pub fn handle_remove(
None
};
- // Show progress with resolved name
- let progress_msg = if let Some(ref b) = resolved_name {
- format!("{CYAN}Removing worktree for {CYAN_BOLD}{b}{CYAN_BOLD:#}...{CYAN:#}")
- } else {
- format!("{CYAN}Removing worktree...{CYAN:#}")
- };
- crate::output::progress(progress_msg)?;
+ // Show progress with resolved name (unless running in background - output handler will show command)
+ if !background {
+ let progress_msg = if let Some(ref b) = resolved_name {
+ format!("{CYAN}Removing worktree for {CYAN_BOLD}{b}{CYAN_BOLD:#}...{CYAN:#}")
+ } else {
+ format!("{CYAN}Removing worktree...{CYAN:#}")
+ };
+ crate::output::progress(progress_msg)?;
+ }
// Two modes: remove current worktree vs. remove by name
match resolved_name.as_deref() {
diff --git a/src/main.rs b/src/main.rs
index 381b228c7..c2500c3b6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -268,7 +268,7 @@ fn main() {
} => {
if worktrees.is_empty() {
// No worktrees specified, remove current worktree
- handle_remove(None, no_delete_branch)
+ handle_remove(None, no_delete_branch, background)
.and_then(|result| handle_remove_output(&result, None, false, background))
} else {
// When removing multiple worktrees, we need to handle the current worktree last
@@ -301,13 +301,18 @@ fn main() {
// Remove others first, then current last
// Progress messages shown by handle_remove_output for all cases
for worktree in others.iter() {
- let result = handle_remove(Some(worktree.as_str()), no_delete_branch)?;
+ let result =
+ handle_remove(Some(worktree.as_str()), no_delete_branch, background)?;
handle_remove_output(&result, Some(worktree.as_str()), false, background)?;
}
// Remove current worktree last (if it was in the list)
if let Some(current_name) = current {
- let result = handle_remove(Some(current_name.as_str()), no_delete_branch)?;
+ let result = handle_remove(
+ Some(current_name.as_str()),
+ no_delete_branch,
+ background,
+ )?;
handle_remove_output(
&result,
Some(current_name.as_str()),
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 9d7911d16..70e851b26 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -4,7 +4,9 @@ use crate::commands::process::spawn_detached;
use crate::commands::worktree::{RemoveResult, SwitchResult};
use crate::output::global::format_switch_success;
use worktrunk::git::GitError;
-use worktrunk::styling::{GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter};
+use worktrunk::styling::{
+ CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter,
+};
/// Format message for switch operation (mode-specific via output system)
fn format_switch_message(result: &SwitchResult, branch: &str) -> (String, bool) {
@@ -205,31 +207,27 @@ pub fn handle_remove_output(
super::flush()?; // Force flush to ensure shell processes the cd
}
+ let repo = worktrunk::git::Repository::current();
+
if background {
// Background mode: spawn detached process
let check_target = target_branch.as_deref().unwrap_or("HEAD");
let remove_command =
build_remove_command(worktree_path, branch_name, *no_delete_branch, check_target);
- // Spawn the removal in background - runs from primary_path (where we cd'd to)
- let log_path = spawn_detached(
- primary_path,
- &remove_command,
- &format!("remove-{}", branch_name),
- )?;
-
- // Show info message indicating backgrounding (not "success" - work hasn't completed)
- super::info(format!(
- "Removal queued for {GREEN_BOLD}{branch_name}{GREEN_BOLD:#} (background)"
+ // Show simple progress message (log location documented in --help)
+ super::progress(format!(
+ "{CYAN}Removing {CYAN_BOLD}{branch_name}{CYAN_BOLD:#}{CYAN} in background{CYAN:#}"
))?;
- super::info(format!("Log: {}", log_path.display()))?;
+
+ // Spawn the removal in background - runs from primary_path (where we cd'd to)
+ spawn_detached(&repo, primary_path, &remove_command, branch_name, "remove")?;
super::flush()?;
Ok(())
} else {
// Synchronous mode: remove immediately and report actual results
// Track whether branch was actually deleted (will be computed based on deletion attempt)
- let repo = worktrunk::git::Repository::current();
if let Err(err) = repo.remove_worktree(worktree_path) {
return Err(match err {
GitError::CommandFailed(msg) => GitError::WorktreeRemovalFailed {
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index d0e1afc20..2cb77279b 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -708,35 +708,20 @@ pub fn make_snapshot_cmd(
make_snapshot_cmd_with_global_flags(repo, subcommand, args, cwd, &[])
}
-/// Resolve the actual git directory path from a worktree path
+/// Resolve the git common directory (shared across all worktrees)
///
-/// In worktrees, `.git` is a file containing `gitdir: /path/to/git/dir`,
-/// not a directory. This helper reads that file and returns the actual
-/// git directory path.
+/// This is where centralized logs and other shared data are stored.
+/// For linked worktrees, this returns the primary worktree's `.git/` directory.
+/// For the primary worktree, this returns the `.git/` directory.
///
/// # Arguments
-/// * `worktree_path` - Path to the worktree root
+/// * `worktree_path` - Path to any worktree root
///
/// # Returns
-/// The resolved git directory path
-pub fn resolve_git_dir(worktree_path: &Path) -> PathBuf {
- let git_path = worktree_path.join(".git");
-
- if git_path.is_file() {
- // Read the gitdir path from the file
- let content = std::fs::read_to_string(&git_path).expect("Failed to read .git file");
-
- // Format is "gitdir: /path/to/git/dir"
- let gitdir_path = content
- .trim()
- .strip_prefix("gitdir: ")
- .expect("Invalid .git file format");
-
- PathBuf::from(gitdir_path)
- } else {
- // Not a worktree, .git is already a directory
- git_path
- }
+/// The common git directory path
+pub fn resolve_git_common_dir(worktree_path: &Path) -> PathBuf {
+ let repo = worktrunk::git::Repository::at(worktree_path);
+ repo.git_common_dir().expect("Failed to get git common dir")
}
/// Validates ANSI escape sequences for the specific nested reset pattern that causes color leaks
diff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rs
index 8e8049b31..3c6f31780 100644
--- a/tests/integration_tests/e2e_shell_post_start.rs
+++ b/tests/integration_tests/e2e_shell_post_start.rs
@@ -1,5 +1,5 @@
use crate::common::{
- TestRepo,
+ TestRepo, resolve_git_common_dir,
shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},
};
use rstest::rstest;
@@ -82,19 +82,9 @@ approved-commands = ["sleep 0.05 && echo 'Background task done' > bg_marker.txt"
.join("test-repo.bg-feature");
// First check if log file was created (proves process was spawned)
- let git_dir = worktree_path.join(".git");
- let actual_git_dir = if git_dir.is_file() {
- let content = fs::read_to_string(&git_dir).expect("Failed to read .git file");
- let gitdir_path = content
- .trim()
- .strip_prefix("gitdir: ")
- .expect("Invalid .git format");
- std::path::PathBuf::from(gitdir_path)
- } else {
- git_dir
- };
-
- let log_dir = actual_git_dir.join("wt-logs");
+ // Logs are centralized in the common git directory
+ let git_common_dir = resolve_git_common_dir(&worktree_path);
+ let log_dir = git_common_dir.join("wt-logs");
assert!(
log_dir.exists(),
"Log directory should exist at {}",
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 57e893cf7..63187db9a 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -1,4 +1,4 @@
-use crate::common::{TestRepo, make_snapshot_cmd, resolve_git_dir, setup_snapshot_settings};
+use crate::common::{TestRepo, make_snapshot_cmd, resolve_git_common_dir, setup_snapshot_settings};
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use std::fs;
@@ -260,10 +260,10 @@ approved-commands = ["sleep 0.1 && echo 'Background task done' > background.txt"
&["--create", "feature"],
);
- // Verify log file was created
+ // Verify log file was created in the common git directory
let worktree_path = repo.root_path().parent().unwrap().join("test-repo.feature");
- let git_dir = resolve_git_dir(&worktree_path);
- let log_dir = git_dir.join("wt-logs");
+ let git_common_dir = resolve_git_common_dir(&worktree_path);
+ let log_dir = git_common_dir.join("wt-logs");
assert!(log_dir.exists(), "Log directory should be created");
// Wait for the background command to complete
@@ -416,10 +416,10 @@ approved-commands = ["echo 'stdout output' && echo 'stderr output' >&2"]
// Give background command time to complete
thread::sleep(SLEEP_FAST_COMMAND);
- // Find and read the log file
+ // Find and read the log file from the common git directory
let worktree_path = repo.root_path().parent().unwrap().join("test-repo.feature");
- let git_dir = resolve_git_dir(&worktree_path);
- let log_dir = git_dir.join("wt-logs");
+ let git_common_dir = resolve_git_common_dir(&worktree_path);
+ let log_dir = git_common_dir.join("wt-logs");
assert!(log_dir.exists(), "Log directory should exist");
// Find the log file
@@ -514,10 +514,10 @@ approved-commands = [
// Give background commands time to complete
thread::sleep(SLEEP_FAST_COMMAND);
- // Verify we have 3 separate log files
+ // Verify we have 3 separate log files in the common git directory
let worktree_path = repo.root_path().parent().unwrap().join("test-repo.feature");
- let git_dir = resolve_git_dir(&worktree_path);
- let log_dir = git_dir.join("wt-logs");
+ let git_common_dir = resolve_git_common_dir(&worktree_path);
+ let log_dir = git_common_dir.join("wt-logs");
let log_files: Vec<_> = fs::read_dir(&log_dir)
.expect("Failed to read log dir")
.filter_map(|e| e.ok())
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 516f58086..814eaf6b5 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -241,3 +241,21 @@ fn test_remove_branch_not_fully_merged() {
None,
);
}
+
+#[test]
+fn test_remove_background() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create a worktree
+ let _worktree_path = repo.add_worktree("feature-bg", "feature-bg");
+
+ // Remove it with --background flag from main repo
+ snapshot_remove(
+ "remove_background",
+ &repo,
+ &["--background", "feature-bg"],
+ None,
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index aa6a127b4..f1638b77d 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpk0twDT/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp203cHd/test-config.toml
---
success: true
exit_code: 0
@@ -289,7 +289,7 @@ complete -c wt -n "__fish_wt_using_subcommand switch" -s v -l verbose -d 'Show g
complete -c wt -n "__fish_wt_using_subcommand switch" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand remove" -s C -d 'Change working directory' -r -F
complete -c wt -n "__fish_wt_using_subcommand remove" -l no-delete-branch -d 'Keep branch after removal'
-complete -c wt -n "__fish_wt_using_subcommand remove" -l background -d 'Background removal for large repos'
+complete -c wt -n "__fish_wt_using_subcommand remove" -l background -d 'Run removal in background'
complete -c wt -n "__fish_wt_using_subcommand remove" -s v -l verbose -d 'Show git commands and debug info'
complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'
complete -c wt -n "__fish_wt_using_subcommand merge" -s C -d 'Change working directory' -r -F
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index c3f5cc091..dcffab44c 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpYQy0PC/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp81uBPc/test-config.toml
---
success: true
exit_code: 0
@@ -435,7 +435,7 @@ _arguments "${_arguments_options[@]}" : \
_arguments "${_arguments_options[@]}" : \
'-C+[Change working directory]:path:_files' \
'--no-delete-branch[Keep branch after removal]' \
-'--background[Background removal for large repos]' \
+'--background[Run removal in background]' \
'-v[Show git commands and debug info]' \
'--verbose[Show git commands and debug info]' \
'-h[Print help]' \
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_background.snap b/tests/snapshots/integration__integration_tests__remove__remove_background.snap
new file mode 100644
index 000000000..eb844677b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_background.snap
@@ -0,0 +1,27 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - "--background"
+ - feature-bg
+ env:
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1761609600"
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWK1Gf3/test-config.toml
+---
+success: true
+exit_code: 0
+----- stdout -----
+🔄 Removing feature-bg in background
+
+----- stderr -----