Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Release v0.79.0 (#4181)
Maximilian Roosf8136155519b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca6f390c3..2bb5b151f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,49 @@# Changelog+## 0.79.0++### Improved++- **`wt switch --no-cd -x <program>` runs the program in the worktree**: it started in the invoking directory, so a program meant for the new worktree had to be handed `{{ worktree_path }}`. `--no-cd` now governs only your shell — `wt switch feature --no-cd -x code -- .` opens the worktree in an editor and leaves your terminal put. (Breaking: a program that wanted the invoking directory needs an explicit `cd`.) Fixes [#4042](https://github.com/max-sixty/worktrunk/issues/4042). ([#4179](https://github.com/max-sixty/worktrunk/pull/4179), thanks @yajo for reporting)++- **The picker's preview tabs show which have content**: a tab's label is dim when that tab is empty for the selected row, and underlined when it's the active tab. Availability sat on the tab's number alone, so every inactive label read dim whatever the row held. ([#4174](https://github.com/max-sixty/worktrunk/pull/4174))++- **Messages name the destination, and end with the command to run**: without shell integration, `wt merge` and `wt remove` printed `Cannot change directory — shell integration not installed` and no path; the warning now names the worktree, as `wt switch` already did. "Cannot determine default branch" had four wordings, and three recovery hints put their command first rather than last. ([#4163](https://github.com/max-sixty/worktrunk/pull/4163), [#4155](https://github.com/max-sixty/worktrunk/pull/4155), thanks @blrain3 for reporting)++- **`/wt-switch-create` no longer stalls at Claude Code's path-entry dialog**: Claude Code confirms every entry outside `.claude/worktrees/`, which is every Worktrunk worktree, so a background session waited for someone to attach. The plugin now approves entry into a worktree at its `worktree-path` location, and reads a bare name as the repo or the branch. ([#4158](https://github.com/max-sixty/worktrunk/pull/4158), [#4159](https://github.com/max-sixty/worktrunk/pull/4159))++### Fixed++- **`wt merge` on a dirty worktree describes what it commits**: the generated message covered the branch's earlier commits and said nothing about the work the merge had just staged into the same commit. `wt step squash --dry-run` now stages into a temp index so its preview covers what the run would commit, as `wt step commit --dry-run` does. ([#4178](https://github.com/max-sixty/worktrunk/pull/4178))++- **Diff display config no longer changes what Worktrunk reads**: `color.ui = always` and `diff.external` reached the commit, squash, and summary prompts. Two settings could also hide a branch's changes from the integration check, so `wt remove` deleted the branch without `-D`: `diff.relative` when run from a subdirectory the changes sat outside, and `submodule.<name>.ignore` on a submodule bump. Every diff Worktrunk parses now runs plumbing, which ignores that configuration, and upgrading discards the cached answers. ([#4146](https://github.com/max-sixty/worktrunk/pull/4146), [#4147](https://github.com/max-sixty/worktrunk/pull/4147), [#4181](https://github.com/max-sixty/worktrunk/pull/4181))++- **`wt config update --output <path>` asks before overwriting**: it replaced whatever was there, so `--output ~/.config/worktrunk/config.toml` from a repo with a deprecated project config wiped the user config and reported success. It now prompts, takes `--yes`, and refuses the config being migrated. (Breaking: `--output` naming the config being migrated used to succeed unless the migration dropped `approved-commands`.) ([#4153](https://github.com/max-sixty/worktrunk/pull/4153))++- **A config save no longer rewrites the rest of your config**: declining a prompt, or setting the commit-generation command, rewrote the whole file — dropping values written at their default, and re-spelling hook pipelines with their comments. It also reloaded that file over the in-memory config, so `wt step commit --config-set 'commit.stage="none"'` staged everything once it had asked about commit generation. ([#4160](https://github.com/max-sixty/worktrunk/pull/4160), [#4156](https://github.com/max-sixty/worktrunk/pull/4156), [#4151](https://github.com/max-sixty/worktrunk/pull/4151))++- **Auto-staging names a wholly untracked directory once**: since 0.78.0 the warning expanded each one into its files, so `wt step commit`, `wt step squash`, and `wt merge` listed 300 paths for a directory of 300 new files. The listing also stops at ten rows, with a hint counting the rest. ([#4152](https://github.com/max-sixty/worktrunk/pull/4152), thanks @Duang777)++- **`wt merge --no-ff` and `wt step push --no-ff` sign their merge commit under `commit.gpgSign`**: they built it with `commit-tree`, which ignores that setting. `wt step rebase` and `wt merge` also pass `--no-update-refs`, so a rebase rewrites only its own worktree's branch. (Breaking: `rebase.updateRefs` no longer moves other local branches stacked in the rebased range.) ([#4146](https://github.com/max-sixty/worktrunk/pull/4146))++- **`wt step prune --min-age` guards branches with no reflog**: they got no age guard at all, so in a bare repository — where `core.logAllRefUpdates` defaults off — a branch that had just arrived at an integrated commit was pruned on the next run. Age now comes from the mtime of the file holding the ref. ([#4154](https://github.com/max-sixty/worktrunk/pull/4154))++- **The picker preview no longer drops a character**: the pane rendered one column wider than skim paints, so a wrapped line breaking flush against the right edge lost its last character mid-sentence. ([#4178](https://github.com/max-sixty/worktrunk/pull/4178))++- **`wt config plugins pi install` expands `~` in `$PI_CODING_AGENT_DIR`**: Pi expands it, so `PI_CODING_AGENT_DIR="~/x"` means a directory under home, where Worktrunk created a literal `~` directory under the current directory. ([#4151](https://github.com/max-sixty/worktrunk/pull/4151))++### Documentation++- **The picker demo shows the CI and summary columns filling in**: `alt-p` widens the rows, the cells land behind them, then it pages a diff, a PR's comment thread, and the PR itself. The homepage omnibus demo opens on the picker. [Docs](https://worktrunk.dev/switch/#interactive-picker) ([#4178](https://github.com/max-sixty/worktrunk/pull/4178))++- **The command pages got a sweep**: help text drops internals, deprecated behavior, and edge cases the command reports itself when they happen — `wt step diff`'s "How it works", the `wt hook --var` paragraph, and the `wt config state ci-status` page among them. Every config sample now renders the file it belongs in as its tab. ([#4157](https://github.com/max-sixty/worktrunk/pull/4157), [#4153](https://github.com/max-sixty/worktrunk/pull/4153), [#4173](https://github.com/max-sixty/worktrunk/pull/4173), [#4177](https://github.com/max-sixty/worktrunk/pull/4177))++### Internal++- **Library API rework** (Breaking library API): `cargo-semver-checks` fails five lints — `BranchDiffSpec` swaps `revs`/`working_base` for `diff_base`, `UserConfig::save_to` gives way to the `ConfigEdit` mutations, `config::UnknownAnalysis` is gone, `Repository::prepare_diff` takes `from`/`to` in place of a revision list, and four diff helpers on `PreparedDiff` and `WorkingTree` go with it. ([#4146](https://github.com/max-sixty/worktrunk/pull/4146), [#4147](https://github.com/max-sixty/worktrunk/pull/4147), [#4160](https://github.com/max-sixty/worktrunk/pull/4160), [#4156](https://github.com/max-sixty/worktrunk/pull/4156))++- **The Nix flake's test sandbox gains `openssh`**, which the merge-signing test needs. ([#4168](https://github.com/max-sixty/worktrunk/pull/4168))+## 0.78.0### Improveddiff --git a/CLAUDE.md b/CLAUDE.mdindex d9225a790..e87a57c06 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -243,6 +243,8 @@ No `get_*` — bare nouns follow Rust stdlib convention.`Repository` caches read-only values via `Arc<RepoCache>` (cloning shares it). What is and isn't cached, the `list_worktrees()` post-mutation invariant, the two storage patterns, and the in-memory-`RepoCache`-vs-persistent-`sha_cache` decision (cheap-and-hot → in-memory get-or-create; expensive → disk; both → in-memory front over disk back): the `# Caching` section in `src/git/repository/mod.rs`.+**A change to what a cached value means bumps `CACHE_EPOCH`** (`src/cache.rs`). The persistent entries are keyed on SHA pairs with no TTL, so the key cannot see the generator's output: an entry written by an older `wt` keeps answering until its key recurs, and on a finished branch that is never. Moving the diffs onto plumbing is the worked example — it left `has-added-changes` entries saying an unmerged branch had no added changes, which is `wt remove` deleting it. So the question belongs to any change that alters what a cached read reports, not just to code inside `cache.rs`; ask it whenever a generator behind one of `sha_cache`'s kinds changes.+## ReleasesUse the `release` skill (version bump, changelog, crates.io publish, GitHub release). It writes every changelog entry from the commits since the last tag, so other PRs leave `CHANGELOG.md` untouched; a PR that already carries an entry drops it rather than resolving a conflict on it.diff --git a/Cargo.lock b/Cargo.lockindex fef0422e5..51d719bd7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4657,7 +4657,7 @@ dependencies = [[[package]]name = "worktrunk"-version = "0.78.0"+version = "0.79.0"dependencies = ["ansi-str","ansi-to-tui",diff --git a/Cargo.toml b/Cargo.tomlindex bf7badfe2..162d7b3cc 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -56,7 +56,7 @@ filterset = "test(/aur_pkgbuild/)"[package]name = "worktrunk"-version = "0.78.0"+version = "0.79.0"edition = "2024"rust-version = "1.97"build = "build.rs"diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.mdindex 023dd1c26..9f759af11 100644--- a/docs/src/content/docs/faq.md+++ b/docs/src/content/docs/faq.md@@ -138,7 +138,7 @@ Worktrunk stores repository state, caches, and logs under `.git/`:| Location | Purpose | Created by ||----------|---------|------------|| `git config worktrunk.*` | Cached default branch, switch history, branch markers, custom variables | Various commands |-| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases) | `wt list`, `wt merge`, `wt remove` |+| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases), beside a stamp of what those results mean — a worktrunk that disagrees with it discards the tree | `wt list`, `wt merge`, `wt remove` || `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) || `.git/wt/cache/picker-preview/*.json` | Rendered preview panes for the interactive picker | `wt switch` || `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |@@ -213,6 +213,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file- `wt remove` — also stops the removed worktree's `git fsmonitor--daemon` (under `core.fsmonitor=true`), and sweeps `.git/wt/trash/` entries older than 24 hours along with fsmonitor daemons whose worktree no longer exists+- any command reading a cache — discards the cached git-command results under `.git/wt/cache/` when they were written by a worktrunk that computed them differently, so a stale answer can't outlive the code that produced it. Cached CI status and LLM summaries are keyed on what they describe, so they are left alone- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell install` — replaces an existing fish or Nushell wrapper file whole, and removes one an older version installed at a previous location (fish `conf.d/wt.fish`, Nushell `<config-dir>/vendor/autoload/wt.nu`), printing each removal; [Files created](/shell-integration/#files-created) names the file each shell gets- `wt config shell uninstall` — removes the lines that run `wt config shell init` from bash/zsh/PowerShell rc files, and deletes wrapper and completion files carrying worktrunk's content markers (fish `functions/`, `conf.d/`, and `completions/`; nushell `vendor/autoload`). Every removed line is printeddiff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex e3e8e4d4a..b9bbcc732 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -134,7 +134,7 @@ Worktrunk stores repository state, caches, and logs under `.git/`:| Location | Purpose | Created by ||----------|---------|------------|| `git config worktrunk.*` | Cached default branch, switch history, branch markers, custom variables | Various commands |-| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases) | `wt list`, `wt merge`, `wt remove` |+| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases), beside a stamp of what those results mean — a worktrunk that disagrees with it discards the tree | `wt list`, `wt merge`, `wt remove` || `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) || `.git/wt/cache/picker-preview/*.json` | Rendered preview panes for the interactive picker | `wt switch` || `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |@@ -209,6 +209,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file- `wt remove` — also stops the removed worktree's `git fsmonitor--daemon` (under `core.fsmonitor=true`), and sweeps `.git/wt/trash/` entries older than 24 hours along with fsmonitor daemons whose worktree no longer exists+- any command reading a cache — discards the cached git-command results under `.git/wt/cache/` when they were written by a worktrunk that computed them differently, so a stale answer can't outlive the code that produced it. Cached CI status and LLM summaries are keyed on what they describe, so they are left alone- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell install` — replaces an existing fish or Nushell wrapper file whole, and removes one an older version installed at a previous location (fish `conf.d/wt.fish`, Nushell `<config-dir>/vendor/autoload/wt.nu`), printing each removal; [Files created](https://worktrunk.dev/shell-integration/#files-created) names the file each shell gets- `wt config shell uninstall` — removes the lines that run `wt config shell init` from bash/zsh/PowerShell rc files, and deletes wrapper and completion files carrying worktrunk's content markers (fish `functions/`, `conf.d/`, and `completions/`; nushell `vendor/autoload`). Every removed line is printeddiff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex e3e8e4d4a..b9bbcc732 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -134,7 +134,7 @@ Worktrunk stores repository state, caches, and logs under `.git/`:| Location | Purpose | Created by ||----------|---------|------------|| `git config worktrunk.*` | Cached default branch, switch history, branch markers, custom variables | Various commands |-| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases) | `wt list`, `wt merge`, `wt remove` |+| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases), beside a stamp of what those results mean — a worktrunk that disagrees with it discards the tree | `wt list`, `wt merge`, `wt remove` || `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) || `.git/wt/cache/picker-preview/*.json` | Rendered preview panes for the interactive picker | `wt switch` || `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |@@ -209,6 +209,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file- `wt remove` — also stops the removed worktree's `git fsmonitor--daemon` (under `core.fsmonitor=true`), and sweeps `.git/wt/trash/` entries older than 24 hours along with fsmonitor daemons whose worktree no longer exists+- any command reading a cache — discards the cached git-command results under `.git/wt/cache/` when they were written by a worktrunk that computed them differently, so a stale answer can't outlive the code that produced it. Cached CI status and LLM summaries are keyed on what they describe, so they are left alone- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell install` — replaces an existing fish or Nushell wrapper file whole, and removes one an older version installed at a previous location (fish `conf.d/wt.fish`, Nushell `<config-dir>/vendor/autoload/wt.nu`), printing each removal; [Files created](https://worktrunk.dev/shell-integration/#files-created) names the file each shell gets- `wt config shell uninstall` — removes the lines that run `wt config shell init` from bash/zsh/PowerShell rc files, and deletes wrapper and completion files carrying worktrunk's content markers (fish `functions/`, `conf.d/`, and `completions/`; nushell `vendor/autoload`). Every removed line is printeddiff --git a/src/cache.rs b/src/cache.rsindex 87815603b..4a0c3b944 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -29,22 +29,198 @@//! errors so `wt config state clear` can report truthfully when it can't//! delete a file (e.g. permission denied). `NotFound` is counted as "already//! gone" so concurrent clearers don't fight each other.-+//!+//! # Epoch+//!+//! A SHA-keyed entry has no TTL and no invalidation rule, so it answers for+//! whatever code wrote it until its key recurs — which for a finished branch+//! is never. That is correct while a given key means one thing, and wrong the+//! moment a release changes how the value is computed: the stale entry then+//! outranks the new code at the one call that would have corrected it.+//! `CACHE_EPOCH` is the version of that meaning. `ensure_epoch` discards the+//! kinds it governs when the stamp on disk disagrees, so a generator change is+//! one constant bump rather than a rename per affected kind.+//! `UNVERSIONED_KINDS` names the kinds it leaves alone and why each one holds.++use std::collections::HashSet;use std::fs;use std::path::{Path, PathBuf};+use std::sync::{Mutex, OnceLock};use std::time::SystemTime;use serde::{Serialize, de::DeserializeOwned};use crate::git::Repository;+/// The meaning of the cached values, bumped whenever a change alters what any+/// of them says.+///+/// 1 — v0.79.0 moved every diff `wt` parses onto plumbing, so display config+/// can no longer change what it reads. The porcelain reads that preceded it+/// wrote `has-added-changes` and `merge-add-probe` entries that, under+/// `diff.relative` or `submodule.<name>.ignore`, recorded a branch as having+/// no added changes when it had some. Those entries are keyed on the branch+/// and target tips, both of which sit still on a finished branch, so without+/// this stamp the first `wt remove` after the upgrade still reads the old+/// answer and deletes an unmerged branch. `diff-stats` and the diffs behind+/// the LLM prompts moved in the same change.+///+/// The stamp records the last worktrunk to *check* a tree, not the version+/// that wrote each entry, so a v0.78.0 binary run against an already-stamped+/// tree writes porcelain answers this one will trust. Two binaries against one+/// repository is the case that costs; putting the epoch in each entry's path+/// is what would close it.+const CACHE_EPOCH: u32 = 1;++/// Kinds the epoch leaves alone. `ci-status` and `pr-number` store the forge's+/// own answer rather than anything `wt` derives — the first under a TTL, the+/// second a ratchet under a constant key — so no change to how `wt` computes+/// things can make them wrong.+///+/// `summary` is exempt on weaker grounds: its key is a hash of the diff, but+/// `SUMMARY_TEMPLATE` and `llm::prepare_diff`'s filtering sit downstream of+/// that hash, so rewording the prompt leaves every finished branch holding a+/// summary the old one wrote. It stays exempt because the value is+/// display-only and reaches no destructive decision, while rebuilding it is a+/// model call per branch. Closing that gap means hashing the rendered prompt,+/// not bumping this constant.+///+/// A new kind left off this list is discarded on a bump, which is the safe+/// direction: that costs a recomputation, while wrongly exempting one costs+/// the branch the stale answer is consulted about.+const UNVERSIONED_KINDS: &[&str] = &["summary", "ci-status", "pr-number"];++/// Cache roots whose epoch this process has already checked.+///+/// Keyed by path rather than held on the `Repository`, so the check covers a+/// second repository in the same process and stays inside this module.+static EPOCH_CHECKED: OnceLock<Mutex<HashSet<PathBuf>>> = OnceLock::new();++/// The root holding every cache kind for a repository.+fn cache_root(repo: &Repository) -> PathBuf {+ repo.wt_dir().join("cache")+}++/// Discard a repository's cache tree when it was written under a different+/// [`CACHE_EPOCH`], then stamp it with the current one.+///+/// Runs at most once per cache root per process, from [`cache_dir`] — the one+/// funnel every read and write passes through. `EPOCH_CHECKED`'s lock is held+/// across the removal, not just the bookkeeping, because `wt list` fans the+/// SHA-keyed reads over a thread pool and a worker that saw the root marked+/// mid-wipe would read the entries the wipe is there to discard. The stamp+/// goes when the cache does ([`clear_epoch`]): a cleared tree then re-stamps+/// on the next command at the cost of wiping nothing, and entries an older+/// worktrunk wrote into it meanwhile are discarded rather than trusted.+///+/// Best-effort, like the rest of this module, and asymmetric in its failures:+/// everything under the root is regenerable, so a failed removal leaves the+/// tree unstamped for the next process to retry, while a removal that succeeds+/// and then fails to stamp costs one more wipe per process until it lands.+fn ensure_epoch(repo: &Repository) {+ let root = cache_root(repo);+ // Held across the removal, not just the set insert: `wt list` fans+ // `has_added_changes_by_sha` out over a Rayon pool, and a worker that found+ // the root already marked while the wipe was still running would read the+ // entries it is there to discard.+ let mut checked = EPOCH_CHECKED+ .get_or_init(|| Mutex::new(HashSet::new()))+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ if checked.contains(&root) {+ return;+ }++ if read_json::<u32>(&epoch_stamp(&root)) != Some(CACHE_EPOCH) {+ match discard_governed_kinds(&root) {+ Ok(()) => stamp_epoch(repo),+ // Nothing better is available: the entries are undeletable, so+ // every read for the rest of this process gets the stale tree —+ // including the `has-added-changes` probe the epoch exists to+ // protect. Retrying per call would repeat the failure without+ // changing that. Left unstamped, so the next process tries again.+ Err(e) => {+ tracing::debug!(path = %root.display(), error = %e, "cache: failed to clear {} for epoch {}: {}", root.display(), CACHE_EPOCH, e);+ }+ }+ }+ checked.insert(root);+}++/// Remove every kind directory under `root` that [`CACHE_EPOCH`] governs.+///+/// Walks what is on disk rather than a list of known kinds, so a kind this+/// version no longer writes still goes; [`UNVERSIONED_KINDS`] is the exemption,+/// and anything else found is discarded. A missing root is nothing to do.+fn discard_governed_kinds(root: &Path) -> std::io::Result<()> {+ let entries = match fs::read_dir(root) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) => return Err(e),+ };+ // Accumulated with `and` rather than `?` or `try_fold`, both of which+ // stop at the first error: one undeletable directory would strand the+ // others, and which ones would follow `read_dir` order rather than+ // anything meaningful. Every kind is attempted, the first error returned.+ let mut outcome = Ok(());+ for entry in entries {+ let result = entry.and_then(|entry| {+ let name = entry.file_name();+ let exempt = name+ .to_str()+ .is_some_and(|name| UNVERSIONED_KINDS.contains(&name));+ if exempt || !entry.file_type()?.is_dir() {+ return Ok(());+ }+ fs::remove_dir_all(entry.path())+ });+ outcome = outcome.and(result);+ }+ outcome+}++/// The stamp naming the [`CACHE_EPOCH`] a cache tree was written under.+fn epoch_stamp(root: &Path) -> PathBuf {+ root.join(".epoch")+}++/// Record a repository's cache tree as written under the current+/// [`CACHE_EPOCH`], leaving its entries alone.+///+/// `ensure_epoch` calls this after discarding a tree from an older epoch.+/// A caller that puts entries in the tree itself — a test seeding what this+/// version would have produced — calls it beforehand, so the first read+/// doesn't sweep them as an older version's.+pub(crate) fn stamp_epoch(repo: &Repository) {+ write_json(&epoch_stamp(&cache_root(repo)), &CACHE_EPOCH);+}++/// Drop a repository's epoch stamp, as part of clearing its cache.+///+/// The stamp describes the tree's contents, so it belongs to them: left behind+/// over an emptied tree it would vouch for whatever lands there next,+/// including entries an older worktrunk writes before this one runs again.+///+/// Propagates like the other clear functions, so a stamp that can't be removed+/// fails the clear rather than leaving `wt config state cache clear` reporting+/// a tree it didn't finish clearing. The removal isn't counted as a cleared+/// entry — it is metadata, and its absence costs one wipe of an empty+/// directory.+pub fn clear_epoch(repo: &Repository) -> anyhow::Result<()> {+ clear_one(&epoch_stamp(&cache_root(repo))).map(|_| ())+}+/// The root directory for a named cache kind.////// Returns `<git-common-dir>/wt/cache/<kind>/`. All worktrunk caches live/// here; the `kind` is the subdirectory name (e.g. `"ci-status"`,/// `"summary"`, `"is-ancestor"`).+///+/// The first call per cache root in a process settles the tree's+/// `CACHE_EPOCH` (see `ensure_epoch`).pub fn cache_dir(repo: &Repository, kind: &str) -> PathBuf {- repo.wt_dir().join("cache").join(kind)+ ensure_epoch(repo);+ cache_root(repo).join(kind)}/// Read and deserialize a JSON cache entry.@@ -218,8 +394,61 @@ pub fn count_json_files(dir: &Path) -> usize {#[cfg(test)]mod tests {use super::*;+ use crate::testing::TestRepo;use tempfile::TempDir;+ /// The epoch's whole job is to answer "was this written by code that meant+ /// something else". A missing stamp is only the v0.78.0 case; every bump+ /// after this one turns on a stamp that disagrees, and on a matching stamp+ /// leaving entries where they are.+ #[test]+ fn test_epoch_discards_a_tree_stamped_by_another_version() {+ for (stamped, survives) in [+ (None, false),+ (Some(CACHE_EPOCH + 1), false),+ (Some(CACHE_EPOCH), true),+ ] {+ let test = TestRepo::new();+ let root = cache_root(&test.repo);+ // Seeded off `cache_root`, not `cache_dir`: that call is itself the+ // funnel, so seeding through it would sweep the tree first and+ // land both entries in one already discarded.+ let entry = root.join("has-added-changes").join("a-b.json");+ let exempt = root.join(UNVERSIONED_KINDS[0]).join("x.json");+ write_json(&entry, &true);+ write_json(&exempt, &true);++ let stamp = epoch_stamp(&root);+ match stamped {+ Some(epoch) => write_json(&stamp, &epoch),+ None => fs::remove_file(&stamp).unwrap(),+ }+ // `cache_dir` checks once per root per process, and `TestRepo`+ // stamped this root as it built it.+ EPOCH_CHECKED+ .get_or_init(|| Mutex::new(HashSet::new()))+ .lock()+ .unwrap()+ .remove(&root);++ let _ = cache_dir(&test.repo, "has-added-changes");+ assert_eq!(+ read_json::<bool>(&entry).is_some(),+ survives,+ "stamp {stamped:?} against epoch {CACHE_EPOCH}"+ );+ assert!(+ read_json::<bool>(&exempt).is_some(),+ "an unversioned kind survives any stamp, here {stamped:?}"+ );+ assert_eq!(+ read_json::<u32>(&epoch_stamp(&root)),+ Some(CACHE_EPOCH),+ "the tree is stamped current either way"+ );+ }+ }+#[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]struct V {x: u32,diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 8cd876f1b..6d2c14143 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -58,6 +58,14 @@//! it is a plain read. So a `clear` followed by the aggregate `get` shows the//! value gone, while the per-key `get` would re-resolve it.//!+//! One exception, and it is the cache's rather than this command's: every+//! cache read goes through `cache::cache_dir`, which discards entries an+//! older worktrunk wrote (`CACHE_EPOCH`). The first `get` after such an+//! upgrade therefore reports the git-command counts it left behind rather+//! than the ones it found. Nothing here can read past that without reporting+//! numbers the next command would invalidate anyway; the kinds that cost+//! something to rebuild are exempt from the discard.+//!//! # Log layout invariant//!//! Inside `wt_logs_dir()`, top-level *files* are shared logs (`commands.jsonl*`,@@ -1063,6 +1071,10 @@ pub fn handle_state_clear_all(yes: bool) -> anyhow::Result<()> {cleared_any |= clear_logs_reported(&repo)?;cleared_any |= clear_hints_reported(&repo)?;cleared_any |= clear_trash_reported(&repo)?;+ // Last, as in `handle_cache_clear`: the category clears above go through+ // `cache_dir`, which stamps. An emptied tree left stamped would vouch for+ // whatever lands in it next.+ worktrunk::cache::clear_epoch(&repo)?;if !cleared_any {eprintln!("{}", info_message("No stored state to clear"));@@ -1086,6 +1098,8 @@ pub fn handle_cache_clear() -> anyhow::Result<()> {cleared_any |= clear_summary_reported(&repo)?;cleared_any |= clear_git_commands_reported(&repo)?;cleared_any |= clear_hints_reported(&repo)?;+ // Last: the category clears above go through `cache_dir`, which stamps.+ worktrunk::cache::clear_epoch(&repo)?;if !cleared_any {eprintln!("{}", info_message("No cache to clear"));diff --git a/src/commands/picker/summary.rs b/src/commands/picker/summary.rsindex 18e8a8b97..27ba43a93 100644--- a/src/commands/picker/summary.rs+++ b/src/commands/picker/summary.rs@@ -175,10 +175,13 @@ mod tests {fn test_write_handles_unwritable_path() {use crate::summary::CachedSummary;let (_t, repo) = temp_repo();- // Block cache directory creation by placing a file where the directory should be+ // Block cache directory creation by placing a file where the directory+ // should be. `TestRepo` stamps the cache epoch, so the directory is+ // already there and has to go first.let wt_dir = repo.wt_dir();fs::create_dir_all(&wt_dir).unwrap();let cache_parent = wt_dir.join("cache");+ fs::remove_dir_all(&cache_parent).unwrap();fs::write(&cache_parent, "blocker").unwrap();let cached = CachedSummary {diff --git a/src/testing/mod.rs b/src/testing/mod.rsindex a5f48e11a..547b9e556 100644--- a/src/testing/mod.rs+++ b/src/testing/mod.rs@@ -1445,6 +1445,10 @@ impl TestRepo {let root = canonicalize(root).unwrap();let repo = Repository::at(&root).unwrap();write_local_test_config(&repo);+ // A test that seeds `.git/wt/cache/` by hand means entries this+ // version produced. Unstamped, the first read would discard them as an+ // older epoch's (`cache::ensure_epoch`).+ crate::cache::stamp_epoch(&repo);Self {temp_dir,diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 72a51f240..6dab8acf8 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -1505,6 +1505,14 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {!summary_feature_dir.exists(),"Summary cache dir for feature should be cleared");+ // The command re-stamps the epoch on its way through `cache_dir`, so the+ // drop has to come after the clears. A stamp left over an emptied tree+ // vouches for whatever lands there next, including entries an older+ // worktrunk writes before this one runs again.+ assert!(+ !git_dir.join("wt/cache/.epoch").exists(),+ "epoch stamp should not survive over an emptied cache tree"+ );assert!(!log_dir.exists());}@@ -1749,6 +1757,12 @@ fn test_state_cache_clear_with_entries(repo: TestRepo) {[32m✓[39m [32mCleared [1m1[22m git commands cache entry[39m[32m✓[39m [32mCleared [1m1[22m hint[39m");+ // Same invariant as `wt config state clear`: the emptied tree carries no+ // stamp, so an older worktrunk's entries aren't trusted on the way back.+ assert!(+ !git_dir.join("wt/cache/.epoch").exists(),+ "epoch stamp should not survive over an emptied cache tree"+ );}/// `cache clear` must leave authoritative state (markers, vars,diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 03cb643a2..2b4c1be4a 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1451,6 +1451,67 @@ fn test_remove_branch_only_unmerged_from_subdirectory_with_diff_relative(repo: T);}+/// The `has-added-changes` answer is keyed on the branch and target tips and+/// never expires, so on a finished branch it outlives the release that wrote+/// it. Releases through 0.78.0 wrote it from porcelain `git diff`, which under+/// `diff.relative` recorded a branch with changes outside the cwd as having+/// none — so moving the read to plumbing fixes nothing until that entry is+/// gone. The epoch stamp is what discards it.+#[rstest]+fn test_remove_branch_only_unmerged_ignores_cache_from_an_older_epoch(repo: TestRepo) {+ repo.run_git(&["switch", "--create", "feature-unmerged"]);+ fs::write(repo.root_path().join("feature.txt"), "new feature").unwrap();+ repo.run_git(&["add", "feature.txt"]);+ repo.run_git(&["commit", "--message", "Add feature"]);+ repo.run_git(&["checkout", "main"]);++ let sha = |rev: &str| {+ String::from_utf8(+ repo.git_command()+ .args(["rev-parse", rev])+ .run()+ .unwrap()+ .stdout,+ )+ .unwrap()+ .trim()+ .to_string()+ };+ // What 0.78.0 left behind: the poisoned answer, and no epoch stamp.+ let cache = repo.root_path().join(".git/wt/cache");+ fs::create_dir_all(cache.join("has-added-changes")).unwrap();+ fs::write(+ cache.join("has-added-changes").join(format!(+ "{}-{}.json",+ sha("feature-unmerged"),+ sha("main")+ )),+ "false",+ )+ .unwrap();+ fs::remove_file(cache.join(".epoch")).unwrap();++ let output = make_snapshot_cmd(&repo, "remove", &["feature-unmerged"], None)+ .output()+ .unwrap();++ let branch = repo+ .git_command()+ .args([+ "rev-parse",+ "--verify",+ "--quiet",+ "refs/heads/feature-unmerged",+ ])+ .run()+ .unwrap();+ assert!(+ branch.status.success(),+ "unmerged branch must survive a pre-epoch cache; wt remove said: {}",+ String::from_utf8_lossy(&output.stderr)+ );+}+#[rstest]fn test_remove_branch_only_force_delete(repo: TestRepo) {// Create a branch with a unique commit (not in main)