Skip to content

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

fix(git): protect untracked files hidden by config (#4111)

DDL2f2ed12130a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5b2406ca3..dced8f9a9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,8 @@
### Fixed
+- **`wt remove`, `wt merge`, and `wt step prune` no longer discard untracked files hidden by Git configuration**: `status.showUntrackedFiles = no` made the clean-worktree guard inherit a display preference, so a worktree containing only untracked files appeared clean and could be removed without `--force` — including by `wt step prune`, which removes unattended. Safety checks now always include untracked files and name the path that blocks removal. Auto-staging warnings for `wt merge`, `wt step commit`, and `wt step squash` likewise override the setting and enumerate every file that will be staged.
+
- **`wt config plugins opencode install` no longer writes the plugin into the directory it was run from**: an exported-but-empty `OPENCODE_CONFIG_DIR` was taken at face value, so the install target collapsed to the relative path `plugins/worktrunk.ts` — typically somewhere inside the user's repository. `is_plugin_installed()` then read the plugin back from that same relative path, so the install reported success while OpenCode never saw it. An empty value now reads as unset, as it already did for `$CLAUDE_CONFIG_DIR` and `$PI_CONFIG_DIR`; the documented precedence `$OPENCODE_CONFIG_DIR` > `$XDG_CONFIG_HOME/opencode` > `~/.config/opencode` is unchanged. ([#4084](https://github.com/max-sixty/worktrunk/pull/4084))
- **`wt step prune` no longer deletes a branch created minutes ago from an older commit**: the min-age guard aged a branch with no worktree by the committer date of the commit it points at, so `git branch <name> main` on a default branch whose last commit was over a day old was pruned on the next run — the case `--min-age` exists to prevent. The branch's age now comes from its oldest reflog entry, written when the branch was created.
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 6ca9a03c1..2ffabaca2 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -259,7 +259,7 @@ impl CommitOptions<'_> {
if self.stage_mode == StageMode::All {
let status = wt
- .run_command(&["status", "--porcelain", "-z"])
+ .run_command(&["status", "--porcelain", "-z", "-uall"])
.context("Failed to get status")?;
warn_about_untracked_files(&status)?;
}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 481f4d382..114b93458 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -100,9 +100,10 @@ pub trait RepositoryCliExt {
impl RepositoryCliExt for Repository {
fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()> {
- // Use -z for NUL-separated output to handle filenames with spaces/newlines
+ // `-uall` overrides the user's display preference and expands untracked
+ // directories so the warning names every path `git add -A` will stage.
let status = self
- .run_command(&["status", "--porcelain", "-z"])
+ .run_command(&["status", "--porcelain", "-z", "-uall"])
.context("Failed to get status")?;
warn_about_untracked_files(&status)
}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 6e25d4e77..af6f085b5 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -529,8 +529,11 @@ impl<'a> WorkingTree<'a> {
/// 2. On large repos (70k+ files), this adds noticeable latency to every clean check
/// 3. Users who use skip-worktree are power users who understand the implications
/// 4. A warning wouldn't prevent data loss anyway — it's informational only
+ ///
+ /// Untracked files are always included, regardless of the user's
+ /// `status.showUntrackedFiles` display preference.
pub fn is_dirty(&self) -> anyhow::Result<bool> {
- let stdout = self.run_command(&["status", "--porcelain"])?;
+ let stdout = self.run_command(&["status", "--porcelain", "--untracked-files=normal"])?;
Ok(!stdout.trim().is_empty())
}
@@ -541,7 +544,7 @@ impl<'a> WorkingTree<'a> {
/// [`GitError::UncommittedChanges`] in [`Self::ensure_clean`]. The same
/// caveats as [`Self::is_dirty`] apply (skip-worktree files are invisible).
pub fn dirty_files(&self) -> anyhow::Result<Vec<String>> {
- let stdout = self.run_command(&["status", "--porcelain"])?;
+ let stdout = self.run_command(&["status", "--porcelain", "--untracked-files=normal"])?;
Ok(stdout.lines().map(str::to_owned).collect())
}
@@ -1377,6 +1380,31 @@ mod tests {
);
}
+ #[test]
+ fn clean_checks_report_untracked_files_hidden_by_user_config() {
+ let test = TestRepo::with_initial_commit();
+ test.run_git(&["config", "status.showUntrackedFiles", "no"]);
+ std::fs::write(test.root_path().join("hidden-by-config.txt"), "loose\n").unwrap();
+
+ assert!(
+ test.git_output(&["status", "--porcelain"]).is_empty(),
+ "the fixture must demonstrate that the user setting hides the file"
+ );
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ let wt = repo.current_worktree();
+
+ assert!(
+ wt.is_dirty().unwrap(),
+ "clean checks must not inherit status.showUntrackedFiles"
+ );
+ assert_eq!(
+ wt.dirty_files().unwrap(),
+ vec!["?? hidden-by-config.txt"],
+ "the destructive guard must name the hidden untracked file"
+ );
+ }
+
#[test]
fn prewarm_info_second_call_returns_cached_snapshot() {
// Once `worktree_roots` is primed, subsequent `prewarm_info` calls
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 6fcecf53d..ce70ddbc4 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -55,6 +55,38 @@ fn snapshot_merge_with_env(
});
}
+fn create_untracked_files_hidden_by_user_config(repo: &TestRepo, worktree: &Path) {
+ repo.run_git(&["config", "status.showUntrackedFiles", "no"]);
+ fs::create_dir(worktree.join("nested")).unwrap();
+ fs::write(worktree.join("nested/first.txt"), "first").unwrap();
+ fs::write(worktree.join("nested/second.txt"), "second").unwrap();
+
+ let hidden = repo
+ .git_command()
+ .args(["status", "--porcelain"])
+ .current_dir(worktree)
+ .run()
+ .unwrap();
+ assert!(
+ hidden.stdout.is_empty(),
+ "the fixture must demonstrate that the user setting hides both files"
+ );
+}
+
+fn assert_hidden_untracked_auto_staging_warning(output: &std::process::Output, command: &str) {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ output.status.success(),
+ "{command} should succeed; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("Auto-staging 2 untracked paths:")
+ && stderr.contains("nested/first.txt")
+ && stderr.contains("nested/second.txt"),
+ "the warning must enumerate every hidden file that git add -A will stage; stderr:\n{stderr}"
+ );
+}
+
#[rstest]
fn test_merge_fast_forward(merge_scenario: (TestRepo, PathBuf)) {
let (repo, feature_wt) = merge_scenario;
@@ -1635,6 +1667,68 @@ fn test_merge_no_commit_with_dirty_tree(mut repo: TestRepo) {
);
}
+/// `status.showUntrackedFiles` controls presentation, not whether a destructive
+/// merge cleanup may discard files. `--no-commit` must reject the hidden file
+/// before changing either branch or removing the source worktree.
+#[rstest]
+fn test_merge_no_commit_refuses_untracked_files_hidden_by_user_config(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit(
+ "feature",
+ "committed.txt",
+ "committed content",
+ "Add committed file",
+ );
+ repo.run_git(&["config", "status.showUntrackedFiles", "no"]);
+ fs::write(feature_wt.join("precious.txt"), "uncommitted work").unwrap();
+
+ let hidden = repo
+ .git_command()
+ .args(["status", "--porcelain"])
+ .current_dir(&feature_wt)
+ .run()
+ .unwrap();
+ assert!(
+ hidden.stdout.is_empty(),
+ "the fixture must demonstrate that the user setting hides the file"
+ );
+ let forced = repo
+ .git_command()
+ .args(["status", "--porcelain", "--untracked-files=normal"])
+ .current_dir(&feature_wt)
+ .run()
+ .unwrap();
+ assert!(
+ String::from_utf8_lossy(&forced.stdout).contains("?? precious.txt"),
+ "the explicit safety query must reveal the untracked file"
+ );
+
+ let target_tip = repo.git_output(&["rev-parse", "main"]);
+ let source_tip = repo.git_output(&["rev-parse", "feature"]);
+ let output = repo
+ .wt_command()
+ .args(["merge", "main", "--no-commit"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ !output.status.success(),
+ "merge must refuse hidden untracked files before cleanup; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("has uncommitted changes") && stderr.contains("precious.txt"),
+ "the dirty-worktree gate must explain the refusal; stderr:\n{stderr}"
+ );
+ assert_eq!(repo.git_output(&["rev-parse", "main"]), target_tip);
+ assert_eq!(repo.git_output(&["rev-parse", "feature"]), source_tip);
+ assert!(feature_wt.exists(), "failed merge must keep the worktree");
+ assert!(
+ feature_wt.join("precious.txt").exists(),
+ "the hidden untracked file must remain recoverable"
+ );
+}
+
#[rstest]
fn test_merge_no_commits(mut repo_with_main_worktree: TestRepo) {
let repo = &mut repo_with_main_worktree;
@@ -2443,6 +2537,27 @@ fn test_step_squash_with_no_hooks_flag(mut repo: TestRepo) {
});
}
+#[rstest]
+fn test_step_squash_auto_staging_warns_about_untracked_files_hidden_by_user_config(
+ repo_with_multi_commit_feature: TestRepo,
+) {
+ let repo = &repo_with_multi_commit_feature;
+ let feature_wt = &repo.worktrees["feature"];
+ create_untracked_files_hidden_by_user_config(repo, feature_wt);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--no-hooks"])
+ .current_dir(feature_wt)
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'squash: include hidden files'",
+ )
+ .output()
+ .unwrap();
+ assert_hidden_untracked_auto_staging_warning(&output, "step squash");
+}
+
#[rstest]
fn test_step_squash_with_stage_tracked_flag(mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
@@ -2558,6 +2673,22 @@ fn test_step_commit_with_no_hooks_flag(repo: TestRepo) {
});
}
+#[rstest]
+fn test_step_commit_auto_staging_warns_about_untracked_files_hidden_by_user_config(repo: TestRepo) {
+ create_untracked_files_hidden_by_user_config(&repo, repo.root_path());
+
+ let output = repo
+ .wt_command()
+ .args(["step", "commit", "--no-hooks"])
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'feat: include hidden files'",
+ )
+ .output()
+ .unwrap();
+ assert_hidden_untracked_auto_staging_warning(&output, "step commit");
+}
+
#[rstest]
fn test_step_commit_with_stage_tracked_flag(repo: TestRepo) {
fs::write(repo.root_path().join("tracked.txt"), "initial").expect("Failed to write file");
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index fd5c4e22c..0f0ebf617 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -777,6 +777,66 @@ fn test_remove_by_name_dirty_target(mut repo: TestRepo) {
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["feature-dirty"], None));
}
+/// A user's status display preference must not weaken the destructive clean
+/// gate. Both execution paths ultimately rename the worktree into trash, so a
+/// false clean result would make the untracked file unrecoverable.
+#[rstest]
+#[case::foreground(&["--foreground"])]
+#[case::background(&[])]
+fn test_remove_refuses_untracked_files_hidden_by_user_config(
+ mut repo: TestRepo,
+ #[case] execution_args: &[&str],
+) {
+ let branch = "feature-hidden-untracked";
+ let worktree_path = repo.add_worktree(branch);
+ repo.run_git(&["config", "status.showUntrackedFiles", "no"]);
+ fs::write(worktree_path.join("precious.txt"), "uncommitted work").unwrap();
+
+ let hidden = repo
+ .git_command()
+ .args(["status", "--porcelain"])
+ .current_dir(&worktree_path)
+ .run()
+ .unwrap();
+ assert!(
+ hidden.stdout.is_empty(),
+ "the fixture must demonstrate that the user setting hides the file"
+ );
+ let forced = repo
+ .git_command()
+ .args(["status", "--porcelain", "--untracked-files=normal"])
+ .current_dir(&worktree_path)
+ .run()
+ .unwrap();
+ assert!(
+ String::from_utf8_lossy(&forced.stdout).contains("?? precious.txt"),
+ "the explicit safety query must reveal the untracked file"
+ );
+
+ let output = repo
+ .wt_command()
+ .arg("remove")
+ .args(execution_args)
+ .arg(branch)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ !output.status.success(),
+ "remove must refuse a worktree with hidden untracked files; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("has uncommitted changes") && stderr.contains("precious.txt"),
+ "the dirty-worktree gate must explain the refusal; stderr:\n{stderr}"
+ );
+ assert!(
+ worktree_path.join("precious.txt").exists(),
+ "the hidden untracked file must remain recoverable"
+ );
+ assert_branch_exists(&repo, branch, true, &stderr);
+}
+
/// An inherited `GIT_DIR` pinned to the invoking worktree makes
/// `ensure_clean` compare the target's working tree against the invoking
/// index. When those agree on a path, a genuinely dirty target reads as
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index cfa185ec7..700951566 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -588,14 +588,26 @@ fn test_prune_min_age_passes(mut repo: TestRepo) {
assert_cmd_snapshot!(cmd);
}
-/// Prune skips worktrees with uncommitted changes
+/// Prune skips worktrees with uncommitted changes even when the user's status
+/// display preference hides the only untracked file.
#[rstest]
fn test_prune_skips_dirty(mut repo: TestRepo) {
repo.commit("initial");
+ repo.run_git(&["config", "status.showUntrackedFiles", "no"]);
- // Merged worktree with uncommitted changes — should be skipped
+ // Merged worktree with an untracked file hidden from bare status.
let wt_path = repo.add_worktree("dirty-merged");
std::fs::write(wt_path.join("scratch.txt"), "wip").unwrap();
+ let status = repo
+ .git_command()
+ .args(["status", "--porcelain"])
+ .current_dir(&wt_path)
+ .run()
+ .unwrap();
+ assert!(
+ status.stdout.is_empty(),
+ "the fixture must demonstrate that the user setting hides the file"
+ );
// Clean merged worktree — should be pruned
repo.add_worktree("clean-merged");
@@ -609,6 +621,11 @@ fn test_prune_skips_dirty(mut repo: TestRepo) {
// Dirty worktree still exists
assert!(wt_path.exists(), "Dirty worktree should be skipped");
+ assert_eq!(
+ std::fs::read_to_string(wt_path.join("scratch.txt")).unwrap(),
+ "wip",
+ "the hidden untracked file must remain recoverable"
+ );
// Clean worktree removed (non-current — no placeholder)
let clean_path = repo.root_path().parent().unwrap().join("repo.clean-merged");
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_with_no_hooks_flag.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_with_no_hooks_flag.snap
index 28880871d..9773234d1 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_commit_with_no_hooks_flag.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_with_no_hooks_flag.snap
@@ -63,7 +63,7 @@ exit_code: 0
----- stderr -----
○ Skipping pre-commit hooks (--no-hooks)
▲ Auto-staging 2 untracked paths:
-  .config/
+  .config/wt.toml
  file1.txt
◎ Generating commit message and committing changes... (2 files, +2)
  feat: add file