Skip to content

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

fix(list): ignore untracked files in conflict probes (#3906)

Maximilian Roos7e5d5ded19e1
diff --git a/docs/public/schema/list-v2.json b/docs/public/schema/list-v2.json
index 51bf15bdb..e70900694 100644
--- a/docs/public/schema/list-v2.json
+++ b/docs/public/schema/list-v2.json
@@ -220,7 +220,7 @@
"description": "How committed content is integrated; absent when determined\nnot-integrated, null when undetermined (dirty trees skip the\nexpensive checks)."
},
"merge_conflicts": {
- "description": "A merge into the default branch would conflict (local `merge-tree`\nsimulation); null while unresolved.",
+ "description": "A merge into the default branch would conflict based on committed\ncontent and tracked worktree changes (local `merge-tree` simulation);\nnull while unresolved.",
"type": [
"boolean",
"null"
diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.md
index 33761ff3a..167017a3d 100644
--- a/docs/src/content/docs/faq.md
+++ b/docs/src/content/docs/faq.md
@@ -163,7 +163,7 @@ None of this is tracked by git or pushed to remotes.
### 5. Temporary files (automatic)
-Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. They let `wt list`, `wt statusline`, `wt step diff`, and `wt switch` include untracked files without changing the real index. The files are removed when the command exits normally.
+Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories; an interrupted process can leave one behind for manual cleanup.
### What Worktrunk does NOT create
diff --git a/docs/src/content/docs/list.md b/docs/src/content/docs/list.md
index ee67c1e30..0e1c2bddb 100644
--- a/docs/src/content/docs/list.md
+++ b/docs/src/content/docs/list.md
@@ -188,7 +188,7 @@ The single highest-priority state describing the branch's relation to the defaul
| `∅` | `"orphan"` | No common ancestor with the default branch |
| `_` | `"empty"` | Same commit as the default branch, working tree clean — safe to remove; row dimmed |
| `⊂` | `"integrated"` | Content [integrated](/remove/#branch-cleanup) into the default branch or merge target via different history; the matching check is in `integration_reason`; row dimmed |
-| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes uncommitted changes |
+| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes tracked uncommitted changes |
| `–` | `"same_commit"` | Same commit as the default branch, but with uncommitted changes |
| `↕` | `"diverged"` | Both ahead of and behind the default branch |
| `↑` | `"ahead"` | Has commits the default branch doesn't |
diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.md
index 130a28514..6d7e27263 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md
@@ -159,7 +159,7 @@ None of this is tracked by git or pushed to remotes.
### 5. Temporary files (automatic)
-Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. They let `wt list`, `wt statusline`, `wt step diff`, and `wt switch` include untracked files without changing the real index. The files are removed when the command exits normally.
+Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories; an interrupted process can leave one behind for manual cleanup.
### What Worktrunk does NOT create
diff --git a/plugins/worktrunk/skills/worktrunk/reference/list.md b/plugins/worktrunk/skills/worktrunk/reference/list.md
index 69a078bfa..79d90d519 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/list.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/list.md
@@ -171,7 +171,7 @@ The single highest-priority state describing the branch's relation to the defaul
| `∅` | `"orphan"` | No common ancestor with the default branch |
| `_` | `"empty"` | Same commit as the default branch, working tree clean — safe to remove; row dimmed |
| `⊂` | `"integrated"` | Content [integrated](https://worktrunk.dev/remove/#branch-cleanup) into the default branch or merge target via different history; the matching check is in `integration_reason`; row dimmed |
-| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes uncommitted changes |
+| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes tracked uncommitted changes |
| `–` | `"same_commit"` | Same commit as the default branch, but with uncommitted changes |
| `↕` | `"diverged"` | Both ahead of and behind the default branch |
| `↑` | `"ahead"` | Has commits the default branch doesn't |
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 130a28514..6d7e27263 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -159,7 +159,7 @@ None of this is tracked by git or pushed to remotes.
### 5. Temporary files (automatic)
-Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. They let `wt list`, `wt statusline`, `wt step diff`, and `wt switch` include untracked files without changing the real index. The files are removed when the command exits normally.
+Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories; an interrupted process can leave one behind for manual cleanup.
### What Worktrunk does NOT create
diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.md
index 69a078bfa..79d90d519 100644
--- a/skills/worktrunk/reference/list.md
+++ b/skills/worktrunk/reference/list.md
@@ -171,7 +171,7 @@ The single highest-priority state describing the branch's relation to the defaul
| `∅` | `"orphan"` | No common ancestor with the default branch |
| `_` | `"empty"` | Same commit as the default branch, working tree clean — safe to remove; row dimmed |
| `⊂` | `"integrated"` | Content [integrated](https://worktrunk.dev/remove/#branch-cleanup) into the default branch or merge target via different history; the matching check is in `integration_reason`; row dimmed |
-| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes uncommitted changes |
+| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes tracked uncommitted changes |
| `–` | `"same_commit"` | Same commit as the default branch, but with uncommitted changes |
| `↕` | `"diverged"` | Both ahead of and behind the default branch |
| `↑` | `"ahead"` | Has commits the default branch doesn't |
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index adf6ad9b2..6a460250c 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -936,7 +936,7 @@ The single highest-priority state describing the branch's relation to the defaul
| `∅` | `"orphan"` | No common ancestor with the default branch |
| `_` | `"empty"` | Same commit as the default branch, working tree clean — safe to remove; row dimmed |
| `⊂` | `"integrated"` | Content [integrated](/remove/#branch-cleanup) into the default branch or merge target via different history; the matching check is in `integration_reason`; row dimmed |
-| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes uncommitted changes |
+| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes tracked uncommitted changes |
| `–` | `"same_commit"` | Same commit as the default branch, but with uncommitted changes |
| `↕` | `"diverged"` | Both ahead of and behind the default branch |
| `↑` | `"ahead"` | Has commits the default branch doesn't |
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 1e732452c..937b4bd9d 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -273,19 +273,19 @@
//!
//! ### Cached via tree SHA
//!
-//! `WorkingTreeConflicts` uses `git write-tree` to snapshot the index as a tree SHA,
-//! then checks for merge conflicts via `has_merge_conflicts_by_tree_with_base_sha`. The tree SHA is
-//! content-addressed and stable — identical index state produces the same SHA.
+//! `WorkingTreeConflicts` snapshots tracked changes as a tree SHA, then checks
+//! for merge conflicts via `has_merge_conflicts_by_tree_with_base_sha`. The tree
+//! SHA is content-addressed and stable — identical tracked state produces the
+//! same SHA.
//!
-//! When there are unstaged modifications or untracked files, the task copies the
-//! index to a temp file, runs `git add -A` to stage all working tree content,
-//! then `write-tree`.
+//! When tracked changes exist, the task copies the index to a temp file, runs
+//! `git add -u`, then `write-tree`. Untracked files remain part of the worktree
+//! status but do not participate in this advisory conflict estimate.
//!
//! The cache key is `(base_commit_sha, branch_head_sha+tree_sha)`. The branch HEAD
//! SHA captures the merge-base dependency. On cache miss, `has_merge_conflicts_by_tree_with_base_sha`
-//! creates an ephemeral commit via `git commit-tree` for merge-tree; on cache hit,
-//! no commit is created. This makes the cache-hit path a single `git write-tree`
-//! (~15ms) instead of the previous `git stash create` (~50-265ms).
+//! creates an ephemeral commit via `git commit-tree` for merge-tree; on cache
+//! hit, no commit is created.
//!
//! ### Fundamentally uncacheable
//!
@@ -797,14 +797,11 @@ pub fn collect(
render_target: RenderTarget,
) -> anyhow::Result<Option<super::model::ListData>> {
// `wt list`'s merge and conflict probes write ephemeral Git objects
- // (`write-tree`, `commit-tree`, `merge-tree --write-tree`). In a read-only
- // checkout those writes fail; redirect them into a temporary object
- // database (real database as a read-only alternate) so the analysis still
- // runs — see `Repository::redirect_objects_if_read_only`. A `None` (writable
- // store, or no writable temp dir) leaves object-writing tasks on the real
- // database, where they surface their own errors.
- let redirected = repo.redirect_objects_if_read_only();
- let repo = redirected.as_ref().unwrap_or(repo);
+ // (`write-tree`, `commit-tree`, `merge-tree --write-tree`) that nothing
+ // references. Redirect them into a temporary object database so they leave
+ // no unreachable objects behind and still work in a read-only checkout.
+ let redirected = repo.redirect_objects_for_observation()?;
+ let repo = &redirected;
let show_progress = matches!(render_target, RenderTarget::Table { progressive: true });
let render_table = matches!(render_target, RenderTarget::Table { .. });
worktrunk::trace::instant("List collect started");
@@ -2221,15 +2218,10 @@ pub fn populate_item(
item: &mut ListItem,
mut options: CollectOptions,
) -> anyhow::Result<()> {
- // Mirror `collect()`: in a read-only checkout, redirect this item's
- // object-writing merge/conflict probes into a temporary object database so
- // the statusline still classifies integration state. `wt list statusline`
- // is a separate entry point from `collect()` (its only callers are in
- // `commands/statusline.rs`) and renders on every Claude Code prompt inside
- // exactly the managed read-only sandbox this targets. See
- // `Repository::redirect_objects_if_read_only`.
- let redirected = repo.redirect_objects_if_read_only();
- let repo = redirected.as_ref().unwrap_or(repo);
+ // Mirror `collect()`: statusline has a separate entry point but runs the
+ // same object-writing merge/conflict probes.
+ let redirected = repo.redirect_objects_for_observation()?;
+ let repo = &redirected;
// Populate commit data directly. The main `collect()` path batches this
// across all items pre-skeleton; the single-item statusline path has no
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index e892093ab..79a85b959 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -609,10 +609,10 @@ impl Task for WorkingTreeDiffTask {
/// Uses default_branch (local main) for consistency with other Main subcolumn symbols.
/// Shows whether merging to your local main would conflict.
///
-/// **Skip-when-dirty optimization:** for worktree items, peek at the shared
-/// porcelain cache. When the worktree is dirty (and has no unmerged
-/// entries), `WorkingTreeConflictsTask` will produce a `Some(Some(_))`
-/// dirty-tree result that is authoritative for the WouldConflict tier
+/// **Skip-when-tracked-dirty optimization:** for worktree items, peek at the
+/// shared porcelain cache. When the worktree has tracked changes (and has no
+/// unmerged entries), `WorkingTreeConflictsTask` will produce a
+/// `Some(Some(_))` tracked-tree result that is authoritative for the WouldConflict tier
/// (`tier_would_conflict` short-circuits on `Some(Some(_))` and ignores the
/// HEAD probe). Returning
/// the redundant HEAD probe in that case would mean a second `git merge-tree`
@@ -635,15 +635,15 @@ impl Task for MergeTreeConflictsTask {
has_merge_tree_conflicts: false,
});
};
- // Skip-when-dirty: defer to WorkingTreeConflictsTask. Only when the
- // worktree is dirty without unmerged entries — the unmerged path
+ // Skip when tracked changes let WorkingTreeConflictsTask provide the
+ // authoritative result. The unmerged path
// returns `Some(None)` from WorkingTreeConflictsTask, which falls
// back to this HEAD probe.
if let Some(wt) = ctx.branch_ref.working_tree(&ctx.repo) {
let porcelain = wt
.status_porcelain_cached()
.map_err(|e| ctx.error(Self::KIND, &e))?;
- if !porcelain.trim().is_empty() && !has_unmerged_entries(&porcelain) {
+ if has_tracked_changes(&porcelain) && !has_unmerged_entries(&porcelain) {
return Ok(TaskResult::MergeTreeConflicts {
item_idx: ctx.item_idx,
has_merge_tree_conflicts: false,
@@ -671,14 +671,13 @@ impl Task for MergeTreeConflictsTask {
/// Task 6b (worktree only): Working tree conflict check
///
-/// For dirty worktrees, builds a tree SHA from the index (plus untracked
-/// files if present) via `git write-tree`, then checks for merge conflicts
-/// against the default branch. Much cheaper than `git stash create` (~15ms
-/// vs ~50-265ms) because it reads the index directly instead of creating a
-/// full stash commit with working-tree diffing.
+/// For worktrees with tracked changes, builds a tree SHA from the index plus
+/// unstaged tracked changes, then checks for merge conflicts against the
+/// default branch. Untracked files remain visible in status but do not
+/// participate in this best-effort conflict estimate.
///
-/// Returns None if working tree is clean (caller should fall back to
-/// MergeTreeConflicts).
+/// Returns None if the working tree has no usable tracked snapshot (caller
+/// falls back to MergeTreeConflicts).
pub struct WorkingTreeConflictsTask;
impl Task for WorkingTreeConflictsTask {
@@ -703,10 +702,8 @@ impl Task for WorkingTreeConflictsTask {
.status_porcelain_cached()
.map_err(|e| ctx.error(Self::KIND, &e))?;
- let is_dirty = !status_output.trim().is_empty();
-
- if !is_dirty {
- // Clean working tree - return None to signal "use commit-based check"
+ if !has_tracked_changes(&status_output) {
+ // A clean or untracked-only worktree uses the commit-based check.
return Ok(TaskResult::WorkingTreeConflicts {
item_idx: ctx.item_idx,
has_working_tree_conflicts: None,
@@ -725,24 +722,18 @@ impl Task for WorkingTreeConflictsTask {
});
}
- // Porcelain format: XY where X=index, Y=working-tree.
- // Fast path when all changes are staged (Y is space for every line):
- // write-tree on the real index is sufficient.
- // Slow path when there are unstaged modifications (Y != ' ') or
- // untracked files ('??'): copy index, `git add -A`, write-tree.
- let needs_working_tree = status_output
+ // A staged-only snapshot needs only `write-tree` against a copy of the
+ // index. Unstaged tracked changes also run `add -u` against that copy so
+ // the user's staging state stays untouched. Untracked entries are
+ // ignored.
+ let has_unstaged_tracked_changes = status_output
.lines()
- .any(|l| l.starts_with("??") || l.as_bytes().get(1) != Some(&b' '));
-
- let tree_sha = if needs_working_tree {
- // Stage all dirty + untracked entries into a temp index so
- // `write-tree` produces a tree representing the full working
- // state. Real index untouched. See `WorkingTree::temp_index`.
- wt.write_worktree_tree()
+ .any(|line| !line.starts_with("??") && line.as_bytes().get(1) != Some(&b' '));
+ let tree_sha = if has_unstaged_tracked_changes {
+ wt.write_tracked_worktree_tree()
.map_err(|e| ctx.error(Self::KIND, &e))?
} else {
- wt.run_command(&["write-tree"])
- .map(|s| s.trim().to_string())
+ wt.write_index_tree()
.map_err(|e| ctx.error(Self::KIND, &e))?
};
@@ -1073,6 +1064,11 @@ fn has_unmerged_entries(status_output: &str) -> bool {
})
}
+/// Whether porcelain status contains a staged or unstaged tracked path.
+fn has_tracked_changes(status_output: &str) -> bool {
+ status_output.lines().any(|line| !line.starts_with("??"))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1126,4 +1122,10 @@ mod tests {
assert!(!has_unmerged_entries("?? untracked.txt"));
assert!(!has_unmerged_entries(""));
}
+
+ #[test]
+ fn tracked_changes_ignore_untracked_porcelain_entries() {
+ assert!(!has_tracked_changes("?? artifact.bin"));
+ assert!(has_tracked_changes("?? artifact.bin\n M src/main.rs"));
+ }
}
diff --git a/src/commands/list/collect/types.rs b/src/commands/list/collect/types.rs
index 34b17c68c..064bbd769 100644
--- a/src/commands/list/collect/types.rs
+++ b/src/commands/list/collect/types.rs
@@ -71,16 +71,17 @@ pub(crate) enum TaskResult {
item_idx: usize,
has_merge_tree_conflicts: bool,
},
- /// Potential merge conflicts including working tree changes
+ /// Potential merge conflicts including tracked working tree changes
///
- /// For dirty worktrees, uses `git stash create` to get a tree object that
- /// includes uncommitted changes, then runs merge-tree against that.
- /// Returns None if working tree is clean (fall back to MergeTreeConflicts).
+ /// Copies the index, stages unstaged tracked changes with `git add -u`, and
+ /// runs merge-tree against the resulting tree. Returns None when there are
+ /// no tracked changes or the index is unmerged (fall back to
+ /// MergeTreeConflicts).
WorkingTreeConflicts {
item_idx: usize,
- /// None = working tree clean (use MergeTreeConflicts result)
- /// Some(true) = dirty working tree would conflict
- /// Some(false) = dirty working tree would not conflict
+ /// None = no tracked result (use MergeTreeConflicts result)
+ /// Some(true) = tracked working tree state would conflict
+ /// Some(false) = tracked working tree state would not conflict
has_working_tree_conflicts: Option<bool>,
},
/// Git operation in progress, `None` when there is none
diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rs
index dd004dbb0..05fddc37d 100644
--- a/src/commands/list/json_v2.rs
+++ b/src/commands/list/json_v2.rs
@@ -332,8 +332,9 @@ pub struct JsonDefaultBranch {
#[serde(skip_serializing_if = "Tri::is_absent")]
pub integration: Tri<JsonIntegration>,
- /// A merge into the default branch would conflict (local `merge-tree`
- /// simulation); null while unresolved.
+ /// A merge into the default branch would conflict based on committed
+ /// content and tracked worktree changes (local `merge-tree` simulation);
+ /// null while unresolved.
pub merge_conflicts: Option<bool>,
}
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 183f61225..5aca0ce8a 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -57,8 +57,9 @@ pub struct WorktreeData {
pub has_conflicts: Option<bool>,
/// Result of `WorkingTreeConflicts` task (`--full` mode only). Outer `None`
/// = task hasn't run yet. Outer `Some(None)` = task ran but working tree
- /// was clean, so fall back to the committed-HEAD merge-tree check.
- /// Outer `Some(Some(b))` = dirty working tree, `b` is the conflict result.
+ /// had no tracked result, so fall back to the committed-HEAD merge-tree
+ /// check. Outer `Some(Some(b))` = tracked working tree state was probed,
+ /// `b` is the conflict result.
pub has_working_tree_conflicts: Option<Option<bool>>,
/// Git operation in progress. Outer `None` = not yet loaded;
/// `Some(None)` = loaded, no operation in progress.
diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rs
index 9d404de16..22d42efe3 100644
--- a/src/commands/list/model/state.rs
+++ b/src/commands/list/model/state.rs
@@ -317,16 +317,15 @@ pub fn tier_orphan(is_orphan: Option<bool>) -> Tier<MainState> {
/// integrated into the default branch.
///
/// `has_merge_tree_conflicts` is the committed-HEAD probe (from
-/// `MergeTreeConflicts`). `has_working_tree_conflicts` is the dirty-tree
+/// `MergeTreeConflicts`). `has_working_tree_conflicts` is the tracked-tree
/// probe (from `WorkingTreeConflicts`), with a nested Option: outer `None`
-/// = task not run, `Some(None)` = task ran but working tree is clean (no
-/// dirty-tree result, fall back to the HEAD probe), `Some(Some(b))` =
-/// dirty-tree result.
+/// = task not run, `Some(None)` = task ran but has no tracked result (fall back
+/// to the HEAD probe), `Some(Some(b))` = tracked-tree result.
///
-/// **The working-tree probe is authoritative when present.** A dirty
-/// worktree's tree includes HEAD's content plus any uncommitted changes,
-/// so its merge-tree result reflects the user's current state better than
-/// the HEAD-only probe. When `has_working_tree_conflicts` is
+/// **The working-tree probe is authoritative when present.** Its tree includes
+/// HEAD's content plus staged and unstaged tracked changes, so its merge-tree
+/// result reflects the tracked working state better than the HEAD-only probe.
+/// When `has_working_tree_conflicts` is
/// `Some(Some(b))`, fire/rule out on `b` and ignore the HEAD probe.
/// `MergeTreeConflictsTask` skips its merge-tree call in that case to
/// avoid a redundant subprocess (returning a sentinel `false` that this
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index b231240e7..9ce8f3cb3 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -1295,16 +1295,64 @@ mod read_only_object_store_tests {
(test, main_sha, feature_sha)
}
- /// A writable object database must never redirect — the normal path is
- /// left byte-for-byte unchanged.
+ #[cfg(unix)]
#[test]
- fn writable_object_database_is_not_redirected() {
+ fn redirected_objects_resolve_a_repo_path_containing_a_colon() {
+ let parent = crate::testing::test_tempdir();
+ let test = TestRepo::at(&parent.path().join("repo:with-colon"));
+ test.commit("Initial commit");
+
+ let redirected = test.repo.redirect_objects_for_observation().unwrap();
+ assert!(
+ redirected
+ .run_command_check(&["cat-file", "-e", "HEAD"])
+ .unwrap(),
+ "the real object database must remain readable through the redirect"
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn redirected_objects_resolve_a_repo_path_containing_a_newline() {
+ let parent = crate::testing::test_tempdir();
+ let test = TestRepo::at(&parent.path().join("repo\nwith-newline"));
+ test.commit("Initial commit");
+
+ let redirected = test.repo.redirect_objects_for_observation().unwrap();
+ assert!(
+ redirected
+ .run_command_check(&["cat-file", "-e", "HEAD"])
+ .unwrap(),
+ "the real object database must remain readable through the redirect"
+ );
+ }
+
+ #[test]
+ fn redirected_object_directory_unregisters_on_drop() {
let test = TestRepo::with_initial_commit();
- let repo = Repository::at(test.root_path()).unwrap();
+ let redirected = test.repo.redirect_objects_for_observation().unwrap();
+ let directory = redirected
+ .object_store_environment()
+ .unwrap()
+ .0
+ .to_path_buf();
+ assert!(
+ test.repo
+ .cache
+ .observation_object_directories
+ .contains_key(&directory)
+ );
+
+ drop(redirected);
+
assert!(
- repo.redirect_objects_if_read_only().is_none(),
- "a writable object database must not trigger a redirect"
+ !test
+ .repo
+ .cache
+ .observation_object_directories
+ .contains_key(&directory)
);
+ assert!(!directory.exists());
}
/// The safety property behind scoping the redirect to observational
@@ -1329,7 +1377,7 @@ mod read_only_object_store_tests {
// Redirected clone: the merge tree lands in the temporary store only.
let redirected = Repository::at(test.root_path())
.unwrap()
- .with_temporary_object_directory()
+ .redirect_objects_for_observation()
.unwrap();
let ephemeral_tree = merge_tree(&redirected);
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 0c8b3ddd2..3d2814f09 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -351,6 +351,10 @@ pub(super) struct RepoCache {
/// (working-tree diff + conflict detection) share one subprocess per worktree
/// instead of spawning `git status` twice.
pub(super) status_porcelain: DashMap<PathBuf, String>,
+ /// Process-scoped object databases created by observational repository
+ /// clones. Original clones consult this shared set so Worktrunk's own
+ /// temporary directories never appear as untracked worktree content.
+ pub(super) observation_object_directories: DashMap<PathBuf, ()>,
}
/// Result of resolving a worktree name.
@@ -625,6 +629,68 @@ pub fn normalize_selector(name: &str) -> &str {
if trimmed.is_empty() { name } else { trimmed }
}
+/// Quote one path for Git's C-style alternate-object-directory list.
+#[cfg(unix)]
+fn quote_alternate_object_directory(path: &OsStr) -> OsString {
+ use std::os::unix::ffi::{OsStrExt, OsStringExt};
+
+ let mut quoted = Vec::with_capacity(path.as_bytes().len() + 2);
+ quoted.push(b'"');
+ for &byte in path.as_bytes() {
+ match byte {
+ b'\\' | b'"' => {
+ quoted.push(b'\\');
+ quoted.push(byte);
+ }
+ b'\n' => quoted.extend_from_slice(b"\\n"),
+ b'\r' => quoted.extend_from_slice(b"\\r"),
+ b'\t' => quoted.extend_from_slice(b"\\t"),
+ b'\x08' => quoted.extend_from_slice(b"\\b"),
+ b'\x0c' => quoted.extend_from_slice(b"\\f"),
+ b' '..=b'~' => quoted.push(byte),
+ _ => {
+ quoted.push(b'\\');
+ quoted.push(b'0' + ((byte >> 6) & 0o7));
+ quoted.push(b'0' + ((byte >> 3) & 0o7));
+ quoted.push(b'0' + (byte & 0o7));
+ }
+ }
+ }
+ quoted.push(b'"');
+ OsString::from_vec(quoted)
+}
+
+#[cfg(not(unix))]
+fn quote_alternate_object_directory(path: &OsStr) -> OsString {
+ let mut quoted = String::from("\"");
+ for ch in path.to_string_lossy().chars() {
+ match ch {
+ '\\' | '"' => {
+ quoted.push('\\');
+ quoted.push(ch);
+ }
+ '\n' => quoted.push_str("\\n"),
+ '\r' => quoted.push_str("\\r"),
+ '\t' => quoted.push_str("\\t"),
+ _ => quoted.push(ch),
+ }
+ }
+ quoted.push('"');
+ quoted.into()
+}
+
+/// Prepend the real object database while preserving inherited alternates.
+fn alternate_object_directories(primary: &Path) -> OsString {
+ let mut alternates = quote_alternate_object_directory(primary.as_os_str());
+ if let Some(inherited) =
+ std::env::var_os("GIT_ALTERNATE_OBJECT_DIRECTORIES").filter(|value| !value.is_empty())
+ {
+ alternates.push(if cfg!(windows) { ";" } else { ":" });
+ alternates.push(inherited);
+ }
+ alternates
+}
+
/// Repository state for git operations.
///
/// Represents the shared state of a git repository (the `.git` directory).
@@ -659,23 +725,33 @@ pub struct Repository {
/// Cached data for this repository. Shared across clones via Arc.
pub(super) cache: Arc<RepoCache>,
/// When set, object-writing git plumbing is redirected into a temporary
- /// object database so observational commands run in a read-only checkout.
- /// `None` for the normal (persistent) path. See
- /// [`Repository::redirect_objects_if_read_only`].
- temporary_object_directory: Option<Arc<TemporaryObjectDirectory>>,
+ /// object database. `None` for the normal persistent path. See
+ /// [`Repository::redirect_objects_for_observation`].
+ /// Held behind an `Arc` so list's parallel repository clones share one
+ /// store, removed when the last clone drops.
+ temporary_object_store: Option<Arc<TemporaryObjectStore>>,
}
-/// A throwaway object database that a redirected [`Repository`] writes new
-/// objects into, with the real database (plus any inherited alternates) as
-/// read-only alternates so existing objects still resolve.
+/// A process-scoped object database plus its visibility registration.
///
-/// Held behind an `Arc` so cloning a `Repository` — as `wt list` does for its
-/// parallel tasks — shares one store and one `TempDir` lifetime; the directory
-/// is removed when the last clone drops.
+/// The shared registration lets repository clones that do not carry the
+/// redirect exclude Worktrunk's own directory from untracked-file views. It
+/// must disappear with the last redirected clone so a subsequently-created
+/// user path at the same location is visible again.
#[derive(Debug)]
-struct TemporaryObjectDirectory {
+struct TemporaryObjectStore {
directory: tempfile::TempDir,
alternates: OsString,
+ registered_path: PathBuf,
+ cache: Arc<RepoCache>,
+}
+
+impl Drop for TemporaryObjectStore {
+ fn drop(&mut self) {
+ self.cache
+ .observation_object_directories
+ .remove(&self.registered_path);
+ }
}
impl Repository {
@@ -732,86 +808,71 @@ impl Repository {
discovery_path,
git_common_dir,
cache: Arc::new(cache),
- temporary_object_directory: None,
+ temporary_object_store: None,
})
}
- /// If this repository's object database is read-only, return a clone whose
- /// object-writing git plumbing is redirected into a temporary object
- /// database (with the real database as a read-only alternate); otherwise
- /// return `Ok(None)` and let the caller keep using `self` unchanged.
+ /// Return a clone whose object-writing git plumbing is redirected into a
+ /// temporary object database.
///
/// Only *observational* commands may redirect. `wt list`'s merge and
/// conflict probes create ephemeral objects (`write-tree`, `commit-tree`,
/// `merge-tree --write-tree`) that are never referenced, so writing them to
/// a throwaway store is harmless and lets the command run in a read-only
- /// checkout. A *mutating* command must never redirect — its commit would be
- /// written to the throwaway store and lost at process exit. Because a
- /// read-only object database also blocks the ref/index/worktree writes
- /// those commands need, keeping them on the persistent database makes them
- /// fail loudly rather than silently succeed into a store that vanishes.
- pub fn redirect_objects_if_read_only(&self) -> Option<Self> {
- let objects = self.object_database_path();
-
- // Probe effective writability by creating a file in the object
- // database — the same thing git's object writers do, so this fails
- // exactly when they would (a read-only mount and a `chmod`ed directory
- // both surface here, unlike the owner-write permission bit). A
- // successful probe file is dropped immediately.
- if tempfile::Builder::new()
- .prefix(".worktrunk-write-probe-")
- .tempfile_in(&objects)
- .is_ok()
- {
- return None;
- }
-
- self.with_temporary_object_directory()
- }
-
- /// Build a clone whose object writes are redirected into a fresh temporary
- /// object database, with the real database as a read-only alternate so
- /// existing objects still resolve. Returns `None` when the temporary store
- /// can't be created (no writable temp dir), leaving the caller on the real
- /// database. This is the *mechanism*; the *policy* — whether to redirect at
- /// all — lives in [`Self::redirect_objects_if_read_only`], the only
- /// production caller.
- fn with_temporary_object_directory(&self) -> Option<Self> {
- let alternates = self.object_database_path().into_os_string();
- let directory = tempfile::Builder::new()
- .prefix("worktrunk-list-objects-")
- .tempdir()
- .ok()?;
+ /// checkout. If the system temporary directory is unavailable, the store
+ /// falls back to the Git common directory. A *mutating* command must never
+ /// redirect because its commit would disappear with the store.
+ pub fn redirect_objects_for_observation(&self) -> anyhow::Result<Self> {
+ let alternate = self.object_database_path();
+ let mut builder = tempfile::Builder::new();
+ builder.prefix("worktrunk-list-objects-");
+ let directory = match builder.tempdir() {
+ Ok(directory) => directory,
+ Err(temp_error) => builder.tempdir_in(&self.git_common_dir).context(format!(
+ "Failed to create temporary object database in the system temp directory or Git common directory; system temp error: {temp_error}"
+ ))?,
+ };
+ let alternates = alternate_object_directories(&alternate);
+ let registered_path = directory.path().to_path_buf();
+ self.cache
+ .observation_object_directories
+ .insert(registered_path.clone(), ());
let mut clone = self.clone();
- clone.temporary_object_directory = Some(Arc::new(TemporaryObjectDirectory {
+ clone.temporary_object_store = Some(Arc::new(TemporaryObjectStore {
directory,
alternates,
+ registered_path,
+ cache: Arc::clone(&self.cache),
}));
- Some(clone)
+ Ok(clone)
}
- /// Absolute path to this repository's shared object database — the store a
- /// redirected repository probes for writability and names as its read-only
- /// alternate.
- ///
- /// This is the common dir's `objects`, shared by every linked worktree. It
- /// does not resolve an inherited `GIT_OBJECT_DIRECTORY` (set only when `wt`
- /// runs under a git alias); that combined with a read-only store and a
- /// `wt list` is vanishingly rare, and the redirect degrades to reading the
- /// common store rather than failing.
+ /// Absolute path to the effective object database that a redirected
+ /// repository names as its read-only alternate.
fn object_database_path(&self) -> PathBuf {
- let objects = self.git_common_dir.join("objects");
+ let objects = std::env::var_os("GIT_OBJECT_DIRECTORY")
+ .map(PathBuf::from)
+ .map(|path| {
+ if path.is_absolute() {
+ path
+ } else {
+ std::env::current_dir()
+ .unwrap_or_else(|_| self.discovery_path.clone())
+ .join(path)
+ }
+ })
+ .unwrap_or_else(|| self.git_common_dir.join("objects"));
canonicalize(&objects).unwrap_or(objects)
}
- /// The `(object-directory, alternates)` environment for a redirected
- /// repository, or `None` when object writes go to the real database.
+ /// The object-directory environment for a redirected repository, or `None`
+ /// when object writes go to the real database.
/// Copied into [`WorkingTree`]'s [`TempIndex`], which builds its own `Cmd`.
pub(super) fn object_store_environment(&self) -> Option<(&Path, &OsStr)> {
- self.temporary_object_directory
+ self.temporary_object_store
.as_ref()
- .map(|temporary| (temporary.directory.path(), temporary.alternates.as_os_str()))
+ .map(|store| (store.directory.path(), store.alternates.as_os_str()))
}
/// Add the temporary-object-database environment to `cmd` when this
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index 46b8b593b..95112dc67 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -2,6 +2,27 @@ use std::path::PathBuf;
use super::super::{DefaultBranchName, WorktreeInfo, finalize_worktree};
+#[cfg(unix)]
+#[test]
+fn alternate_object_directory_uses_git_c_style_quoting() {
+ use std::ffi::OsStr;
+ use std::os::unix::ffi::{OsStrExt, OsStringExt};
+
+ let path = OsStr::from_bytes(b"a:b\n\r\t\x08\x0c\\\"\x01\xff");
+ let quoted = super::quote_alternate_object_directory(path);
+ assert_eq!(
+ quoted.into_vec(),
+ b"\"a:b\\n\\r\\t\\b\\f\\\\\\\"\\001\\377\""
+ );
+}
+
+#[cfg(not(unix))]
+#[test]
+fn alternate_object_directory_uses_git_c_style_quoting() {
+ let quoted = super::quote_alternate_object_directory(std::ffi::OsStr::new("a;b\n\r\t\\\""));
+ assert_eq!(quoted, "\"a;b\\n\\r\\t\\\\\\\"\"");
+}
+
#[test]
fn test_parse_worktree_list() {
let output = "worktree /path/to/main
@@ -389,7 +410,7 @@ fn repo_path_error_when_is_bare_fails() {
discovery_path: PathBuf::from("/nonexistent/repo"),
git_common_dir: PathBuf::from("/nonexistent/.git"),
cache: Arc::new(RepoCache::default()),
- temporary_object_directory: None,
+ temporary_object_store: None,
};
let err = repo.repo_path().unwrap_err();
@@ -432,7 +453,7 @@ fn repo_path_ignores_non_local_core_worktree() {
discovery_path: tmp.path().to_path_buf(),
git_common_dir: git_dir.clone(),
cache: Arc::new(cache),
- temporary_object_directory: None,
+ temporary_object_store: None,
};
// Should fall through to parent(git_common_dir), ignoring the bulk value.
@@ -655,7 +676,7 @@ fn is_builtin_fsmonitor_enabled_variants() {
discovery_path: PathBuf::from("/nonexistent/repo"),
git_common_dir: PathBuf::from("/nonexistent/.git"),
cache: Arc::new(cache),
- temporary_object_directory: None,
+ temporary_object_store: None,
}
}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 8d5ac370b..d72bcadac 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -1,5 +1,6 @@
//! WorkingTree - a borrowed handle for worktree-specific git operations.
+use std::ffi::OsString;
use std::path::{Path, PathBuf};
use anyhow::Context;
@@ -28,6 +29,17 @@ fn escape_pathspec_glob_literal(path: &str) -> String {
})
}
+/// Exclude one Worktrunk-owned temporary directory inside a worktree.
+fn temporary_path_exclusion(worktree_root: &Path, temporary_path: &Path) -> Option<String> {
+ let temporary_path = canonicalize_with_parents(temporary_path);
+ let worktree_root = canonicalize_with_parents(worktree_root);
+ temporary_path
+ .strip_prefix(worktree_root)
+ .ok()
+ .filter(|relative| !relative.as_os_str().is_empty())
+ .map(|relative| format!(":(top,exclude,literal){}", relative.to_slash_lossy()))
+}
+
/// Parse `git submodule status` output and detect whether any submodule is initialized.
///
/// Status lines start with a one-character state marker:
@@ -408,17 +420,31 @@ impl<'a> WorkingTree<'a> {
match self.repo.cache.status_porcelain.entry(self.path.clone()) {
Entry::Occupied(e) => Ok(e.get().clone()),
Entry::Vacant(e) => {
- let stdout = self.run_command(&[
+ let exclusions = self.observation_path_exclusions()?;
+ let mut args = vec![
"--no-optional-locks",
"status",
"--porcelain",
"--untracked-files=normal",
- ])?;
+ ];
+ args.extend(exclusions.iter().map(String::as_str));
+ let stdout = self.run_command(&args)?;
Ok(e.insert(stdout).clone())
}
}
}
+ fn observation_path_exclusions(&self) -> anyhow::Result<Vec<String>> {
+ let worktree_root = self.root()?;
+ Ok(self
+ .repo
+ .cache
+ .observation_object_directories
+ .iter()
+ .filter_map(|entry| temporary_path_exclusion(&worktree_root, entry.key()))
+ .collect())
+ }
+
/// Check if the working tree has uncommitted changes.
///
/// Note: This does NOT detect files hidden via `git update-index --assume-unchanged`
@@ -763,15 +789,12 @@ impl<'a> WorkingTree<'a> {
}
fn untracked_diff_stats(&self) -> anyhow::Result<LineDiff> {
- let output =
- self.run_command_output(&["ls-files", "--others", "--exclude-standard", "-z"])?;
+ let exclusions = self.observation_path_exclusions()?;
+ let mut args = vec!["ls-files", "--others", "--exclude-standard", "-z"];
+ args.extend(exclusions.iter().map(String::as_str));
+ let output = self.run_command_output(&args)?;
if !output.status.success() {
- return Err(CommandError::from_failed_output(
- "git",
- &["ls-files", "--others", "--exclude-standard", "-z"],
- &output,
- )
- .into());
+ return Err(CommandError::from_failed_output("git", &args, &output).into());
}
let paths: Vec<String> = output
@@ -827,10 +850,14 @@ impl<'a> WorkingTree<'a> {
// a shared system temp directory. A missing `<gitdir>/index` is
// semantically an empty index (nothing staged), so only that case
// closes and removes the 0-byte file before Git creates a valid index.
- let mut temp_file = tempfile::Builder::new()
- .prefix(TEMP_INDEX_PREFIX)
- .tempfile()
- .context("Failed to create temporary index")?;
+ let mut builder = tempfile::Builder::new();
+ builder.prefix(TEMP_INDEX_PREFIX);
+ let mut temp_file = match builder.tempfile() {
+ Ok(file) => file,
+ Err(temp_error) => builder.tempfile_in(&git_dir).context(format!(
+ "Failed to create temporary index in the system temp directory or Git directory; system temp error: {temp_error}"
+ ))?,
+ };
let mut real_index_file = match std::fs::File::open(&real_index) {
Ok(file) => Some(file),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
@@ -854,21 +881,30 @@ impl<'a> WorkingTree<'a> {
object_store_environment: self.repo.object_store_environment().map(
|(directory, alternates)| (directory.to_path_buf(), alternates.to_os_string()),
),
+ observation_path_exclusions: self.observation_path_exclusions()?,
})
}
- /// Write a tree containing the index plus every working-tree change.
+ /// Write a tree containing the index plus tracked working-tree changes.
///
- /// A temporary index keeps the user's staging state unchanged. `--sparse`
- /// is intentional here: this is a complete worktree snapshot for conflict
- /// detection, so untracked files outside a sparse-checkout definition must
- /// participate too.
- pub fn write_worktree_tree(&self) -> anyhow::Result<String> {
+ /// A temporary index keeps the user's staging state unchanged. The conflict
+ /// probe is advisory and leaves untracked paths out of its synthetic tree.
+ pub fn write_tracked_worktree_tree(&self) -> anyhow::Result<String> {
let index = self.temp_index()?;
- index.stage_worktree_snapshot()?;
+ // With no pathspec, `add -u` also accepts an empty index (a staged
+ // deletion of every tracked file, or a missing real index). The command
+ // still covers the whole worktree because TempIndex runs at its root.
+ index.run_command(["add".to_string(), "-u".to_string(), "--sparse".to_string()])?;
index.write_tree()
}
+ /// Write a tree containing the current index state without changing the
+ /// real index. Copying the index keeps a missing real index absent while
+ /// avoiding a working-tree scan for staged-only changes.
+ pub fn write_index_tree(&self) -> anyhow::Result<String> {
+ self.temp_index()?.write_tree()
+ }
+
/// Determine whether there are staged changes in the index.
///
/// Returns `Ok(true)` when staged changes are present, `Ok(false)` otherwise.
@@ -967,7 +1003,7 @@ impl<'a> WorkingTree<'a> {
/// operations there. Today the callers are
/// [`WorkingTree::working_tree_diff_stats_with_untracked`] (HEAD± with
/// untracked, used by `wt list --full` / `wt statusline`),
-/// `WorkingTreeConflictsTask` (write-tree of dirty + untracked, for
+/// `WorkingTreeConflictsTask` (write-tree of tracked changes, for
/// merge-conflict probing), `wt step diff` (diff vs target merge-base with
/// untracked), `wt step commit --dry-run` (mirror its `--stage` mode without
/// changing the user's index), and the `wt switch` unified/working preview tabs.
@@ -977,8 +1013,11 @@ pub struct TempIndex {
log_ctx: String,
/// Copied from the [`Repository`] so a redirected `wt list` writes the temp
/// index's `write-tree` objects into the temporary store. `None` on the
- /// normal persistent path. See [`Repository::redirect_objects_if_read_only`].
- object_store_environment: Option<(PathBuf, std::ffi::OsString)>,
+ /// normal persistent path. See [`Repository::redirect_objects_for_observation`].
+ object_store_environment: Option<(PathBuf, OsString)>,
+ /// Exact Worktrunk-owned temporary directories to hide from untracked
+ /// previews when the configured temp directory is inside this worktree.
+ observation_path_exclusions: Vec<String>,
}
impl TempIndex {
@@ -1008,20 +1047,6 @@ impl TempIndex {
Ok(())
}
- /// Stage a complete working-tree snapshot, crossing sparse boundaries.
- fn stage_worktree_snapshot(&self) -> anyhow::Result<()> {
- let mut args = vec![
- "add".to_string(),
- "-A".to_string(),
- "--sparse".to_string(),
- "--".to_string(),
- ".".to_string(),
- ];
- self.append_temp_index_exclusion(&mut args)?;
- self.run_command(args)?;
- Ok(())
- }
-
/// Write the temporary index as a tree and return its object id.
fn write_tree(&self) -> anyhow::Result<String> {
self.run_command(["write-tree"])
@@ -1066,6 +1091,7 @@ impl TempIndex {
":(top,exclude,glob){relative}{separator}{TEMP_INDEX_PREFIX}*"
));
}
+ args.extend(self.observation_path_exclusions.iter().cloned());
Ok(())
}
@@ -1363,6 +1389,31 @@ mod tests {
);
}
+ #[test]
+ fn observation_object_directory_is_excluded_from_status_and_diff() {
+ let test = TestRepo::with_initial_commit();
+ let observation_directory = test
+ .root_path()
+ .join("local-tmp/worktrunk-list-objects-test");
+ std::fs::create_dir_all(observation_directory.join("info")).unwrap();
+ std::fs::write(observation_directory.join("info/alternates"), "temporary\n").unwrap();
+ std::fs::write(test.root_path().join("untracked.txt"), "user\n").unwrap();
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ repo.cache
+ .observation_object_directories
+ .insert(observation_directory.clone(), ());
+ let wt = repo.current_worktree();
+
+ let status = wt.status_porcelain_cached().unwrap();
+ assert!(status.contains("?? untracked.txt"));
+ assert!(!status.contains("worktrunk-list-objects-test"));
+
+ let stats = wt.working_tree_diff_stats_with_untracked().unwrap();
+ assert_eq!(stats.added, 1);
+ assert_eq!(stats.deleted, 0);
+ }
+
fn sparse_checkout_with_untracked_file() -> TestRepo {
let test = TestRepo::with_initial_commit();
std::fs::create_dir_all(test.root_path().join("visible")).unwrap();
@@ -1405,20 +1456,19 @@ mod tests {
}
#[test]
- fn write_worktree_tree_crosses_sparse_checkout_boundary() {
+ fn tracked_worktree_tree_crosses_sparse_checkout_boundary() {
let test = sparse_checkout_with_untracked_file();
+ std::fs::write(test.root_path().join("hidden/tracked.txt"), "changed\n").unwrap();
let repo = Repository::at(test.root_path()).unwrap();
- let tree = repo.current_worktree().write_worktree_tree().unwrap();
+ let tree = repo
+ .current_worktree()
+ .write_tracked_worktree_tree()
+ .unwrap();
let files = test.git_output(&["ls-tree", "-r", "--name-only", &tree]);
assert_eq!(
files.lines().collect::<Vec<_>>(),
- [
- "file.txt",
- "hidden/loose.txt",
- "hidden/tracked.txt",
- "visible/tracked.txt",
- ]
+ ["file.txt", "hidden/tracked.txt", "visible/tracked.txt"]
);
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 57565d359..b0cd74ad9 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -3329,7 +3329,7 @@ fn test_list_maximum_status_symbols(mut repo: TestRepo) {
///
/// This specifically tests the WorkingTreeConflicts task which:
-/// 1. Uses `git write-tree` to snapshot the index (with temp index for unstaged/untracked)
+/// 1. Uses a temp index plus `git write-tree` to snapshot tracked changes
/// 2. Runs merge-tree against the default branch to detect conflicts
///
/// Both kinds of conflicts are checked in both `wt list` and `wt list --full`:
@@ -3369,9 +3369,8 @@ fn test_list_working_tree_conflicts(mut repo: TestRepo) {
});
}
-/// A dirty worktree may contain untracked files outside its sparse-checkout
-/// definition. The temporary-index snapshot must still include the visible
-/// tracked change and produce the working-tree conflict result.
+/// A tracked file modified outside the sparse-checkout definition must still
+/// participate in the working-tree conflict result.
#[rstest]
fn test_list_working_tree_conflicts_cross_sparse_checkout_boundary(mut repo: TestRepo) {
repo.write_test_config("[list]\njson-schema = 2\n");
@@ -3384,14 +3383,13 @@ fn test_list_working_tree_conflicts_cross_sparse_checkout_boundary(mut repo: Tes
repo.commit("Add sparse fixture");
let feature = repo.add_worktree("feature");
- std::fs::write(repo.root_path().join("visible/shared.txt"), "main\n").unwrap();
- repo.commit("Change shared file on main");
+ std::fs::write(repo.root_path().join("hidden/tracked.txt"), "main\n").unwrap();
+ repo.commit("Change hidden file on main");
repo.run_git_in(&feature, &["sparse-checkout", "init", "--cone"]);
repo.run_git_in(&feature, &["sparse-checkout", "set", "visible"]);
- std::fs::write(feature.join("visible/shared.txt"), "feature\n").unwrap();
std::fs::create_dir_all(feature.join("hidden")).unwrap();
- std::fs::write(feature.join("hidden/loose.txt"), "loose\n").unwrap();
+ std::fs::write(feature.join("hidden/tracked.txt"), "feature\n").unwrap();
let output = repo
.wt_command()
@@ -3415,6 +3413,195 @@ fn test_list_working_tree_conflicts_cross_sparse_checkout_boundary(mut repo: Tes
assert_eq!(feature["default_branch"]["merge_conflicts"], true);
}
+/// A staged deletion can leave the temporary index empty. The conflict probe
+/// must still write that empty tree and detect a modify/delete conflict.
+#[rstest]
+fn test_list_working_tree_conflicts_with_staged_deletion_of_all_files(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ std::fs::write(repo.root_path().join("shared.txt"), "base\n").unwrap();
+ repo.commit("Initial commit");
+ let feature_path = repo.add_worktree("feature");
+
+ repo.run_git_in(&feature_path, &["rm", "shared.txt"]);
+ std::fs::write(repo.root_path().join("shared.txt"), "main\n").unwrap();
+ repo.commit("Change on main");
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt list should succeed; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["branch"] == "feature")
+ .expect("feature row");
+ assert_eq!(feature["default_branch"]["merge_conflicts"], true);
+}
+
+/// Untracked paths stay visible as changes but do not participate in the
+/// advisory merge-conflict estimate.
+#[rstest]
+fn test_list_ignores_untracked_paths_for_conflict_estimate(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ repo.commit("Initial commit");
+ let feature_path = repo.add_worktree("feature");
+
+ std::fs::write(repo.root_path().join("collision.txt"), "main\n").unwrap();
+ repo.run_git(&["add", "collision.txt"]);
+ repo.run_git(&["commit", "-m", "Add collision path"]);
+ std::fs::write(feature_path.join("collision.txt"), "untracked\n").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt list should succeed; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["branch"] == "feature")
+ .expect("feature row");
+ assert_eq!(feature["worktree"]["changes"]["untracked"], true);
+ assert_eq!(feature["default_branch"]["merge_conflicts"], false);
+}
+
+/// Ignoring untracked paths must still fall back to the committed conflict
+/// probe rather than treating an untracked-only worktree as conflict-free.
+#[rstest]
+fn test_list_untracked_only_preserves_committed_conflict(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ std::fs::write(repo.root_path().join("shared.txt"), "base\n").unwrap();
+ repo.commit("Initial commit");
+ let feature_path = repo.add_worktree("feature");
+
+ std::fs::write(feature_path.join("shared.txt"), "feature\n").unwrap();
+ repo.run_git_in(&feature_path, &["add", "shared.txt"]);
+ repo.run_git_in(&feature_path, &["commit", "-m", "Change on feature"]);
+ std::fs::write(repo.root_path().join("shared.txt"), "main\n").unwrap();
+ repo.commit("Change on main");
+ std::fs::write(feature_path.join("artifact.bin"), "untracked\n").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt list should succeed; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["branch"] == "feature")
+ .expect("feature row");
+ assert_eq!(feature["worktree"]["changes"]["untracked"], true);
+ assert_eq!(feature["default_branch"]["merge_conflicts"], true);
+}
+
+/// Every object produced by an observational merge probe is process-scoped,
+/// including blobs and trees for changing tracked worktree content.
+#[rstest]
+fn test_list_does_not_persist_observation_objects(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ repo.commit("Initial commit");
+ let feature_path = repo.add_worktree("feature");
+ repo.commit("Main diverges");
+
+ let before = repo.git_output(&["count-objects", "-v"]);
+ std::fs::write(feature_path.join("file.txt"), "feature\n").unwrap();
+ std::fs::write(feature_path.join("artifact.bin"), "untracked\n").unwrap();
+
+ for args in [
+ &["list", "--format=json"][..],
+ &["list", "statusline", "--format=json"][..],
+ ] {
+ let output = repo
+ .wt_command()
+ .args(args)
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{} should succeed; stderr:\n{}",
+ args.join(" "),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ assert_eq!(
+ repo.git_output(&["count-objects", "-v"]),
+ before,
+ "observational probes must leave the real object database unchanged"
+ );
+}
+
+/// A broken system temporary-directory setting must not prevent either list
+/// entry point from rendering. Probe objects fall back to a temporary directory
+/// in Git's metadata and still disappear when the command exits.
+#[cfg(unix)]
+#[rstest]
+fn test_list_survives_unavailable_system_temp_directory(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ repo.commit("Initial commit");
+ let feature_path = repo.add_worktree("feature");
+ repo.commit("Main diverges");
+ std::fs::write(feature_path.join("file.txt"), "feature\n").unwrap();
+
+ let before = repo.git_output(&["count-objects", "-v"]);
+ let missing_temp = repo.root_path().join("missing-temp");
+ assert!(!missing_temp.exists());
+ for args in [
+ &["list", "--format=json"][..],
+ &["list", "statusline", "--format=json"][..],
+ ] {
+ let output = repo
+ .wt_command()
+ .args(args)
+ .current_dir(&feature_path)
+ .env("TMPDIR", &missing_temp)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "{} should fall back from an unavailable TMPDIR; stderr:\n{}",
+ args.join(" "),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ assert_eq!(
+ repo.git_output(&["count-objects", "-v"]),
+ before,
+ "fallback probe objects must not enter the real object database"
+ );
+}
+
///
/// Even with --full, if the working tree is clean, we skip the working-tree check
/// and just use the commit-level conflict detection.
@@ -3750,8 +3937,7 @@ fn test_list_unborn_worktree_no_task_failures(repo: TestRepo) {
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
- // Untracked content forces WorkingTreeConflictsTask to run merge-tree
- // against the null OID rather than short-circuiting on a clean tree.
+ // Untracked content forces WorkingTreeDiffTask to inspect the unborn tree.
std::fs::write(orphan_path.join("untracked.txt"), "content\n").unwrap();
let output = repo
@@ -4013,6 +4199,89 @@ fn test_list_tolerates_missing_index(mut repo: TestRepo) {
);
}
+#[rstest]
+#[case::relative(false)]
+#[case::absolute(true)]
+fn test_list_preserves_inherited_object_directory(
+ mut repo: TestRepo,
+ #[case] use_absolute_path: bool,
+) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ repo.commit("Initial commit");
+ repo.add_worktree("feature");
+ let feature_sha = repo.git_output(&["rev-parse", "feature"]);
+
+ let objects = repo.root_path().join(".git/objects");
+ let external_objects = repo.root_path().join(".git/external-objects");
+ std::fs::rename(&objects, &external_objects).unwrap();
+ std::fs::create_dir_all(objects.join("info")).unwrap();
+ std::fs::create_dir_all(objects.join("pack")).unwrap();
+
+ let object_directory = if use_absolute_path {
+ external_objects.to_string_lossy().into_owned()
+ } else {
+ ".git/external-objects".to_owned()
+ };
+
+ let output = repo
+ .wt_command()
+ .env("GIT_OBJECT_DIRECTORY", object_directory)
+ .args(["list", "--format=json"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt list should preserve GIT_OBJECT_DIRECTORY; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["branch"] == "feature")
+ .expect("feature row");
+ assert_eq!(feature["head"]["sha"], feature_sha);
+}
+
+#[rstest]
+fn test_list_preserves_inherited_object_alternates(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ repo.commit("Initial commit");
+ repo.add_worktree_with_commit("feature", "feature.txt", "feature\n", "Add feature");
+
+ let feature_sha = repo.git_output(&["rev-parse", "feature"]);
+ let object_path = std::path::Path::new(&feature_sha[..2]).join(&feature_sha[2..]);
+ let objects = repo.root_path().join(".git/objects");
+ let alternate = repo.home_path().join("alternate-objects");
+ std::fs::create_dir_all(alternate.join(object_path.parent().unwrap())).unwrap();
+ std::fs::rename(objects.join(&object_path), alternate.join(&object_path)).unwrap();
+
+ let output = repo
+ .wt_command()
+ .env("GIT_ALTERNATE_OBJECT_DIRECTORIES", &alternate)
+ .args(["list", "--format=json"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt list should preserve inherited alternates; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json["items"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|item| item["branch"] == "feature")
+ .expect("feature row");
+ assert_eq!(feature["head"]["sha"], feature_sha);
+}
+
/// Recursively strips write permission from a repository's object database and
/// restores the original modes on drop, so a test can exercise the read-only
/// sandbox path without leaving an unremovable directory behind.
@@ -4068,7 +4337,7 @@ impl Drop for ReadOnlyObjectDirectory {
/// read-only (a managed sandbox). Its merge and conflict probes write
/// ephemeral objects — `merge-tree --write-tree` for the integration diff and
/// `write-tree` against a temp index for the dirty-worktree conflict check —
-/// which `Repository::redirect_objects_if_read_only` reroutes into a temporary
+/// which `Repository::redirect_objects_for_observation` reroutes into a temporary
/// object database. The analysis stays complete instead of erroring with
/// "insufficient permission for adding an object".
#[cfg(unix)]
diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rs
index b6bab51e4..cd7b89ca5 100644
--- a/tests/integration_tests/switch_picker_dry_run.rs
+++ b/tests/integration_tests/switch_picker_dry_run.rs
@@ -187,11 +187,10 @@ fn test_picker_dry_run_speculative_complete_diff_uses_real_head(
}
/// A user may point TMPDIR inside the repository (common in hermetic build
-/// environments). Temporary indexes share an excluded temp namespace so
-/// concurrent panes cannot see them as untracked files. Genuine untracked
-/// content still appears.
+/// environments). Worktrunk's temporary indexes and object databases must not
+/// appear as untracked files. Genuine untracked content still appears.
#[rstest]
-fn test_picker_dry_run_tempdir_inside_worktree_has_no_index_artifacts(
+fn test_picker_dry_run_tempdir_inside_worktree_has_no_worktrunk_artifacts(
#[from(main_only_repo)] repo: TestRepo,
) {
// Brackets also prove the exclusion quotes Git pathspec glob metacharacters
@@ -235,7 +234,7 @@ fn test_picker_dry_run_tempdir_inside_worktree_has_no_index_artifacts(
);
assert!(
!content.contains("local-[tmp]/"),
- "mode {mode} must not include temporary-index artifacts: {content:?}"
+ "mode {mode} must not include Worktrunk's temporary artifacts: {content:?}"
);
}
}
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index ec7162c17..8214fecd9 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -244,17 +244,17 @@ An in-progress git operation, a worktree-location attribute, or a branch with no
The single highest-priority state describing the branch's relation to the default branch; blank when none applies (a normal up-to-date branch). Each symbol is one main_state value:
- Symbol main_state Meaning
- ────── ──────────────── ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
- ^ "is_main" The main worktree (the repo's home worktree)
- ∅ "orphan" No common ancestor with the default branch
- _ "empty" Same commit as the default branch, working tree clean — safe to remove; row dimmed
- ⊂ "integrated" Content integrated into the default branch or merge target via different history; the matching check is in integration_reason; row dimmed
- ✗ "would_conflict" Merging into the default branch would conflict (simulated with git merge-tree) and the branch isn't already integrated; with --full, the check includes uncommitted changes
- – "same_commit" Same commit as the default branch, but with uncommitted changes
- ↕ "diverged" Both ahead of and behind the default branch
- ↑ "ahead" Has commits the default branch doesn't
- ↓ "behind" Missing commits the default branch has
+ Symbol main_state Meaning
+ ────── ──────────────── ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ ^ "is_main" The main worktree (the repo's home worktree)
+ ∅ "orphan" No common ancestor with the default branch
+ _ "empty" Same commit as the default branch, working tree clean — safe to remove; row dimmed
+ ⊂ "integrated" Content integrated into the default branch or merge target via different history; the matching check is in integration_reason; row dimmed
+ ✗ "would_conflict" Merging into the default branch would conflict (simulated with git merge-tree) and the branch isn't already integrated; with --full, the check includes tracked uncommitted changes
+ – "same_commit" Same commit as the default branch, but with uncommitted changes
+ ↕ "diverged" Both ahead of and behind the default branch
+ ↑ "ahead" Has commits the default branch doesn't
+ ↓ "behind" Missing commits the default branch has
Rows are dimmed when safe to delete — _ ("empty") or ⊂ ("integrated").
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index aa3965489..3a76b74d6 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -319,7 +319,7 @@ symbol is one main_state value:
; row dimmed
✗ "would_con Merging into the default branch would conflict (simulated with
flict" git merge-tree) and the branch isn't already integrated; with
- --full, the check includes uncommitted changes
+ --full, the check includes tracked uncommitted changes
– "same_comm Same commit as the default branch, but with uncommitted
it" changes
↕ "diverged" Both ahead of and behind the default branch