Skip to content

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

docs: share project instructions through AGENTS.md (#4245)

Maximilian Roos650263036653
diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md
index 999cce396..44470abfd 100644
--- a/.claude/skills/release/SKILL.md
+++ b/.claude/skills/release/SKILL.md
@@ -89,7 +89,7 @@ Give each a distinct charter. At least two receive no grep and no keyword list,
### Analyze: adjudicate each candidate
-Pool the candidates, dedupe, and analyze each against the data-safety invariants in `CLAUDE.md` and the FAQ "What can Worktrunk delete?" inventory: does it preserve data on failure, require explicit consent for destructive ops, and avoid silent side-effect deletion? Mark each real risk / acceptable / needs change, with the reasoning.
+Pool the candidates, dedupe, and analyze each against the data-safety invariants in `AGENTS.md` and the FAQ "What can Worktrunk delete?" inventory: does it preserve data on failure, require explicit consent for destructive ops, and avoid silent side-effect deletion? Mark each real risk / acceptable / needs change, with the reasoning.
Surface the full adjudicated list and get explicit sign-off before tagging. Do not tag a release with an unresolved deletion-surface candidate, even if it looks acceptable.
@@ -325,11 +325,11 @@ Recommendation: Minor release (0.3.0) — new features, no breaking changes
- **Second digit** (0.1.0 → 0.2.0): Backward incompatible changes
- **Third digit** (0.1.0 → 0.1.1): Everything else
-Current project status: maturing mode (see [CLAUDE.md › Project Status](../../../CLAUDE.md)). External interfaces — the config file format (`wt.toml`, user config) and CLI flags/arguments — carry compatibility weight, so breaks there need justification (a real improvement, not cleanup) and prefer deprecation warnings over silent breaks. Everything else, including the internal and library APIs, stays flexible: worktrunk ships breaking library changes freely and bumps the version each time, putting no weight on the existing internal APIs.
+Current project status: maturing mode (see [AGENTS.md › Project Status](../../../AGENTS.md)). External interfaces — the config file format (`wt.toml`, user config) and CLI flags/arguments — carry compatibility weight, so breaks there need justification (a real improvement, not cleanup) and prefer deprecation warnings over silent breaks. Everything else, including the internal and library APIs, stays flexible: worktrunk ships breaking library changes freely and bumps the version each time, putting no weight on the existing internal APIs.
## Library API Compatibility
-Worktrunk is a CLI tool. The `[lib]` crate in `Cargo.toml` does expose a public API, but it is **not a compatibility surface** — per [CLAUDE.md › Project Status](../../../CLAUDE.md) there are no Rust library compatibility concerns, and the project ships breaking library changes freely, bumping the version each time (see the "Breaking library API" entries in `CHANGELOG.md`). Downstream crates are expected to pin.
+Worktrunk is a CLI tool. The `[lib]` crate in `Cargo.toml` does expose a public API, but it is **not a compatibility surface** — per [AGENTS.md › Project Status](../../../AGENTS.md) there are no Rust library compatibility concerns, and the project ships breaking library changes freely, bumping the version each time (see the "Breaking library API" entries in `CHANGELOG.md`). Downstream crates are expected to pin.
`cargo-semver-checks` is therefore an **advisory bump-level input**, not a gate that commits us to keeping the API stable for downstream crates. It compares the current public API against the last version published to crates.io and reports semver-relevant changes — a useful signal for choosing the bump:
diff --git a/.claude/skills/running-tend/SKILL.md b/.claude/skills/running-tend/SKILL.md
index 518df8b88..8427ac55f 100644
--- a/.claude/skills/running-tend/SKILL.md
+++ b/.claude/skills/running-tend/SKILL.md
@@ -46,7 +46,7 @@ If codecov fails **locally**, investigate with `task coverage` and
Don't try to `cargo install` them in the sandbox — past attempts at
source-compiling installs cascaded into bash-tool interrupts that blocked
even `pwd` and `echo`. Instead, query Codecov directly, following
-`tests/CLAUDE.md` → **Coverage Investigation** for the endpoints and their
+`tests/AGENTS.md` → **Coverage Investigation** for the endpoints and their
traps. The scratch paths there and below go to `${TMPDIR:-/tmp}` — write new
ones the same way.
@@ -146,7 +146,7 @@ benefit — the maintainer can rerun the failed job directly once `benchmarks`
clears, or merge regardless if the failure is clearly a flake.
The codecov-failure dismissal pattern is different and remains correct:
-`CLAUDE.md` requires explicit user approval before merging with failing
+`AGENTS.md` requires explicit user approval before merging with failing
`codecov/patch`, so dismissing the approval until the coverage gap is
addressed is intentional.
diff --git a/.claude/skills/running-tend/references/nightly-cleaner.md b/.claude/skills/running-tend/references/nightly-cleaner.md
index a31e78128..a35128ad0 100644
--- a/.claude/skills/running-tend/references/nightly-cleaner.md
+++ b/.claude/skills/running-tend/references/nightly-cleaner.md
@@ -4,7 +4,7 @@
For each `.rs` file in the survey, also check:
-- **System docstring** — modules with cached state, coordination logic, or non-obvious invariants need a spec docstring (see CLAUDE.md "System Docstrings"). Flag if missing or stale.
+- **System docstring** — modules with cached state, coordination logic, or non-obvious invariants need a spec docstring (see AGENTS.md "System Docstrings"). Flag if missing or stale.
## Branch Naming
diff --git a/.claude/skills/running-tend/references/review-pr.md b/.claude/skills/running-tend/references/review-pr.md
index 4ff76dd41..f44786395 100644
--- a/.claude/skills/running-tend/references/review-pr.md
+++ b/.claude/skills/running-tend/references/review-pr.md
@@ -46,11 +46,11 @@ On a match:
**Testing:**
-- Do the tests follow the project's testing conventions (see tests/CLAUDE.md)?
+- Do the tests follow the project's testing conventions (see tests/AGENTS.md)?
-**CLAUDE.md compliance:**
+**AGENTS.md compliance:**
-- Review the CLAUDE.md sections relevant to the changed code and flag
+- Review the AGENTS.md sections relevant to the changed code and flag
deviations — code quality, error handling, command execution, data safety,
system docstrings, etc.
diff --git a/.config/clawpatch/features/feat_custom_approval_gate.json b/.config/clawpatch/features/feat_custom_approval_gate.json
index b98c71dc3..fc14e0951 100644
--- a/.config/clawpatch/features/feat_custom_approval_gate.json
+++ b/.config/clawpatch/features/feat_custom_approval_gate.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_approval_gate",
"title": "Project-command approval gate and command execution",
- "summary": "Worktrunk runs arbitrary project-defined hook commands, alias steps, and --execute bodies. These must only run after the approval gate (`Approvals` + `approve_command_batch` / `approve_or_skip`) clears them. Bypassing the gate = remote code execution on `wt switch`. Also handles signal-derived child exits (Ctrl-C must abort, not get swallowed by `FailureStrategy::Warn`). See CLAUDE.md > Project Commands Run Only After Approval and Signal Handling.",
+ "summary": "Worktrunk runs arbitrary project-defined hook commands, alias steps, and --execute bodies. These must only run after the approval gate (`Approvals` + `approve_command_batch` / `approve_or_skip`) clears them. Bypassing the gate = remote code execution on `wt switch`. Also handles signal-derived child exits (Ctrl-C must abort, not get swallowed by `FailureStrategy::Warn`). See AGENTS.md > Project Commands Run Only After Approval and Signal Handling.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -54,7 +54,7 @@
"reason": "child process spawning"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "approval gate and signal handling invariants"
}
],
diff --git a/.config/clawpatch/features/feat_custom_approvals_storage.json b/.config/clawpatch/features/feat_custom_approvals_storage.json
index fcb9ac5d0..7398ac79f 100644
--- a/.config/clawpatch/features/feat_custom_approvals_storage.json
+++ b/.config/clawpatch/features/feat_custom_approvals_storage.json
@@ -34,7 +34,7 @@
"reason": "config path resolution"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "Project Commands Run Only After Approval"
}
],
diff --git a/.config/clawpatch/features/feat_custom_config_deprecation.json b/.config/clawpatch/features/feat_custom_config_deprecation.json
index 34816c56d..5104aaa4e 100644
--- a/.config/clawpatch/features/feat_custom_config_deprecation.json
+++ b/.config/clawpatch/features/feat_custom_config_deprecation.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_config_deprecation",
"title": "Config loading, deprecation, and migration",
- "summary": "Pre-deserialization TOML migration rewrites deprecated patterns into canonical form. A silent migration bug here changes user-facing behavior without warning. Must: emit warnings exactly once per process, never drop unknown keys silently, and produce a stable .new file. Config format is an external interface (CLAUDE.md > Project Status). See CLAUDE.md > Config Deprecation.",
+ "summary": "Pre-deserialization TOML migration rewrites deprecated patterns into canonical form. A silent migration bug here changes user-facing behavior without warning. Must: emit warnings exactly once per process, never drop unknown keys silently, and produce a stable .new file. Config format is an external interface (AGENTS.md > Project Status). See AGENTS.md > Config Deprecation.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -50,7 +50,7 @@
"reason": "approvals config schema"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "config compatibility policy and deprecation recipe"
}
],
diff --git a/.config/clawpatch/features/feat_custom_hook_logs.json b/.config/clawpatch/features/feat_custom_hook_logs.json
index dc41e3ab9..d8e621629 100644
--- a/.config/clawpatch/features/feat_custom_hook_logs.json
+++ b/.config/clawpatch/features/feat_custom_hook_logs.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_hook_logs",
"title": "Hook output logs: filename sanitization and log-path layout",
- "summary": "Hook stdout/stderr is persisted under `.git/wt/logs/` with per-branch and repo-wide paths. Branch names and hook names flow into filesystem paths through `sanitize_for_filename`; a sanitization gap (path separators, `..`, absolute prefixes, reserved Windows device names) means a crafted branch name could write or truncate files outside the logs tree. The top-level file-vs-directory split must stay consistent or `wt config state` mis-walks it. See CLAUDE.md > Hook Output Logs.",
+ "summary": "Hook stdout/stderr is persisted under `.git/wt/logs/` with per-branch and repo-wide paths. Branch names and hook names flow into filesystem paths through `sanitize_for_filename`; a sanitization gap (path separators, `..`, absolute prefixes, reserved Windows device names) means a crafted branch name could write or truncate files outside the logs tree. The top-level file-vs-directory split must stay consistent or `wt config state` mis-walks it. See AGENTS.md > Hook Output Logs.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -30,7 +30,7 @@
],
"contextFiles": [
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "Hook Output Logs section: log layout and sanitize_for_filename rule"
},
{
diff --git a/.config/clawpatch/features/feat_custom_merge_safety.json b/.config/clawpatch/features/feat_custom_merge_safety.json
index 1ebffd703..88687a4d7 100644
--- a/.config/clawpatch/features/feat_custom_merge_safety.json
+++ b/.config/clawpatch/features/feat_custom_merge_safety.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_merge_safety",
"title": "wt merge: data safety, rebase, and worktree cleanup",
- "summary": "The `wt merge` command lands a feature branch onto the target, runs the rebase, performs cleanup of the merged worktree, and runs pre-/post-merge hooks. Critical data-safety surface: a failed merge must not silently discard uncommitted work, and cleanup must not run before approval. See CLAUDE.md > Data Safety and Project Commands Run Only After Approval.",
+ "summary": "The `wt merge` command lands a feature branch onto the target, runs the rebase, performs cleanup of the merged worktree, and runs pre-/post-merge hooks. Critical data-safety surface: a failed merge must not silently discard uncommitted work, and cleanup must not run before approval. See AGENTS.md > Data Safety and Project Commands Run Only After Approval.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -50,7 +50,7 @@
"reason": "dirty/clean detection"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "data safety + approval gate invariants"
}
],
diff --git a/.config/clawpatch/features/feat_custom_network_boundary.json b/.config/clawpatch/features/feat_custom_network_boundary.json
index b94335dfd..7eac38b6b 100644
--- a/.config/clawpatch/features/feat_custom_network_boundary.json
+++ b/.config/clawpatch/features/feat_custom_network_boundary.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_network_boundary",
"title": "Local-first network-access boundary",
- "summary": "Worktrunk is local-first: the network is touched only when the user asked for it. The audit keys on the calling command, not a fixed blocklist — an egress (`git fetch`, `git ls-remote`, `gh`, `glab`, `az`, HTTP) is a violation when it sits in a fast command or a synchronous hot path (a shell prompt) that cannot absorb the latency, or in a background TTL-cache refresh. A foreground command the user runs and waits on may reach the wire for the activity it was asked to perform, and must still paint its first frame from local data — network-derived detail streams in behind it. Sanctioned activities: CI status (`wt list --full`, `wt list statusline`, and plain `wt list` when `[list] columns` names `ci`); the interactive `wt switch` picker, the most forgiving home for forge data because its lifetime is bounded by the user rather than the job — per-row CI status, the per-row `gh pr view --json comments` / `glab api …/notes` that fills a row's `comments` tab, and the `gh pr list` / `glab mr list` plus per-row previews behind `wt switch --prs`; branch-summary and commit-message generation (`commit.generation` commands); PR/MR resolution (`wt switch pr:`/`mr:`); and the `wt config show --full` version check; plus the one detection-helper exception — the first `Repository::default_branch()` per repo may fall through to `git ls-remote`, caching into `worktrunk.default-branch`. Silent lookup fallthroughs (alias dispatch, hook context build, recovery) must stay local. See CLAUDE.md > Network Access.",
+ "summary": "Worktrunk is local-first: the network is touched only when the user asked for it. The audit keys on the calling command, not a fixed blocklist — an egress (`git fetch`, `git ls-remote`, `gh`, `glab`, `az`, HTTP) is a violation when it sits in a fast command or a synchronous hot path (a shell prompt) that cannot absorb the latency, or in a background TTL-cache refresh. A foreground command the user runs and waits on may reach the wire for the activity it was asked to perform, and must still paint its first frame from local data — network-derived detail streams in behind it. Sanctioned activities: CI status (`wt list --full`, `wt list statusline`, and plain `wt list` when `[list] columns` names `ci`); the interactive `wt switch` picker, the most forgiving home for forge data because its lifetime is bounded by the user rather than the job — per-row CI status, the per-row `gh pr view --json comments` / `glab api …/notes` that fills a row's `comments` tab, and the `gh pr list` / `glab mr list` plus per-row previews behind `wt switch --prs`; branch-summary and commit-message generation (`commit.generation` commands); PR/MR resolution (`wt switch pr:`/`mr:`); and the `wt config show --full` version check; plus the one detection-helper exception — the first `Repository::default_branch()` per repo may fall through to `git ls-remote`, caching into `worktrunk.default-branch`. Silent lookup fallthroughs (alias dispatch, hook context build, recovery) must stay local. See AGENTS.md > Network Access.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -46,7 +46,7 @@
"reason": "alias dispatch must resolve locally, no fallthrough to the wire"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "Network Access policy and the default_branch detection-helper exception"
}
],
diff --git a/.config/clawpatch/features/feat_custom_performance.json b/.config/clawpatch/features/feat_custom_performance.json
index fce69b8ef..9e4c33e11 100644
--- a/.config/clawpatch/features/feat_custom_performance.json
+++ b/.config/clawpatch/features/feat_custom_performance.json
@@ -42,11 +42,11 @@
"reason": "[wt-trace] timing instrumentation"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "Benchmarks & Traces; Repository Caching"
},
{
- "path": "benches/CLAUDE.md",
+ "path": "benches/AGENTS.md",
"reason": "benchmark filter map and expected numbers"
}
],
diff --git a/.config/clawpatch/features/feat_custom_prune.json b/.config/clawpatch/features/feat_custom_prune.json
index 509d689a4..8b3338adf 100644
--- a/.config/clawpatch/features/feat_custom_prune.json
+++ b/.config/clawpatch/features/feat_custom_prune.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_prune",
"title": "wt step prune: worktree pruning and concurrent .git/config safety",
- "summary": "`wt step prune` scans worktrees and orphan branches and removes stale ones. As a destructive operation it must require explicit consent for force-removal, must not discard uncommitted or untracked work, and runs pre/post-remove hooks only after the approval gate clears them. Concurrent `git worktree` mutations race on `.git/config` (the Windows prune race, issue #2801) so pruning must tolerate or serialize that. Complements feat_custom_remove, which covers `wt remove` and the picker. See CLAUDE.md > Data Safety.",
+ "summary": "`wt step prune` scans worktrees and orphan branches and removes stale ones. As a destructive operation it must require explicit consent for force-removal, must not discard uncommitted or untracked work, and runs pre/post-remove hooks only after the approval gate clears them. Concurrent `git worktree` mutations race on `.git/config` (the Windows prune race, issue #2801) so pruning must tolerate or serialize that. Complements feat_custom_remove, which covers `wt remove` and the picker. See AGENTS.md > Data Safety.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -38,7 +38,7 @@
"reason": "ApprovedHookPlan: prune is a gate-then-mutate operation"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "Data Safety invariants"
}
],
diff --git a/.config/clawpatch/features/feat_custom_remove.json b/.config/clawpatch/features/feat_custom_remove.json
index cff816d16..884618a1f 100644
--- a/.config/clawpatch/features/feat_custom_remove.json
+++ b/.config/clawpatch/features/feat_custom_remove.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_remove",
"title": "wt remove and picker-driven removal: data-loss surface",
- "summary": "Worktree removal is the highest-stakes destructive operation. Force-remove must require explicit user consent; cleanup must not silently discard uncommitted changes or untracked files. Race conditions between safety checks and the actual delete must fail closed (retain data). The picker also routes alt-r through handle_remove_output - must consult approvals read-only and skip rather than prompt mid-render. See CLAUDE.md > Data Safety, Time-of-check vs time-of-use.",
+ "summary": "Worktree removal is the highest-stakes destructive operation. Force-remove must require explicit user consent; cleanup must not silently discard uncommitted changes or untracked files. Race conditions between safety checks and the actual delete must fail closed (retain data). The picker also routes alt-r through handle_remove_output - must consult approvals read-only and skip rather than prompt mid-render. See AGENTS.md > Data Safety, Time-of-check vs time-of-use.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -50,7 +50,7 @@
"reason": "documented destructive surface"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "data safety invariants"
}
],
diff --git a/.config/clawpatch/features/feat_custom_repo_cache.json b/.config/clawpatch/features/feat_custom_repo_cache.json
index 9eb39d4bb..58da84b38 100644
--- a/.config/clawpatch/features/feat_custom_repo_cache.json
+++ b/.config/clawpatch/features/feat_custom_repo_cache.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_repo_cache",
"title": "Repository caching invariants and worktree list mutation",
- "summary": "Repository<Arc<RepoCache>> caches read-only values to avoid re-querying git. Mutating paths (switch --create / remove) must NOT read list_worktrees() through the same Repository after their own mutation - cache is now stale. Per CLAUDE.md, dirty/HEAD must NOT be cached. Stale cache reads here surface as missing worktrees or wrong commit in hook template vars.",
+ "summary": "Repository<Arc<RepoCache>> caches read-only values to avoid re-querying git. Mutating paths (switch --create / remove) must NOT read list_worktrees() through the same Repository after their own mutation - cache is now stale. Per AGENTS.md, dirty/HEAD must NOT be cached. Stale cache reads here surface as missing worktrees or wrong commit in hook template vars.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -58,7 +58,7 @@
"reason": "mutating caller (remove)"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "caching contract"
}
],
diff --git a/.config/clawpatch/features/feat_custom_signal_handling.json b/.config/clawpatch/features/feat_custom_signal_handling.json
index 8c84fa856..3eb44e3fe 100644
--- a/.config/clawpatch/features/feat_custom_signal_handling.json
+++ b/.config/clawpatch/features/feat_custom_signal_handling.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_signal_handling",
"title": "Signal handling: Ctrl-C aborts every child-process loop",
- "summary": "wt installs a signal_hook SIGINT/SIGTERM handler that forwards signals to child process groups, so wt itself does not die from the user's Ctrl-C, only the current child does. Every foreground loop that runs multiple child processes (`wt step for-each`, hook pipelines, alias steps, concurrent groups) MUST abort on a signal-derived child exit instead of charging into the next iteration: otherwise one Ctrl-C against `wt merge` runs the remaining hook steps, with FailureStrategy::Warn silently swallowing each interrupt. Detect via `err.interrupt_signal()` (the worktrunk::git::ErrorExt trait); the check happens before any FailureStrategy branch. The structured channel is WorktrunkError::ChildProcessExited { signal }, never sniff code >= 128. See CLAUDE.md > Signal Handling.",
+ "summary": "wt installs a signal_hook SIGINT/SIGTERM handler that forwards signals to child process groups, so wt itself does not die from the user's Ctrl-C, only the current child does. Every foreground loop that runs multiple child processes (`wt step for-each`, hook pipelines, alias steps, concurrent groups) MUST abort on a signal-derived child exit instead of charging into the next iteration: otherwise one Ctrl-C against `wt merge` runs the remaining hook steps, with FailureStrategy::Warn silently swallowing each interrupt. Detect via `err.interrupt_signal()` (the worktrunk::git::ErrorExt trait); the check happens before any FailureStrategy branch. The structured channel is WorktrunkError::ChildProcessExited { signal }, never sniff code >= 128. See AGENTS.md > Signal Handling.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -34,7 +34,7 @@
"reason": "Cmd: spawns children into the process groups the signal handler forwards to"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "Signal Handling policy: every child-process loop aborts on a signal"
}
],
diff --git a/.config/clawpatch/features/feat_custom_switch_resolve.json b/.config/clawpatch/features/feat_custom_switch_resolve.json
index cab6798a5..9d837446b 100644
--- a/.config/clawpatch/features/feat_custom_switch_resolve.json
+++ b/.config/clawpatch/features/feat_custom_switch_resolve.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_switch_resolve",
"title": "wt switch + branch resolution: ref-injection, PR fetching, network policy",
- "summary": "`wt switch` resolves user-supplied references (branch names, pr:N, mr:N, gh URLs) and may create worktrees. Branch names can contain hyphens, slashes, special chars — must be passed to git without interpretation as flags. PR/MR fetch is the one place where shelling out to `gh`/`glab` is allowed and must not happen on background paths. See CLAUDE.md > Network Access policy and Worktree Model.",
+ "summary": "`wt switch` resolves user-supplied references (branch names, pr:N, mr:N, gh URLs) and may create worktrees. Branch names can contain hyphens, slashes, special chars — must be passed to git without interpretation as flags. PR/MR fetch is the one place where shelling out to `gh`/`glab` is allowed and must not happen on background paths. See AGENTS.md > Network Access policy and Worktree Model.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -66,7 +66,7 @@
"reason": "post-switch hook invocation"
},
{
- "path": "CLAUDE.md",
+ "path": "AGENTS.md",
"reason": "network policy, branch name handling"
}
],
diff --git a/.config/nextest.toml b/.config/nextest.toml
index c47be1a1d..5410536b4 100644
--- a/.config/nextest.toml
+++ b/.config/nextest.toml
@@ -8,7 +8,7 @@ nextest-version = "0.9.118"
# run this same suite and would silently disagree. Environment belongs in the
# hermetic latch (`shell_exec::enable_hermetic_test_env`) and
# `.cargo/config.toml`, behavior in the fixture. See
-# tests/CLAUDE.md → One Result Per Test, Whatever Runs It.
+# tests/AGENTS.md → One Result Per Test, Whatever Runs It.
[profile.default]
slow-timeout = { period = "180s", terminate-after = 1 }
diff --git a/.config/tend.yaml b/.config/tend.yaml
index f2d9fccb7..df2bfda2f 100644
--- a/.config/tend.yaml
+++ b/.config/tend.yaml
@@ -4,7 +4,7 @@ setup:
# tend 0.2.14 deprecated `sandbox_setup:` and runs its commands as an ordinary
# `runner` step after `setup:`; the agent then sees what they install through a
# copy-on-write view of the job's home (see "Sandbox toolchain" in
-# .github/CLAUDE.md). #4222 kept the key so a release reverting 0.2.14 would
+# .github/AGENTS.md). #4222 kept the key so a release reverting 0.2.14 would
# still find it, so this block outliving its original rationale is deliberate,
# not drift.
#
@@ -22,7 +22,7 @@ setup:
sandbox_setup:
- mkdir -p ~/.local/bin
- uv tool install --quiet pre-commit
-- 'for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done'
+- 'for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done'
secrets:
allowed:
- CODECOV_TOKEN
diff --git a/.github/AGENTS.md b/.github/AGENTS.md
new file mode 100644
index 000000000..f293f2a8f
--- /dev/null
+++ b/.github/AGENTS.md
@@ -0,0 +1,134 @@
+# CI Automation — Worktrunk
+
+See [tend's security model](https://github.com/max-sixty/tend/blob/main/docs/security-model.md)
+for the generic security model. This file documents worktrunk-specific
+configuration.
+
+## Bot identity
+
+`worktrunk-bot` — a regular GitHub user account (PAT-based, not a GitHub App).
+Workflows check `user.login == 'worktrunk-bot'` directly.
+
+## Tokens
+
+| Token | Purpose | Stored in |
+|-------|---------|-----------|
+| `TEND_BOT_TOKEN` | Every workflow acting as `worktrunk-bot`, including the winget and Homebrew publish jobs | `tend` and `release` environments |
+| `CLAUDE_CODE_OAUTH_TOKEN` | Authenticates Claude Code to the Anthropic API | `tend` environment |
+| `CODECOV_TOKEN` | Uploads coverage from `ci.yaml` and `coverage.yaml` | repo level, allowlisted in `.config/tend.yaml` |
+
+## Merge restriction
+
+Only the repo owner (`@max-sixty`, admin) can merge to `main`.
+`worktrunk-bot` has `write` role only. Enforced by a "Merge access" ruleset
+(restrict updates, admin bypass in exempt mode). Required status checks:
+`test (linux)`, `test (macos)`, `test (windows)`, `fast-checks`.
+
+## Environment protection
+
+Every secret except `CODECOV_TOKEN` lives in a GitHub Environment, where no
+other workflow the repo runs can read it. A coverage upload grants nothing
+worth gating. Each environment holds what one phase needs, since a job that
+joins an environment can read every secret in it:
+
+| Environment | Admits | Secret | Read by |
+|-------------|--------|--------|---------|
+| `tend` | `main` | `CLAUDE_CODE_OAUTH_TOKEN`, `TEND_BOT_TOKEN` | every `tend-*.yaml` job except `relay`; `append-gist`; both `create-issue-on-*-failure` jobs |
+| `release` | any tag | `AUR_SSH_PRIVATE_KEY`, `TEND_BOT_TOKEN` | `publish-aur`, `publish-winget`, `publish-homebrew` |
+| `signing` | any tag | `SIGNPATH_API_TOKEN` | `build-local-artifacts` |
+| `github-pages` | `main` | none — OIDC only | `deploy-docs` |
+
+The deployment branch policy is the gate: a job naming an environment runs
+only from a ref the policy admits, so a workflow pushed to a feature branch is
+refused before its first step. `worktrunk-bot` can push branches but cannot
+update `main` (the "Merge access" ruleset) or move tags (the "Tag operations"
+ruleset, admin-only), which is what makes both admitted sets unreachable to
+it. No environment has a reviewer rule, so joining a job to one costs no
+approval step.
+
+The tag policies admit every tag rather than a `v*` pattern. "Tag operations"
+covers `~ALL` tags, so the pattern carries no part of the gate — it only
+duplicates `release.yaml`'s own tag filter, and the two are easy to drift
+apart. They already had: the workflow fires on `**[0-9]+.[0-9]+.[0-9]+*`,
+which matches an unprefixed `1.2.3` that a `v*` policy would then refuse. A
+release cut under that name would have stopped at `build-local-artifacts`,
+which names `signing` and waits only on `plan` — before an artifact was built,
+let alone published.
+
+`TEND_BOT_TOKEN` is stored in two environments rather than shared, because a
+policy admits branches or tags but the token is needed under both: the bot's
+own workflows run on `main`, the publish jobs on a tag. Adding the tag to
+`tend` is not an option — `tend check` pins that policy to exactly the
+protected branches and its `--fix` deletes anything else.
+
+Jobs name `tend` as `{name: tend, deployment: false}`. GitHub files a
+deployment record for every job that names an environment, against whatever
+ref the run belongs to — under `pull_request_target` that is the pull request
+itself, so an omission posts a "worktrunk-bot deployed to tend" line on every
+push to every PR. `deployment: false` drops the record and keeps the gate. The
+release jobs keep their records: a tag-push deployment lands in no PR
+timeline, and it reads as what it is.
+
+The generated `tend-*.yaml` files carry the same `{name: tend, deployment:
+false}`, written by tend's generator rather than edited here — every `uvx
+tend@latest init` overwrites them, so a hand edit would not survive one. tend
+0.1.14 added the field and #3749 landed the regen, which is what cleared `tend
+check`'s `environment-deployments`.
+
+crates.io publishing holds no stored token — it uses Trusted Publishing.
+crates.io mints a short-lived one only for an OIDC claim from `release.yaml`
+running in that same `release` environment.
+
+## Sandbox toolchain
+
+The agent runs as `tend-sandbox`, but from tend 0.2.14 it works through a
+copy-on-write view of the job's own checkout and home rather than a tree of
+its own: `$HOME` is `/home/runner`, the cwd is the runner's checkout, and what
+`setup:` installed is on PATH at the path it was installed to. Writes stay
+inside the view, so nothing the agent writes reaches the runner or a later
+step. A tool `tend-setup` installs anywhere the runner can reach is therefore a
+tool the agent has, and no hand-off is needed to carry it across.
+
+That replaced the arrangement 0.2.5–0.2.13 ran under, where the agent had a
+home of its own, tend rewrote a leading `/home/runner` out of its PATH, and the
+Sandbox Runtime denied reads across the runner's home and checkout. Machinery
+this repo built for that is still in place and still runs, now as a second copy
+rather than as the route:
+
+- `tend-setup` `sudo install`s `cargo-insta` and `cargo-nextest` into
+ `/usr/local/bin`. Both also resolve from `$HOME/.cargo-install/<crate>/bin`,
+ which comes first on the agent's PATH.
+- `.config/tend.yaml`'s `sandbox_setup:` installs `pre-commit`, which
+ `tend-setup` installs too. 0.2.14 deprecated the key and runs its commands as
+ an ordinary `runner` step after `setup:`; #4222 kept it so a release
+ reverting 0.2.14 would still find it. Its closing probe still earns its place
+ — it asserts the four tools the pre-merge gate needs, whichever step
+ installed them, plus `nix` for the weekly toolchain bump.
+
+Being on PATH gets the *binary* across, not what it talks to. `nix` resolves
+for the agent but cannot reach the daemon: `socket(AF_UNIX, …)` is blocked, so
+`nix store info` fails with "Address family not supported by protocol" and the
+weekly `flake.lock` refresh needs an upstream lever (max-sixty/tend#1197).
+`command -v` can't see that distinction, which is why the probe stays green
+while the weekly job would not.
+
+## Build environment
+
+`Swatinem/rust-cache` hashes `CARGO*` and `RUST*` env vars into the cache key.
+All workflows sharing a cache must set the same env vars, or they'll get
+different keys and miss each other's caches.
+
+It hashes the vars **visible at its own step**, so a var exported by a later
+step is invisible and a var the writers don't set poisons the key. ci.yaml and
+nightly.yaml carry theirs in a workflow-level `env:` block, always in place
+first. A miss is silent — the step succeeds having restored nothing — so drift
+here shows up only as slow jobs.
+
+The `tend-*.yaml` workflows are out of this scheme: they can't carry a
+workflow-level `env:` block, so `tend-setup` restores nothing, sets none of the
+three vars, and tend sessions compile cold. What forced that between tend 0.2.5
+and 0.2.13 — the agent building in a disposable `/tmp` clone, where a cache
+restored into the runner's checkout and home was both unreachable and at the
+wrong path — no longer holds, because 0.2.14 put the agent on the job's own
+checkout and home. Whether a restore now pays for itself is a measurement
+against the download cost in all eight workflows (max-sixty/tend#1198).
diff --git a/.github/CLAUDE.md b/.github/CLAUDE.md
index f293f2a8f..43c994c2d 100644
--- a/.github/CLAUDE.md
+++ b/.github/CLAUDE.md
@@ -1,134 +1 @@
-# CI Automation — Worktrunk
-
-See [tend's security model](https://github.com/max-sixty/tend/blob/main/docs/security-model.md)
-for the generic security model. This file documents worktrunk-specific
-configuration.
-
-## Bot identity
-
-`worktrunk-bot` — a regular GitHub user account (PAT-based, not a GitHub App).
-Workflows check `user.login == 'worktrunk-bot'` directly.
-
-## Tokens
-
-| Token | Purpose | Stored in |
-|-------|---------|-----------|
-| `TEND_BOT_TOKEN` | Every workflow acting as `worktrunk-bot`, including the winget and Homebrew publish jobs | `tend` and `release` environments |
-| `CLAUDE_CODE_OAUTH_TOKEN` | Authenticates Claude Code to the Anthropic API | `tend` environment |
-| `CODECOV_TOKEN` | Uploads coverage from `ci.yaml` and `coverage.yaml` | repo level, allowlisted in `.config/tend.yaml` |
-
-## Merge restriction
-
-Only the repo owner (`@max-sixty`, admin) can merge to `main`.
-`worktrunk-bot` has `write` role only. Enforced by a "Merge access" ruleset
-(restrict updates, admin bypass in exempt mode). Required status checks:
-`test (linux)`, `test (macos)`, `test (windows)`, `fast-checks`.
-
-## Environment protection
-
-Every secret except `CODECOV_TOKEN` lives in a GitHub Environment, where no
-other workflow the repo runs can read it. A coverage upload grants nothing
-worth gating. Each environment holds what one phase needs, since a job that
-joins an environment can read every secret in it:
-
-| Environment | Admits | Secret | Read by |
-|-------------|--------|--------|---------|
-| `tend` | `main` | `CLAUDE_CODE_OAUTH_TOKEN`, `TEND_BOT_TOKEN` | every `tend-*.yaml` job except `relay`; `append-gist`; both `create-issue-on-*-failure` jobs |
-| `release` | any tag | `AUR_SSH_PRIVATE_KEY`, `TEND_BOT_TOKEN` | `publish-aur`, `publish-winget`, `publish-homebrew` |
-| `signing` | any tag | `SIGNPATH_API_TOKEN` | `build-local-artifacts` |
-| `github-pages` | `main` | none — OIDC only | `deploy-docs` |
-
-The deployment branch policy is the gate: a job naming an environment runs
-only from a ref the policy admits, so a workflow pushed to a feature branch is
-refused before its first step. `worktrunk-bot` can push branches but cannot
-update `main` (the "Merge access" ruleset) or move tags (the "Tag operations"
-ruleset, admin-only), which is what makes both admitted sets unreachable to
-it. No environment has a reviewer rule, so joining a job to one costs no
-approval step.
-
-The tag policies admit every tag rather than a `v*` pattern. "Tag operations"
-covers `~ALL` tags, so the pattern carries no part of the gate — it only
-duplicates `release.yaml`'s own tag filter, and the two are easy to drift
-apart. They already had: the workflow fires on `**[0-9]+.[0-9]+.[0-9]+*`,
-which matches an unprefixed `1.2.3` that a `v*` policy would then refuse. A
-release cut under that name would have stopped at `build-local-artifacts`,
-which names `signing` and waits only on `plan` — before an artifact was built,
-let alone published.
-
-`TEND_BOT_TOKEN` is stored in two environments rather than shared, because a
-policy admits branches or tags but the token is needed under both: the bot's
-own workflows run on `main`, the publish jobs on a tag. Adding the tag to
-`tend` is not an option — `tend check` pins that policy to exactly the
-protected branches and its `--fix` deletes anything else.
-
-Jobs name `tend` as `{name: tend, deployment: false}`. GitHub files a
-deployment record for every job that names an environment, against whatever
-ref the run belongs to — under `pull_request_target` that is the pull request
-itself, so an omission posts a "worktrunk-bot deployed to tend" line on every
-push to every PR. `deployment: false` drops the record and keeps the gate. The
-release jobs keep their records: a tag-push deployment lands in no PR
-timeline, and it reads as what it is.
-
-The generated `tend-*.yaml` files carry the same `{name: tend, deployment:
-false}`, written by tend's generator rather than edited here — every `uvx
-tend@latest init` overwrites them, so a hand edit would not survive one. tend
-0.1.14 added the field and #3749 landed the regen, which is what cleared `tend
-check`'s `environment-deployments`.
-
-crates.io publishing holds no stored token — it uses Trusted Publishing.
-crates.io mints a short-lived one only for an OIDC claim from `release.yaml`
-running in that same `release` environment.
-
-## Sandbox toolchain
-
-The agent runs as `tend-sandbox`, but from tend 0.2.14 it works through a
-copy-on-write view of the job's own checkout and home rather than a tree of
-its own: `$HOME` is `/home/runner`, the cwd is the runner's checkout, and what
-`setup:` installed is on PATH at the path it was installed to. Writes stay
-inside the view, so nothing the agent writes reaches the runner or a later
-step. A tool `tend-setup` installs anywhere the runner can reach is therefore a
-tool the agent has, and no hand-off is needed to carry it across.
-
-That replaced the arrangement 0.2.5–0.2.13 ran under, where the agent had a
-home of its own, tend rewrote a leading `/home/runner` out of its PATH, and the
-Sandbox Runtime denied reads across the runner's home and checkout. Machinery
-this repo built for that is still in place and still runs, now as a second copy
-rather than as the route:
-
-- `tend-setup` `sudo install`s `cargo-insta` and `cargo-nextest` into
- `/usr/local/bin`. Both also resolve from `$HOME/.cargo-install/<crate>/bin`,
- which comes first on the agent's PATH.
-- `.config/tend.yaml`'s `sandbox_setup:` installs `pre-commit`, which
- `tend-setup` installs too. 0.2.14 deprecated the key and runs its commands as
- an ordinary `runner` step after `setup:`; #4222 kept it so a release
- reverting 0.2.14 would still find it. Its closing probe still earns its place
- — it asserts the four tools the pre-merge gate needs, whichever step
- installed them, plus `nix` for the weekly toolchain bump.
-
-Being on PATH gets the *binary* across, not what it talks to. `nix` resolves
-for the agent but cannot reach the daemon: `socket(AF_UNIX, …)` is blocked, so
-`nix store info` fails with "Address family not supported by protocol" and the
-weekly `flake.lock` refresh needs an upstream lever (max-sixty/tend#1197).
-`command -v` can't see that distinction, which is why the probe stays green
-while the weekly job would not.
-
-## Build environment
-
-`Swatinem/rust-cache` hashes `CARGO*` and `RUST*` env vars into the cache key.
-All workflows sharing a cache must set the same env vars, or they'll get
-different keys and miss each other's caches.
-
-It hashes the vars **visible at its own step**, so a var exported by a later
-step is invisible and a var the writers don't set poisons the key. ci.yaml and
-nightly.yaml carry theirs in a workflow-level `env:` block, always in place
-first. A miss is silent — the step succeeds having restored nothing — so drift
-here shows up only as slow jobs.
-
-The `tend-*.yaml` workflows are out of this scheme: they can't carry a
-workflow-level `env:` block, so `tend-setup` restores nothing, sets none of the
-three vars, and tend sessions compile cold. What forced that between tend 0.2.5
-and 0.2.13 — the agent building in a disposable `/tmp` clone, where a cache
-restored into the runner's checkout and home was both unreachable and at the
-wrong path — no longer holds, because 0.2.14 put the agent on the job's own
-checkout and home. Whether a restore now pays for itself is a measurement
-against the download cost in all eight workflows (max-sixty/tend#1198).
diff --git a/.github/actions/tend-setup/action.yaml b/.github/actions/tend-setup/action.yaml
index b019dad86..8720776ad 100644
--- a/.github/actions/tend-setup/action.yaml
+++ b/.github/actions/tend-setup/action.yaml
@@ -29,7 +29,7 @@ runs:
# PATH. The publish was the only route while the sandbox denied reads under
# the runner's home (0.2.5–0.2.13) and is now a second copy of the same two
# binaries; it stays as what keeps `.config/tend.yaml`'s probe green if
- # that isolation returns (see "Sandbox toolchain" in .github/CLAUDE.md).
+ # that isolation returns (see "Sandbox toolchain" in .github/AGENTS.md).
# Swapping these steps for an action with a different layout breaks the
# publish step, which hardcodes this root; update both sides.
- name: Install cargo-insta
@@ -87,7 +87,7 @@ runs:
# `shell-integration-tests` — that needs `nu` as much as zsh and fish, and
# two tests `.expect()` it outright. `setup-nu` installs into
# /opt/hostedtoolcache, which the agent has reached under every sandbox
- # arrangement so far (see "Sandbox toolchain" in .github/CLAUDE.md). Level
+ # arrangement so far (see "Sandbox toolchain" in .github/AGENTS.md). Level
# with `test-setup`'s pin.
- name: Install nushell
if: inputs.install-shells == 'true'
diff --git a/.github/workflows/affected.yaml b/.github/workflows/affected.yaml
index 7cd88bcad..4f3fad433 100644
--- a/.github/workflows/affected.yaml
+++ b/.github/workflows/affected.yaml
@@ -21,7 +21,7 @@ concurrency:
env:
# Both jobs restore the rust-cache that `test` saves, and Swatinem/rust-cache
# hashes CARGO*/RUST* into the key, so these must match ci.yaml exactly
- # (.github/CLAUDE.md → Build environment).
+ # (.github/AGENTS.md → Build environment).
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUSTFLAGS: -C debuginfo=0
@@ -51,7 +51,7 @@ jobs:
# Until then the full `test` matrix stays required and runs on every PR,
# unchanged. Do NOT reach affected-only by making the required `test (*)`
# checks skip=pass on PRs — relaxing the merge gate is a deliberate
- # branch-protection change owned by the repo admin (see `.github/CLAUDE.md`),
+ # branch-protection change owned by the repo admin (see `.github/AGENTS.md`),
# not a silent workflow skip.
#
# The full suite must keep running after the flip, because cargo-affected
diff --git a/.github/workflows/benchmarks.yaml b/.github/workflows/benchmarks.yaml
index 77a33662c..e016f953f 100644
--- a/.github/workflows/benchmarks.yaml
+++ b/.github/workflows/benchmarks.yaml
@@ -25,7 +25,7 @@ concurrency:
env:
# Match ci.yaml/nightly.yaml: Swatinem/rust-cache hashes CARGO*/RUST* into
# the cache key, so the shared `test` cache only restores when these agree
- # (see .github/CLAUDE.md).
+ # (see .github/AGENTS.md).
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUSTFLAGS: -C debuginfo=0
@@ -92,7 +92,7 @@ jobs:
runs-on: ubuntu-24.04
environment:
name: tend
- # A secret scope, not a deploy target — see .github/CLAUDE.md.
+ # A secret scope, not a deploy target — see .github/AGENTS.md.
deployment: false
permissions:
contents: read
@@ -142,7 +142,7 @@ jobs:
runs-on: ubuntu-24.04
environment:
name: tend
- # A secret scope, not a deploy target — see .github/CLAUDE.md.
+ # A secret scope, not a deploy target — see .github/AGENTS.md.
deployment: false
permissions:
contents: read
@@ -154,7 +154,7 @@ jobs:
- uses: JasonEtco/create-an-issue@v2
env:
# Use TEND_BOT_TOKEN for a consistent bot identity (per
- # .github/CLAUDE.md) and so any future issue-triage automation can
+ # .github/AGENTS.md) and so any future issue-triage automation can
# cascade off issue creation — events from the default GITHUB_TOKEN
# don't trigger other workflows.
GITHUB_TOKEN: ${{ secrets.TEND_BOT_TOKEN }}
diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml
index 03e7cfad7..2bc54b224 100644
--- a/.github/workflows/coverage.yaml
+++ b/.github/workflows/coverage.yaml
@@ -20,7 +20,7 @@ concurrency:
env:
# Swatinem/rust-cache hashes CARGO*/RUST* into the cache key, so these track
- # ci.yaml (.github/CLAUDE.md → Build environment).
+ # ci.yaml (.github/AGENTS.md → Build environment).
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUSTFLAGS: -C debuginfo=0
diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml
index 89bfc2ee2..ed362da47 100644
--- a/.github/workflows/nightly.yaml
+++ b/.github/workflows/nightly.yaml
@@ -458,7 +458,7 @@ jobs:
runs-on: ubuntu-24.04
environment:
name: tend
- # A secret scope, not a deploy target — see .github/CLAUDE.md. The cron
+ # A secret scope, not a deploy target — see .github/AGENTS.md. The cron
# gate above keeps this off the workflow's pull_request and
# workflow_dispatch triggers, whose refs the `tend` policy can refuse;
# its push trigger is `main`-only, which the policy already admits.
@@ -473,7 +473,7 @@ jobs:
- uses: JasonEtco/create-an-issue@v2
env:
# Use TEND_BOT_TOKEN for a consistent bot identity (per
- # .github/CLAUDE.md) and so any future issue-triage automation can
+ # .github/AGENTS.md) and so any future issue-triage automation can
# cascade off issue creation — events from the default GITHUB_TOKEN
# don't trigger other workflows.
GITHUB_TOKEN: ${{ secrets.TEND_BOT_TOKEN }}
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index 5432dc1ab..5068cc5b0 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -122,7 +122,7 @@ jobs:
# This job doesn't deploy anything; the environment scopes
# SIGNPATH_API_TOKEN so it isn't readable by every workflow the repo runs.
# It is deliberately not `release`, which also holds the publish
- # credentials — see .github/CLAUDE.md. The policy admits tags only, so
+ # credentials — see .github/AGENTS.md. The policy admits tags only, so
# setting `pr-run-mode = "upload"` in dist-workspace.toml would make GitHub
# reject this job on a PR ref.
environment: signing
diff --git a/.github/workflows/tend-ci-fix.yaml b/.github/workflows/tend-ci-fix.yaml
index fc5b3f6f9..a97db2ab5 100644
--- a/.github/workflows/tend-ci-fix.yaml
+++ b/.github/workflows/tend-ci-fix.yaml
@@ -46,7 +46,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-mention.yaml b/.github/workflows/tend-mention.yaml
index 275907749..0fbcde87c 100644
--- a/.github/workflows/tend-mention.yaml
+++ b/.github/workflows/tend-mention.yaml
@@ -352,7 +352,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-nightly.yaml b/.github/workflows/tend-nightly.yaml
index 6153805c6..949ac7784 100644
--- a/.github/workflows/tend-nightly.yaml
+++ b/.github/workflows/tend-nightly.yaml
@@ -37,7 +37,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-notifications.yaml b/.github/workflows/tend-notifications.yaml
index fa07d694e..1254caec3 100644
--- a/.github/workflows/tend-notifications.yaml
+++ b/.github/workflows/tend-notifications.yaml
@@ -250,7 +250,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
if: steps.check.outputs.count != '0' || steps.check.outputs.conflict_count != '0' || github.event_name == 'workflow_dispatch'
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-review-runs.yaml b/.github/workflows/tend-review-runs.yaml
index 7eb51c35f..ad333b19a 100644
--- a/.github/workflows/tend-review-runs.yaml
+++ b/.github/workflows/tend-review-runs.yaml
@@ -37,7 +37,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-review.yaml b/.github/workflows/tend-review.yaml
index 9a1b874ef..421e525a0 100644
--- a/.github/workflows/tend-review.yaml
+++ b/.github/workflows/tend-review.yaml
@@ -55,7 +55,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-triage.yaml b/.github/workflows/tend-triage.yaml
index 858a630c8..9e54f3c1a 100644
--- a/.github/workflows/tend-triage.yaml
+++ b/.github/workflows/tend-triage.yaml
@@ -49,7 +49,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/.github/workflows/tend-weekly.yaml b/.github/workflows/tend-weekly.yaml
index dfb0f3a11..e711f455b 100644
--- a/.github/workflows/tend-weekly.yaml
+++ b/.github/workflows/tend-weekly.yaml
@@ -37,7 +37,7 @@ jobs:
- run: |-
mkdir -p ~/.local/bin
uv tool install --quiet pre-commit
- for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/CLAUDE.md"; exit 1; }; done
+ for t in cargo-insta cargo-nextest pre-commit nu nix; do command -v "$t" >/dev/null || { echo "::error::tend sandbox is missing $t; see Sandbox toolchain in .github/AGENTS.md"; exit 1; }; done
shell: bash
- uses: max-sixty/tend/[email protected]
diff --git a/AGENTS.md b/AGENTS.md
deleted file mode 120000
index 681311eb9..000000000
--- a/AGENTS.md
+++ /dev/null
@@ -1 +0,0 @@
-CLAUDE.md
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000..6c2e70de5
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,251 @@
+# Worktrunk Development Guidelines
+
+## Quick Start
+
+```bash
+cargo run -- hook pre-merge --yes # all tests + lints (runs automatically in wt merge)
+```
+
+Claude Code web: run `task setup-web` first. Test commands, isolation, and coverage investigation: `tests/AGENTS.md`.
+Codex Cloud: use the setup in `.codex/cloud.sh`.
+
+## Project Status
+
+Maturing mode: a growing user base, so balance clean design with compatibility.
+
+- New features are welcome, but a command, option, user-facing concept, or configuration key is a product decision. Its user value must justify the code and documentation surface it adds.
+- Consolidate or remove existing prose and machinery before adding another explanation, mode, or special case.
+- External-interface breaks need justification (a real improvement, not cleanup); prefer deprecation warnings over silent breaks.
+- **Protected interfaces:** config file format (`wt.toml`, user config) and CLI flags/arguments. Everything else (internal APIs, output formatting, log locations) is flexible.
+- No Rust library compatibility concerns (CLI tool only).
+- MSRV: latest stable − 1, bumped during weekly tend maintenance (`running-tend` skill).
+
+## Terminology
+
+Use consistently in docs, help text, and code comments:
+
+- **main worktree** — the original git directory (from clone/init); bare repos have none
+- **linked worktree** — created via `git worktree add` (git's term)
+- **primary worktree** — the "home" worktree: main worktree for normal repos, default-branch worktree for bare repos
+- **default branch** — the branch (main, master, …), not "main branch"
+- **target** — destination for merge/rebase/push ("merge target"). Never use "target" for worktrees; say "worktree"
+
+## Skills
+
+Load relevant skills before starting; reload when scope changes mid-session. Project-local skills live in `.claude/skills/`, with `.agents/skills` linking Codex to the same files:
+
+- `writing-user-outputs` — before editing code that calls `warning_message`, `hint_message`, `error_message`, `info_message`, `eprintln`, `println`, or otherwise produces user-visible strings (CLI help, progress UI, snapshots).
+- `running-tend` — operating in CI or writing tend workflows.
+- `release` — cutting a release.
+
+## Worktree Model
+
+- Worktrees are **addressed by branch name**, with a worktree's own path as an alias — resolved branch-first by `Repository::resolve_worktree`, the one canonicalizer every worktree-naming argument routes through. A path is not a second addressing scheme: it names what a branch cannot (a detached worktree, one of two checkouts of a branch). So document arguments as taking a branch, state the path alias once rather than per argument, and give a new argument the canonicalizer rather than its own rule.
+- Each worktree maps to **exactly one branch**.
+- **Never retarget an existing worktree** to a different branch; create/switch/remove instead. (Sole exception: `wt step promote`, experimental, exchanges branches between two worktrees.)
+
+## Documentation
+
+Behavior changes require doc updates. `src/cli/mod.rs` (`after_long_help` plus clap attributes) is the PRIMARY SOURCE for command pages; their rendered mirrors in `docs/src/content/docs/` and `skills/worktrunk/reference/` are generated, as is all of `plugins/worktrunk/skills/` — but both directories also hold hand-edited primaries (non-command docs in `docs/src/content/docs/`, skill-only pages like `troubleshooting.md` in the reference dir), so check which file is primary in the sync taxonomy before editing. Ask: "does `--help` still describe what the code does?" `cargo test --test integration test_docs_are_in_sync` checks doc sync; editing help text (`after_long_help`, `about`, arg docs) also changes the rendered `--help` snapshots, which that test leaves untouched — `cargo insta test --accept --test integration -- test_help` regenerates them (the pre-merge hook runs both). Sync taxonomy, help-text authoring (three render contexts, link text, config-TOML blocks): `docs/AGENTS.md`.
+
+## Plugin Layout
+
+Per-tool layout and path resolution (Claude/Codex/Gemini), the convention-only Claude manifest, the Codex inline-hooks rationale, the generated plugin-skills mirror, the accepted `wt-switch-create` tradeoff, and `test_plugin_layout_is_consolidated`: `plugins/worktrunk/AGENTS.md`.
+
+The Pi-family integrations are two commands because they are two agents. `wt config plugins pi` targets Pi (earendil-works/pi), which loads `ExtensionAPI` extensions from `~/.pi/agent/extensions/`; `wt config plugins omp` targets oh-my-pi, which loads `HookAPI` hooks from `~/.omp/agent/hooks/pre/`. Path rules live in `src/commands/config/pi.rs` and `src/commands/config/omp.rs`; the embedded sources are `dev/pi-extension.ts` and `dev/omp-hook.ts`. Neither file is interchangeable — the loaders differ, and so do the config roots (`$PI_CODING_AGENT_DIR` for Pi; `$PI_CONFIG_DIR`, `$OMP_PROFILE`/`$PI_PROFILE`, and `$PI_CODING_AGENT_DIR` for oh-my-pi).
+
+## Data Safety
+
+Never risk data loss without explicit user consent. A failed command that preserves data beats a "successful" one that silently destroys work.
+
+- **Prefer failure over silent loss** — if an operation might destroy untracked files, uncommitted changes, or user data, fail with an error.
+- **Explicit consent for destructive ops** — force-removing data (e.g. `--force` on remove) requires the user to explicitly request it.
+- **No implicit destructive side effects** — never silently delete/overwrite as a side effect of an unrelated operation; make cleanup a separate explicit action the user chooses.
+- **Favor the failing variant on races** — `git reset --keep` (fails if tracked files were modified) over `--hard`; `git checkout --merge` over `--force`. If no safer variant exists, document the risk inline.
+- **Time-of-check vs time-of-use** — be conservative when there's a gap between the safety check and the operation. `wt merge` verifies clean before rebasing, but files could appear before cleanup — don't force-remove during cleanup.
+- **Replace full files, never truncate them** — `fs::write` truncates before it writes, so a crash mid-write leaves the file empty. Every full-file rewrite worktrunk can't put back (shell wrappers, `config.toml`, `approvals.toml`, another tool's `settings.json`) goes through `utils::write_atomically`, which renames a sibling temp file over the target; the spec on that function covers symlinks, mode, and what a rename costs. When a user-owned file was observed missing, `utils::write_new_atomically` refuses to overwrite one that appears before persistence. Adding to an existing Bash, Zsh, or PowerShell rc file instead opens it in append mode, so a stale snapshot cannot replace concurrent edits; never truncate the file to recover from an append error. Don't grow the install path into a rebuild. Removal still rewrites those rc files whole (`uninstall_previewed_lines`), which is why the `write_atomically` spec still names them. Regenerable content (the cache, the `-vv` diagnostic report) keeps the plain write.
+- **A path the user named is written, not second-guessed** — `wt config update --output <path>` replaces whatever is there, the way `cp` and a shell redirect do, and pointed at the config being migrated it writes the migration there too. No-clobber belongs to the other case: a path worktrunk chose itself and observed absent (a shell rc file, `wt config create`), where a file appearing before the rename is one wt never read and a dangling symlink is a dotfile manager's link to keep. Deciding between the two at a call site is the smell — each write site is in one case or the other, so it calls one function unconditionally.
+- **Shell-config concurrency has a deliberate boundary** — the append lock coordinates Worktrunk installers, and no-clobber creation turns the missing-file race into a fail-and-rerun outcome. An editor save racing rc-file uninstall can still be overwritten; accept this final check-to-rename window because sidecar locks, backups, retries, and extra pre-rename checks do not close it. Revisit after an observed incident or a simpler write design. Worktrunk-owned wrappers and completions use last-writer-wins semantics, as does the merge into another tool's `settings.json`.
+
+These stop where git's own protections stop, and matching git is deliberate in each case. The named spec says why:
+
+- `wt merge` and `wt step push` overwrite an ignored file in the destination worktree whose path the incoming commits track, exactly as a `git merge` run there would (`src/commands/worktree/push.rs`).
+- Removal's final dirty-worktree gate is answered by the fsmonitor daemon under `core.fsmonitor`, exactly as `git worktree remove`'s own gate is (`src/git/remove.rs`).
+
+Full inventory: FAQ [What files does Worktrunk create?](docs/src/content/docs/faq.md#what-files-does-worktrunk-create) and [What can Worktrunk delete?](docs/src/content/docs/faq.md#what-can-worktrunk-delete). Review new code that changes this surface against those sections.
+
+## Command Execution Principles
+
+### All Commands Through `shell_exec::Cmd`
+
+Every external command goes through `shell_exec::Cmd` for consistent debug logging (`$ git status [worktree-name]`) and `[wt-trace]` timing. Never call `cmd.output()` directly. For git, prefer `Repository::run_command()` (wraps `Cmd` with worktree context). `Cmd` has four execution modes — `run` (capture), `stream` (inherit stdio), `delayed_stream` (buffer then stream to stderr, for slow ops like `git worktree add`), and `pipe_into` (two-stage pipe). Pipe stdin via `.stdin_bytes(...)`.
+
+```rust
+Cmd::new("git").args(["status", "--porcelain"]).current_dir(&wt).context("worktree-name").run()?;
+Cmd::new("gh").args(["pr", "list"]).run()?; // no context for standalone tools
+```
+
+**The `[wt-trace]` command record has one emitter: `CommandTrace` in `src/trace/emit.rs`.** The grammar lives there too (don't hand-write `log::debug!("[wt-trace] …")`). `CommandTrace::{complete,fail}` are the only callers of the private `command_completed`/`command_errored` writers, so a subprocess is either traced through the guard or produces no command record. Most spawns get this for free via `Cmd`. A few spawn sites have I/O shapes `Cmd` can't model and construct a `CommandTrace` directly: the concurrent-command runner (`output/concurrent.rs`), pipeline steps (`commands/run_pipeline.rs`), `wt step tether`, and the fsmonitor daemon launch. **Any new spawn site that runs an in-process command must construct a `CommandTrace` (start it just before spawn; `complete(success)` after wait, `fail(err)` on spawn/wait error)** — otherwise the command shows up as an unattributed gap in `wt-perf timeline`. The guard is `#[must_use]` and trips a debug-build assertion if dropped unresolved, so a forgotten `complete`/`fail` fails tests rather than silently going untraced. Detached background children (`commands/process.rs`) and interactive helpers (pagers, shell probes) are intentionally untraced — they outlive the invocation or aren't part of its timeline.
+
+### Git-Discovery Env Vars Follow Who Chose the Cwd
+
+Git resolves `GIT_DIR`/`GIT_WORK_TREE` (and the rest of `INHERITED_GIT_PATH_VARS`) before walking up from the cwd, so an inherited value silently overrides a child's working directory. **Any spawn site whose cwd names a `wt`-chosen worktree must scrub these vars** (`Cmd::scrub_git_discovery_env` or `scrub_git_discovery_env_vars`) — both relocated user commands (hooks, `wt step for-each`, the `--execute` program) and `wt`'s own worktree-local plumbing (`WorkingTree::run_command`, `TempIndex::command`). A site that supplies its own value for one of the scrubbed vars sets it after the scrub; `Cmd` applies env mutations in call order, so the set wins. Children running in the user's own context (aliases, `commit.generation`) and repo-level plumbing (`Repository::run_command`) keep the inherited context (absolutized) — that exemption is about scope, not cwd: `Repository::at` is handed a `wt`-chosen worktree at several sites, but repo-level questions are worktree-agnostic within one repository, and every worktree-scoped answer routes through `WorkingTree`. Full site classification and rationale: `scrub_git_discovery_env_vars` in `src/shell_exec.rs`.
+
+### Real-time Output Streaming
+
+Stream command output line-by-line rather than buffering. Responsiveness is a priority.
+
+### Structured Output Over Error-Message Parsing
+
+Prefer exit codes / `--porcelain` / `--json` over parsing human-readable messages, which break on locale, version, and rewording changes. `git merge-base` exit codes encode meaning (0 found, 1 no common ancestor, 128 invalid ref) — branch on `status.code()`, not message text.
+
+| Tool | Fragile | Structured |
+|------|---------|------------|
+| `git diff-tree` / `diff-index` | `--stat` (localized) | `--numstat`, `--shortstat` (`(+)`/`(-)` hardcoded) |
+| `git status` | default | `--porcelain=v2 -z` |
+| `git merge-base` | error messages | exit codes |
+| `gh` / `glab` | default | `--json` |
+
+When no structured alternative exists, document the fragility inline.
+
+### Plumbing for Output `wt` Consumes
+
+Porcelain commands read display configuration that changes what they report: `diff.relative` once made `wt remove` delete an unmerged branch, and `color.ui=always` and `diff.external` leaked into LLM prompts. When `wt` parses, caches, renders, or prompts with git's output, it runs plumbing (`diff-tree`, `diff-index`, `diff-files`, `for-each-ref`), which ignores that configuration apart from `submodule.<name>.ignore`. `PlumbingDiff::args` builds every plumbing diff with `--ignore-submodules=none` to override that setting, and a test rejects one spelled by hand. Rendered and prompted diffs go through `PreparedDiff::capture`, which also restores the `git diff` defaults plumbing lacks. `git status` has no plumbing equivalent, so it pins its behavior with explicit flags. Output shown as git's own view, like `wt step diff`, stays porcelain.
+
+### Immutable Ids Over List Positions
+
+`stash@{0}` names a position in a list any process can reorder, so a handle captured before a mutation window and used after it can resolve to a different object — restoring the target worktree's autostash by position after `git push` silently restored a concurrent writer's entry and reported success. Capture the immutable id instead (`git stash list --format=%H`, `git stash create`, `rev-parse`) and act on that; where an operation accepts only a positional selector, re-derive it from something stable immediately beforehand. An index into a collection `wt` owns is a different thing — this is about namespaces other processes can mutate. The strongest form is not to enter the shared namespace at all: the autostash this rule came from was later deleted outright, replaced by a two-tree merge that leaves the target worktree's changes in place (`advance_target` in `src/commands/worktree/push.rs`).
+
+### Network Access
+
+worktrunk is local-first: the network is touched only when the user asked for it, and only where reaching the wire directly serves that request. **One detection helper is exempt:** the *first* `Repository::default_branch()` per repo may fall through to `git ls-remote`; the result caches in `worktrunk.default-branch` and every later call is local. The query is bounded by `REMOTE_DETECTION_TIMEOUT` — nothing in git bounds it, and an unreachable host costs ~127 s per address on Linux — and a query that hits the bound falls back to local inference *without* caching it, so an outage can't make a guess permanent. No other detection helper may add a similar fallback.
+
+Why: silent "lookup" paths that walk to the wire (alias dispatch, hook context build, recovery) stall commands the user wouldn't expect to do network work, worst on a fresh clone. The `default_branch()` bootstrap keeps a fresh clone usable while bounding the exception to one helper firing at most once per repo.
+
+**Network never blocks the first write.** Fast output to the terminal is the priority (Real-time Output Streaming, above): every command paints from local data first, then network-derived detail streams in progressively behind it. A command that can't render its first frame until `gh` or `git fetch` returns is the failure mode, worst on a fresh clone or a slow link. Before adding an accessor that could reach the wire (`gh`, `glab`, `git fetch`, `git ls-remote`, HTTP), confirm it renders progressively and never gates the first paint. A synchronous hot path like a shell prompt is stricter: it must not reach the wire at all, even progressively. `wt list statusline` is not such a path despite running on every prompt, because Claude Code consumes its output asynchronously.
+
+**The picker is the most forgiving home for network work, because its lifetime is bounded by the user, not the job.** It paints immediately, the user browses, and a slow forge call streams into the rows whenever it arrives; if the user picks first, the picker's exit cancels the unfinished request (`shell_exec::cancel_background_commands`), so its latency never costs anything. A run-to-completion command is less forgiving: `wt list` renders progressively but still cannot *finish* until every task returns, so a slow `gh` call extends the command the user is waiting on. Prefer the picker for live forge data, and fetch it there progressively.
+
+What currently reaches the wire:
+
+- `wt list --full`, `wt list statusline` — CI status; also plain `wt list` (table) when `[list] columns` names `ci`, which forces the column (and its fetch) on without `--full`. `--format json` plans off `--full` alone, so a display setting can't send a machine-readable call to a forge
+- `wt switch` (interactive picker, no target) — per-row CI status, primed from the local cache then fetched live and streamed into the rows; once a row's CI fetch surfaces an open PR/MR, a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) fills that row's `comments` preview tab — the same fetch a `--prs` row makes, spawned once per row from `progressive_handler` (see `picker::prs::spawn_comments_fetch`). The `comments` tab is the only PR data fetched lazily here; `pr` rides the CI call and `log` is the local `git log`
+- generating a branch summary with a `commit.generation` command
+- generating a commit message with a `commit.generation` command
+- `wt switch pr:<n>`, `wt switch mr:<n>` — host API to resolve the PR/MR, then `git fetch` of its branch
+- `wt switch --prs` — one `gh pr list` / `glab mr list` to populate the interactive picker (streamed in after the frame paints), then a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) to fill each row's `comments` preview tab, plus a `gh pr view <n> --json commits` / `glab api …/commits` for the `log` tab **only when the head commit isn't already local** — a `--prs` row whose `headRefOid`/`sha` resolves in the object store renders the `log` tab from a local `git log` with no network (off the pool, once per row when the rows land — see `picker::prs::spawn_pr_previews`)
+- `wt config show --full` — version check against GitHub
+- the first `Repository::default_branch()` per repo — `git ls-remote` (above)
+
+### Signal Handling: Ctrl-C Cancels the Current Command
+
+When a child process exits from a signal (SIGINT, SIGTERM), every loop in the foreground execution path MUST abort rather than continue to the next iteration. This applies to worktree loops (`wt step for-each`), hook pipelines, alias steps, concurrent groups, and any future code running multiple child processes in sequence.
+
+Why: wt installs a `signal_hook` SIGINT/SIGTERM handler so it can forward signals to child process groups before exiting cleanly. As a side effect wt itself does not die from the user's Ctrl-C — only the current child does. Without this policy a single Ctrl-C against `wt merge` would charge through the remaining hook steps, with `FailureStrategy::Warn` silently swallowing each interrupt.
+
+- Signal-derived child exits surface structurally: stream mode (`Cmd::stream`) as `WorktrunkError::ChildProcessExited { signal: Some(sig), .. }`, capture mode (`Cmd::run`) as `CommandError { signal: Some(sig), .. }`. These fields are the structured channel — never sniff `code >= 128` or parse error messages.
+- Detect via `err.interrupt_signal()` (the `worktrunk::git::ErrorExt` trait). When it returns `Some(signal)`, propagate as `WorktrunkError::Interrupted { signal, hint }` and break the loop. `Interrupted` exits `128 + signal` (130 SIGINT, 143 SIGTERM) and renders once, at exit, per shell convention: silent for SIGINT (the terminal echoed `^C`), `Terminated` for SIGTERM — the line the shell would print if wt weren't trapping the signal. `hint` carries an optional recovery line for state the interrupt left behind (e.g. a mid-rebase worktree).
+- In capture mode only SIGINT/SIGTERM classify as interrupts. Capture children get no forwarding or escalation, and their captured output would be discarded by the silent exit — so a child killed by any other signal (a crash, an OOM kill) surfaces as a visible error instead. A capture child with a `Cmd::timeout` is the one the tty broadcast doesn't reach: it runs in its own process group so expiry can tear down its whole tree (`run_with_timeout_impl`), which is what makes the bound bound anything, so a Ctrl-C during one waits out the remaining timeout. Stream mode counts any signal: output already streamed to the terminal, and user-initiated kills are normalized upstream to the originating SIGINT/SIGTERM (`seen_signal` in `shell_exec`, the concurrent runner's originating-signal override).
+- The check happens **before** any `FailureStrategy` branch — Warn must NOT swallow signal-derived errors.
+- `handle_command_error` in `src/commands/command_executor.rs` enforces this for hook and alias pipelines (foreground and concurrent groups); `for_each.rs` enforces it for the worktree loop. New code that loops over child processes calls `.interrupt_signal()` on per-iteration errors and breaks.
+
+### Project Commands Run Only After Approval
+
+**Policy:** project-defined commands (`pre-*` / `post-*` hooks, `[aliases]`, `--execute` bodies from project config) are arbitrary code shipped in a repo the user may have just cloned, so they run only after the approval system (`Approvals` plus `approve_command_batch` / `approve_or_skip` in `src/commands/command_approval.rs`) clears them. Never build a code path that runs project commands without that gate. A context that can't prompt (a TUI mid-render, a background recovery path) consults the approval state read-only and runs only the already-approved subset: `commands::picker::do_removal` builds the plan via `HookPlan::approve_readonly` (no prompt).
+
+**Why:** the gate is the only thing between `git clone && wt switch` and a `post-switch` hook running `curl … | sh`. A "we already validated the operation, so run the hooks too" shortcut turns every command that touches project config into remote code execution.
+
+**Implementation:** the operation-driven hooks (`pre-merge`, `post-merge`, `pre-remove`, `post-remove`, `post-switch`, `pre-start`, `post-start`) are gated *before* a state mutation and run *after* it, so a second config read could select an unapproved command. `src/commands/hook_plan.rs` closes this structurally: each gate (`wt remove` / `wt merge` / `wt step prune` / `wt switch`) selects the command set once into an immutable `ApprovedHookPlan` (`HookPlan::approve`); the executor consumes only that value via `execute_planned_hook` / `register_planned` and holds no `ProjectConfig` to re-derive from, so re-selection is a compile error, not a review check. An empty plan (`--no-hooks`, declined, or no project config) runs nothing. The adjacent hooks with no gate→exec mutation (`pre-commit`, `post-commit`, `pre-switch`, `wt hook <type>`, aliases) still resolve config at invocation via `execute_hook` / `HookAnnouncer::register`. See `src/commands/hook_plan.rs` and the `commands::hooks` module spec.
+
+### Background Hook Pipelines Run Concurrently, Per Source
+
+A `post-*` batch spawns one detached pipeline per source, and they run at once. Don't serialize them: `post-start` is documented for dev servers and `wt step tether`, so a user hook that never exits would block the project's forever, and `wt merge`'s batch spans two worktrees (`post-commit` anchors on the invoking worktree, the rest on the destination) so chaining also drops hooks behind a head whose worktree is already removed. That span is also why the flush can reach a pipeline whose anchor is gone: the merge removes `post-commit`'s worktree first, so the removal reports it through `HookAnnouncer::mark_worktree_removed` and the flush drops that pipeline rather than spawning it into a path whose git discovery would resolve to the primary worktree. The removal is what knows — where its fast rename into `.git/wt/trash/` fails, the fallback `git worktree remove` runs detached and the anchor is still on disk at the flush, so a filesystem probe would answer differently on the two paths. The cost is that two hooks touching one worktree's git state can collide — two `git pull`s there append to each other's `FETCH_HEAD` and both fail — which `wt hook --help` tells users to avoid by keeping dependent commands in one source.
+
+## Hook Output Logs
+
+`.git/wt/logs/` layout — per-branch and repo-wide log paths, plus the `sanitize_for_filename` filename rule: the `HookLog` spec in `src/commands/process.rs`. The top-level file-vs-directory split that `wt config state` walks: the "Log layout invariant" in `src/commands/config/state.rs`.
+
+## Coverage
+
+**`codecov/patch` gates the merge, not the design.** Write the change the design calls for, then deal with the check. A predicted red patch is never a reason to shelve or water down an improvement, and neither the code nor the tests get contorted to move the number. The patch target is `auto` (the base commit's project coverage), so a handful of missed lines flips a small patch red, and a refactor that only relocates existing uncovered lines pulls their misses in without changing behavior.
+
+**NEVER merge a PR with failing `codecov/patch` without explicit user approval.** It is marked "not required" in GitHub but still gates merge. On PR heads codecov posts **check runs** (codecov GitHub App), not commit statuses: poll with `gh pr checks <number>` or the check-runs API; the combined-status API (`/commits/<sha>/status`) never shows them, and the check run lands a few minutes after the `code-coverage` job finishes. On failure, close the gap where it's real — write tests, or delete code that's genuinely unused (a specialized error handler where falling through to the general one suffices; never a rarely-reached backstop that's load-bearing). Where it isn't real — misses that predate the change, or a path with no deterministic trigger — push the change and ask before merging, handing over the arithmetic: which lines, why they can't be covered, what the patch percentage comes to. Coverage runs include `--features shell-integration-tests` (CI `code-coverage` and local `task coverage`) — don't dismiss failures by claiming the feature is off. Investigation commands, moved-line false positives, and the "N functions mismatched" warning: `tests/AGENTS.md`.
+
+## Benchmarks & Traces
+
+`cargo bench --bench list <filter>` (Criterion takes a positional substring filter; there's no `--skip`). `cargo run -p wt-perf -- timeline -- <args>` traces one `wt` invocation. Real-repo benchmarks clone rust-lang/rust on first run. Benchmarks run as a standalone scheduled workflow (`.github/workflows/benchmarks.yaml`, daily cron plus `workflow_dispatch`), not on PRs, so they never gate a merge; only `test (linux|macos|windows)` block it. Filter map, expected numbers, and trace queries: `benches/AGENTS.md`.
+
+## Code Quality
+
+### Use Existing Dependencies
+
+Check `Cargo.toml` before hand-rolling a utility:
+
+| Need | Use | Not |
+|------|-----|-----|
+| Path normalization | `path_slash::PathExt::to_slash_lossy()` | `.to_string_lossy().replace('\\', "/")` |
+| Shell escaping | `shell_escape::unix::escape()` | manual quoting |
+| ANSI colors | `color_print::cformat!()` | raw escape codes |
+| Template var detection | `minijinja::undeclared_variables(false)` | regex/substring on `{{ var }}` |
+
+Delegation extends past utilities to **another tool's own rules** — where zsh
+reads its config, which TOML keys a schema accepts, how MiniJinja scopes a
+template binding. Ask the library; don't re-derive its rule inside `wt`. A
+re-derived rule is correct on the cases that motivated it and drifts silently
+afterwards. Where the library exposes no API that answers the question, keep
+the substitute no larger than the question and say in the code why it exists.
+
+### Don't Defend Improbable Environments
+
+No resolvable home directory, a config directory the user moved out from under
+the tool that owns it — `wt`'s behavior there is the least of that user's
+problems. Take the working environment as a precondition and drop the fallback
+chain rather than carrying code that is maintained forever and exercised by
+nobody. Dropping a fallback still means failing with an error, never
+`.expect()` — see **Error Handling**. Data safety is the exception, and it has
+its own section.
+
+### Other
+
+- **Don't suppress warnings** with `#[allow(dead_code)]` — delete the code or add `// TODO(topic): used by <upcoming work>`.
+- **System docstrings** — complex systems (state machines, cached state, cross-module coordination, non-obvious invalidation) get a module-level spec docstring (purpose, key decisions, contracts, invariants); keep it current. Exemplar: `commands/list/collect/mod.rs`.
+- **No test code in library code** — no `#[cfg(test)]` convenience methods on library types; tests call the real API or define their own helpers.
+- **Multiline strings** — plain literals with real embedded newlines (`r#"…"#` to avoid escaping `"`); never `\` continuation (silently strips following whitespace) or `concat!()`. Place long constants at module level.
+
+## Error Handling
+
+`anyhow` with context. `bail!` for business-logic errors (dirty worktree, missing branch, invalid state); `.context()` for wrapping I/O and external-command failures. Never `.expect()` / `.unwrap()` in a function returning `Result` — use `?`, `bail!`, or return an error.
+
+## Config Deprecation
+
+All config deprecation lives in one layer: pre-deserialization TOML migration in `src/config/deprecation.rs`. `migrate_content()` rewrites deprecated patterns into canonical form before serde parses; `check_and_migrate()` reuses it, and additionally detects patterns and emits per-process-deduped warnings (the user materializes migrations via `wt config update`). **Never silently drop an old config key** — that's a silent behavior change for users; migrate it.
+
+Every deprecation is one row in the `DEPRECATION_RULES` table: a single idempotent function that rewrites the pattern AND returns the `DeprecationKind`s for what it changed — there is no separate detection function, so detection and migration share one predicate and cannot drift. Detection runs the same functions against a scratch copy of the document (progressively, so a rule sees earlier rules' rewrites); the invariant for warning rules is **a warning fires exactly when `wt config update` would change the file**, pinned by `test_warning_fires_iff_update_changes` — add new edge cases to its battery. The row variant decides when the rewrite applies: `Structural` rewrites on every load; `UpdateOnly` only via `wt config update`, for deprecated forms that still work at runtime; `Silent` rewrites on every load with no warning — its function signature has no channel for a kind, which is what scopes the invariant to `Structural` and `UpdateOnly`. Table order is both the warning-emission order and the migration order. Each `DeprecationKind` carries its own display payload, so wording it is a match over the kinds — twice, in one file: `format_warning_lines()` names what a load still has ahead of it, `format_applied_lines()` what a config mutation's write already did. A config that can't be rewritten safely (a malformed value, an occupied destination key) is left untouched and unwarned — serde's type or unknown-field error is the messaging; an empty deprecated section is also left alone, with no message at all (it contributes no config). Adding a deprecation: (1) one idempotent migrate-and-report function; (2) a `DeprecationKind` variant plus its match arm in each of those two renderers; (3) a `DEPRECATION_RULES` row; (4) for a removed top-level section, add a `DeprecatedSection` to `DEPRECATED_SECTION_KEYS` (canonical key plus display form) so `warn_unknown_fields` defers to the deprecation messaging and suggests the correct config file. A silently-migrated rename (e.g. `pre-create` → `pre-start`) is a `Silent` row with no variant. Renaming a field within a section follows the same shape via a TOML-level rename function (see `migrate_negated_bool`); the struct never needs the old field since migration precedes serde.
+
+**What an update writes must load clean.** A rule that moves a section's table wholesale (`[select]` → `[switch.picker]`) removes the keys its destination struct has no field for and reports each one (`drop_unsupported_keys`); a key removal that empties a `[projects."<id>"]`-scoped section removes the section too. Otherwise the key or the empty section ends up at a path the user never typed, `warn_unknown_fields` names that path on every command, and `wt config update` — the command the deprecation hint points at — writes it into the file rather than clearing it, so the warning outlives every fix available to the user. `test_warning_fires_iff_update_changes` pins both halves: what the update writes raises no deprecation warning and no unknown-field warning. The removal is reported and the key had no home in either config file, so this does not conflict with "never silently drop a key". A key that is merely *misplaced* (valid in the other config, such as a user-only `commit.generation.command` in project config) stays, and keeps its redirect warning; that is why `drop_unsupported_keys` gets the union of the destination's schemas across config types. Those schemas must carry no `#[serde(alias)]`, which `schema_property_names` cannot see.
+
+## Adding CLI Commands
+
+Recipe, help-text placement, and flag-description conventions: `src/commands/AGENTS.md`.
+
+## Accessor Function Naming
+
+| Prefix | Returns | Side effects | Absent → | Example |
+|--------|---------|--------------|----------|---------|
+| (bare noun) | `Option<T>` / `T` | none (may cache) | None/default | `config()`, `switch_previous()` |
+| `set_*` | `Result<()>` | writes state | errors | `set_config()` |
+| `require_*` | `Result<T>` | none | errors | `require_branch()` |
+| `fetch_*` | `Result<T>` | network I/O | errors | `fetch_pr_info()` |
+| `load_*` | `Result<T>` | file I/O | errors | `load_project_config()` |
+
+No `get_*` — bare nouns follow Rust stdlib convention.
+
+## Repository Caching
+
+`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 leaves the old answers in place.** The persistent entries are keyed on SHA pairs with no TTL, so 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. Nothing invalidates these on an upgrade, deliberately: a cache version is permanent machinery for a transition that has come up once. So when a generator behind one of `sha_cache`'s kinds changes, the PR description says what the old answers get wrong, which is where that trade gets decided.
+
+## Releases
+
+Use 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/CLAUDE.md b/CLAUDE.md
index afa094d5c..43c994c2d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,251 +1 @@
-# Worktrunk Development Guidelines
-
-## Quick Start
-
-```bash
-cargo run -- hook pre-merge --yes # all tests + lints (runs automatically in wt merge)
-```
-
-Claude Code web: run `task setup-web` first. Test commands, isolation, and coverage investigation: `tests/CLAUDE.md`.
-Codex Cloud: use the setup in `.codex/cloud.sh`.
-
-## Project Status
-
-Maturing mode: a growing user base, so balance clean design with compatibility.
-
-- New features are welcome, but a command, option, user-facing concept, or configuration key is a product decision. Its user value must justify the code and documentation surface it adds.
-- Consolidate or remove existing prose and machinery before adding another explanation, mode, or special case.
-- External-interface breaks need justification (a real improvement, not cleanup); prefer deprecation warnings over silent breaks.
-- **Protected interfaces:** config file format (`wt.toml`, user config) and CLI flags/arguments. Everything else (internal APIs, output formatting, log locations) is flexible.
-- No Rust library compatibility concerns (CLI tool only).
-- MSRV: latest stable − 1, bumped during weekly tend maintenance (`running-tend` skill).
-
-## Terminology
-
-Use consistently in docs, help text, and code comments:
-
-- **main worktree** — the original git directory (from clone/init); bare repos have none
-- **linked worktree** — created via `git worktree add` (git's term)
-- **primary worktree** — the "home" worktree: main worktree for normal repos, default-branch worktree for bare repos
-- **default branch** — the branch (main, master, …), not "main branch"
-- **target** — destination for merge/rebase/push ("merge target"). Never use "target" for worktrees; say "worktree"
-
-## Skills
-
-Load relevant skills before starting; reload when scope changes mid-session. Project-local skills live in `.claude/skills/`, with `.agents/skills` linking Codex to the same files:
-
-- `writing-user-outputs` — before editing code that calls `warning_message`, `hint_message`, `error_message`, `info_message`, `eprintln`, `println`, or otherwise produces user-visible strings (CLI help, progress UI, snapshots).
-- `running-tend` — operating in CI or writing tend workflows.
-- `release` — cutting a release.
-
-## Worktree Model
-
-- Worktrees are **addressed by branch name**, with a worktree's own path as an alias — resolved branch-first by `Repository::resolve_worktree`, the one canonicalizer every worktree-naming argument routes through. A path is not a second addressing scheme: it names what a branch cannot (a detached worktree, one of two checkouts of a branch). So document arguments as taking a branch, state the path alias once rather than per argument, and give a new argument the canonicalizer rather than its own rule.
-- Each worktree maps to **exactly one branch**.
-- **Never retarget an existing worktree** to a different branch; create/switch/remove instead. (Sole exception: `wt step promote`, experimental, exchanges branches between two worktrees.)
-
-## Documentation
-
-Behavior changes require doc updates. `src/cli/mod.rs` (`after_long_help` plus clap attributes) is the PRIMARY SOURCE for command pages; their rendered mirrors in `docs/src/content/docs/` and `skills/worktrunk/reference/` are generated, as is all of `plugins/worktrunk/skills/` — but both directories also hold hand-edited primaries (non-command docs in `docs/src/content/docs/`, skill-only pages like `troubleshooting.md` in the reference dir), so check which file is primary in the sync taxonomy before editing. Ask: "does `--help` still describe what the code does?" `cargo test --test integration test_docs_are_in_sync` checks doc sync; editing help text (`after_long_help`, `about`, arg docs) also changes the rendered `--help` snapshots, which that test leaves untouched — `cargo insta test --accept --test integration -- test_help` regenerates them (the pre-merge hook runs both). Sync taxonomy, help-text authoring (three render contexts, link text, config-TOML blocks): `docs/CLAUDE.md`.
-
-## Plugin Layout
-
-Per-tool layout and path resolution (Claude/Codex/Gemini), the convention-only Claude manifest, the Codex inline-hooks rationale, the generated plugin-skills mirror, the accepted `wt-switch-create` tradeoff, and `test_plugin_layout_is_consolidated`: `plugins/worktrunk/CLAUDE.md`.
-
-The Pi-family integrations are two commands because they are two agents. `wt config plugins pi` targets Pi (earendil-works/pi), which loads `ExtensionAPI` extensions from `~/.pi/agent/extensions/`; `wt config plugins omp` targets oh-my-pi, which loads `HookAPI` hooks from `~/.omp/agent/hooks/pre/`. Path rules live in `src/commands/config/pi.rs` and `src/commands/config/omp.rs`; the embedded sources are `dev/pi-extension.ts` and `dev/omp-hook.ts`. Neither file is interchangeable — the loaders differ, and so do the config roots (`$PI_CODING_AGENT_DIR` for Pi; `$PI_CONFIG_DIR`, `$OMP_PROFILE`/`$PI_PROFILE`, and `$PI_CODING_AGENT_DIR` for oh-my-pi).
-
-## Data Safety
-
-Never risk data loss without explicit user consent. A failed command that preserves data beats a "successful" one that silently destroys work.
-
-- **Prefer failure over silent loss** — if an operation might destroy untracked files, uncommitted changes, or user data, fail with an error.
-- **Explicit consent for destructive ops** — force-removing data (e.g. `--force` on remove) requires the user to explicitly request it.
-- **No implicit destructive side effects** — never silently delete/overwrite as a side effect of an unrelated operation; make cleanup a separate explicit action the user chooses.
-- **Favor the failing variant on races** — `git reset --keep` (fails if tracked files were modified) over `--hard`; `git checkout --merge` over `--force`. If no safer variant exists, document the risk inline.
-- **Time-of-check vs time-of-use** — be conservative when there's a gap between the safety check and the operation. `wt merge` verifies clean before rebasing, but files could appear before cleanup — don't force-remove during cleanup.
-- **Replace full files, never truncate them** — `fs::write` truncates before it writes, so a crash mid-write leaves the file empty. Every full-file rewrite worktrunk can't put back (shell wrappers, `config.toml`, `approvals.toml`, another tool's `settings.json`) goes through `utils::write_atomically`, which renames a sibling temp file over the target; the spec on that function covers symlinks, mode, and what a rename costs. When a user-owned file was observed missing, `utils::write_new_atomically` refuses to overwrite one that appears before persistence. Adding to an existing Bash, Zsh, or PowerShell rc file instead opens it in append mode, so a stale snapshot cannot replace concurrent edits; never truncate the file to recover from an append error. Don't grow the install path into a rebuild. Removal still rewrites those rc files whole (`uninstall_previewed_lines`), which is why the `write_atomically` spec still names them. Regenerable content (the cache, the `-vv` diagnostic report) keeps the plain write.
-- **A path the user named is written, not second-guessed** — `wt config update --output <path>` replaces whatever is there, the way `cp` and a shell redirect do, and pointed at the config being migrated it writes the migration there too. No-clobber belongs to the other case: a path worktrunk chose itself and observed absent (a shell rc file, `wt config create`), where a file appearing before the rename is one wt never read and a dangling symlink is a dotfile manager's link to keep. Deciding between the two at a call site is the smell — each write site is in one case or the other, so it calls one function unconditionally.
-- **Shell-config concurrency has a deliberate boundary** — the append lock coordinates Worktrunk installers, and no-clobber creation turns the missing-file race into a fail-and-rerun outcome. An editor save racing rc-file uninstall can still be overwritten; accept this final check-to-rename window because sidecar locks, backups, retries, and extra pre-rename checks do not close it. Revisit after an observed incident or a simpler write design. Worktrunk-owned wrappers and completions use last-writer-wins semantics, as does the merge into another tool's `settings.json`.
-
-These stop where git's own protections stop, and matching git is deliberate in each case. The named spec says why:
-
-- `wt merge` and `wt step push` overwrite an ignored file in the destination worktree whose path the incoming commits track, exactly as a `git merge` run there would (`src/commands/worktree/push.rs`).
-- Removal's final dirty-worktree gate is answered by the fsmonitor daemon under `core.fsmonitor`, exactly as `git worktree remove`'s own gate is (`src/git/remove.rs`).
-
-Full inventory: FAQ [What files does Worktrunk create?](docs/src/content/docs/faq.md#what-files-does-worktrunk-create) and [What can Worktrunk delete?](docs/src/content/docs/faq.md#what-can-worktrunk-delete). Review new code that changes this surface against those sections.
-
-## Command Execution Principles
-
-### All Commands Through `shell_exec::Cmd`
-
-Every external command goes through `shell_exec::Cmd` for consistent debug logging (`$ git status [worktree-name]`) and `[wt-trace]` timing. Never call `cmd.output()` directly. For git, prefer `Repository::run_command()` (wraps `Cmd` with worktree context). `Cmd` has four execution modes — `run` (capture), `stream` (inherit stdio), `delayed_stream` (buffer then stream to stderr, for slow ops like `git worktree add`), and `pipe_into` (two-stage pipe). Pipe stdin via `.stdin_bytes(...)`.
-
-```rust
-Cmd::new("git").args(["status", "--porcelain"]).current_dir(&wt).context("worktree-name").run()?;
-Cmd::new("gh").args(["pr", "list"]).run()?; // no context for standalone tools
-```
-
-**The `[wt-trace]` command record has one emitter: `CommandTrace` in `src/trace/emit.rs`.** The grammar lives there too (don't hand-write `log::debug!("[wt-trace] …")`). `CommandTrace::{complete,fail}` are the only callers of the private `command_completed`/`command_errored` writers, so a subprocess is either traced through the guard or produces no command record. Most spawns get this for free via `Cmd`. A few spawn sites have I/O shapes `Cmd` can't model and construct a `CommandTrace` directly: the concurrent-command runner (`output/concurrent.rs`), pipeline steps (`commands/run_pipeline.rs`), `wt step tether`, and the fsmonitor daemon launch. **Any new spawn site that runs an in-process command must construct a `CommandTrace` (start it just before spawn; `complete(success)` after wait, `fail(err)` on spawn/wait error)** — otherwise the command shows up as an unattributed gap in `wt-perf timeline`. The guard is `#[must_use]` and trips a debug-build assertion if dropped unresolved, so a forgotten `complete`/`fail` fails tests rather than silently going untraced. Detached background children (`commands/process.rs`) and interactive helpers (pagers, shell probes) are intentionally untraced — they outlive the invocation or aren't part of its timeline.
-
-### Git-Discovery Env Vars Follow Who Chose the Cwd
-
-Git resolves `GIT_DIR`/`GIT_WORK_TREE` (and the rest of `INHERITED_GIT_PATH_VARS`) before walking up from the cwd, so an inherited value silently overrides a child's working directory. **Any spawn site whose cwd names a `wt`-chosen worktree must scrub these vars** (`Cmd::scrub_git_discovery_env` or `scrub_git_discovery_env_vars`) — both relocated user commands (hooks, `wt step for-each`, the `--execute` program) and `wt`'s own worktree-local plumbing (`WorkingTree::run_command`, `TempIndex::command`). A site that supplies its own value for one of the scrubbed vars sets it after the scrub; `Cmd` applies env mutations in call order, so the set wins. Children running in the user's own context (aliases, `commit.generation`) and repo-level plumbing (`Repository::run_command`) keep the inherited context (absolutized) — that exemption is about scope, not cwd: `Repository::at` is handed a `wt`-chosen worktree at several sites, but repo-level questions are worktree-agnostic within one repository, and every worktree-scoped answer routes through `WorkingTree`. Full site classification and rationale: `scrub_git_discovery_env_vars` in `src/shell_exec.rs`.
-
-### Real-time Output Streaming
-
-Stream command output line-by-line rather than buffering. Responsiveness is a priority.
-
-### Structured Output Over Error-Message Parsing
-
-Prefer exit codes / `--porcelain` / `--json` over parsing human-readable messages, which break on locale, version, and rewording changes. `git merge-base` exit codes encode meaning (0 found, 1 no common ancestor, 128 invalid ref) — branch on `status.code()`, not message text.
-
-| Tool | Fragile | Structured |
-|------|---------|------------|
-| `git diff-tree` / `diff-index` | `--stat` (localized) | `--numstat`, `--shortstat` (`(+)`/`(-)` hardcoded) |
-| `git status` | default | `--porcelain=v2 -z` |
-| `git merge-base` | error messages | exit codes |
-| `gh` / `glab` | default | `--json` |
-
-When no structured alternative exists, document the fragility inline.
-
-### Plumbing for Output `wt` Consumes
-
-Porcelain commands read display configuration that changes what they report: `diff.relative` once made `wt remove` delete an unmerged branch, and `color.ui=always` and `diff.external` leaked into LLM prompts. When `wt` parses, caches, renders, or prompts with git's output, it runs plumbing (`diff-tree`, `diff-index`, `diff-files`, `for-each-ref`), which ignores that configuration apart from `submodule.<name>.ignore`. `PlumbingDiff::args` builds every plumbing diff with `--ignore-submodules=none` to override that setting, and a test rejects one spelled by hand. Rendered and prompted diffs go through `PreparedDiff::capture`, which also restores the `git diff` defaults plumbing lacks. `git status` has no plumbing equivalent, so it pins its behavior with explicit flags. Output shown as git's own view, like `wt step diff`, stays porcelain.
-
-### Immutable Ids Over List Positions
-
-`stash@{0}` names a position in a list any process can reorder, so a handle captured before a mutation window and used after it can resolve to a different object — restoring the target worktree's autostash by position after `git push` silently restored a concurrent writer's entry and reported success. Capture the immutable id instead (`git stash list --format=%H`, `git stash create`, `rev-parse`) and act on that; where an operation accepts only a positional selector, re-derive it from something stable immediately beforehand. An index into a collection `wt` owns is a different thing — this is about namespaces other processes can mutate. The strongest form is not to enter the shared namespace at all: the autostash this rule came from was later deleted outright, replaced by a two-tree merge that leaves the target worktree's changes in place (`advance_target` in `src/commands/worktree/push.rs`).
-
-### Network Access
-
-worktrunk is local-first: the network is touched only when the user asked for it, and only where reaching the wire directly serves that request. **One detection helper is exempt:** the *first* `Repository::default_branch()` per repo may fall through to `git ls-remote`; the result caches in `worktrunk.default-branch` and every later call is local. The query is bounded by `REMOTE_DETECTION_TIMEOUT` — nothing in git bounds it, and an unreachable host costs ~127 s per address on Linux — and a query that hits the bound falls back to local inference *without* caching it, so an outage can't make a guess permanent. No other detection helper may add a similar fallback.
-
-Why: silent "lookup" paths that walk to the wire (alias dispatch, hook context build, recovery) stall commands the user wouldn't expect to do network work, worst on a fresh clone. The `default_branch()` bootstrap keeps a fresh clone usable while bounding the exception to one helper firing at most once per repo.
-
-**Network never blocks the first write.** Fast output to the terminal is the priority (Real-time Output Streaming, above): every command paints from local data first, then network-derived detail streams in progressively behind it. A command that can't render its first frame until `gh` or `git fetch` returns is the failure mode, worst on a fresh clone or a slow link. Before adding an accessor that could reach the wire (`gh`, `glab`, `git fetch`, `git ls-remote`, HTTP), confirm it renders progressively and never gates the first paint. A synchronous hot path like a shell prompt is stricter: it must not reach the wire at all, even progressively. `wt list statusline` is not such a path despite running on every prompt, because Claude Code consumes its output asynchronously.
-
-**The picker is the most forgiving home for network work, because its lifetime is bounded by the user, not the job.** It paints immediately, the user browses, and a slow forge call streams into the rows whenever it arrives; if the user picks first, the picker's exit cancels the unfinished request (`shell_exec::cancel_background_commands`), so its latency never costs anything. A run-to-completion command is less forgiving: `wt list` renders progressively but still cannot *finish* until every task returns, so a slow `gh` call extends the command the user is waiting on. Prefer the picker for live forge data, and fetch it there progressively.
-
-What currently reaches the wire:
-
-- `wt list --full`, `wt list statusline` — CI status; also plain `wt list` (table) when `[list] columns` names `ci`, which forces the column (and its fetch) on without `--full`. `--format json` plans off `--full` alone, so a display setting can't send a machine-readable call to a forge
-- `wt switch` (interactive picker, no target) — per-row CI status, primed from the local cache then fetched live and streamed into the rows; once a row's CI fetch surfaces an open PR/MR, a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) fills that row's `comments` preview tab — the same fetch a `--prs` row makes, spawned once per row from `progressive_handler` (see `picker::prs::spawn_comments_fetch`). The `comments` tab is the only PR data fetched lazily here; `pr` rides the CI call and `log` is the local `git log`
-- generating a branch summary with a `commit.generation` command
-- generating a commit message with a `commit.generation` command
-- `wt switch pr:<n>`, `wt switch mr:<n>` — host API to resolve the PR/MR, then `git fetch` of its branch
-- `wt switch --prs` — one `gh pr list` / `glab mr list` to populate the interactive picker (streamed in after the frame paints), then a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) to fill each row's `comments` preview tab, plus a `gh pr view <n> --json commits` / `glab api …/commits` for the `log` tab **only when the head commit isn't already local** — a `--prs` row whose `headRefOid`/`sha` resolves in the object store renders the `log` tab from a local `git log` with no network (off the pool, once per row when the rows land — see `picker::prs::spawn_pr_previews`)
-- `wt config show --full` — version check against GitHub
-- the first `Repository::default_branch()` per repo — `git ls-remote` (above)
-
-### Signal Handling: Ctrl-C Cancels the Current Command
-
-When a child process exits from a signal (SIGINT, SIGTERM), every loop in the foreground execution path MUST abort rather than continue to the next iteration. This applies to worktree loops (`wt step for-each`), hook pipelines, alias steps, concurrent groups, and any future code running multiple child processes in sequence.
-
-Why: wt installs a `signal_hook` SIGINT/SIGTERM handler so it can forward signals to child process groups before exiting cleanly. As a side effect wt itself does not die from the user's Ctrl-C — only the current child does. Without this policy a single Ctrl-C against `wt merge` would charge through the remaining hook steps, with `FailureStrategy::Warn` silently swallowing each interrupt.
-
-- Signal-derived child exits surface structurally: stream mode (`Cmd::stream`) as `WorktrunkError::ChildProcessExited { signal: Some(sig), .. }`, capture mode (`Cmd::run`) as `CommandError { signal: Some(sig), .. }`. These fields are the structured channel — never sniff `code >= 128` or parse error messages.
-- Detect via `err.interrupt_signal()` (the `worktrunk::git::ErrorExt` trait). When it returns `Some(signal)`, propagate as `WorktrunkError::Interrupted { signal, hint }` and break the loop. `Interrupted` exits `128 + signal` (130 SIGINT, 143 SIGTERM) and renders once, at exit, per shell convention: silent for SIGINT (the terminal echoed `^C`), `Terminated` for SIGTERM — the line the shell would print if wt weren't trapping the signal. `hint` carries an optional recovery line for state the interrupt left behind (e.g. a mid-rebase worktree).
-- In capture mode only SIGINT/SIGTERM classify as interrupts. Capture children get no forwarding or escalation, and their captured output would be discarded by the silent exit — so a child killed by any other signal (a crash, an OOM kill) surfaces as a visible error instead. A capture child with a `Cmd::timeout` is the one the tty broadcast doesn't reach: it runs in its own process group so expiry can tear down its whole tree (`run_with_timeout_impl`), which is what makes the bound bound anything, so a Ctrl-C during one waits out the remaining timeout. Stream mode counts any signal: output already streamed to the terminal, and user-initiated kills are normalized upstream to the originating SIGINT/SIGTERM (`seen_signal` in `shell_exec`, the concurrent runner's originating-signal override).
-- The check happens **before** any `FailureStrategy` branch — Warn must NOT swallow signal-derived errors.
-- `handle_command_error` in `src/commands/command_executor.rs` enforces this for hook and alias pipelines (foreground and concurrent groups); `for_each.rs` enforces it for the worktree loop. New code that loops over child processes calls `.interrupt_signal()` on per-iteration errors and breaks.
-
-### Project Commands Run Only After Approval
-
-**Policy:** project-defined commands (`pre-*` / `post-*` hooks, `[aliases]`, `--execute` bodies from project config) are arbitrary code shipped in a repo the user may have just cloned, so they run only after the approval system (`Approvals` plus `approve_command_batch` / `approve_or_skip` in `src/commands/command_approval.rs`) clears them. Never build a code path that runs project commands without that gate. A context that can't prompt (a TUI mid-render, a background recovery path) consults the approval state read-only and runs only the already-approved subset: `commands::picker::do_removal` builds the plan via `HookPlan::approve_readonly` (no prompt).
-
-**Why:** the gate is the only thing between `git clone && wt switch` and a `post-switch` hook running `curl … | sh`. A "we already validated the operation, so run the hooks too" shortcut turns every command that touches project config into remote code execution.
-
-**Implementation:** the operation-driven hooks (`pre-merge`, `post-merge`, `pre-remove`, `post-remove`, `post-switch`, `pre-start`, `post-start`) are gated *before* a state mutation and run *after* it, so a second config read could select an unapproved command. `src/commands/hook_plan.rs` closes this structurally: each gate (`wt remove` / `wt merge` / `wt step prune` / `wt switch`) selects the command set once into an immutable `ApprovedHookPlan` (`HookPlan::approve`); the executor consumes only that value via `execute_planned_hook` / `register_planned` and holds no `ProjectConfig` to re-derive from, so re-selection is a compile error, not a review check. An empty plan (`--no-hooks`, declined, or no project config) runs nothing. The adjacent hooks with no gate→exec mutation (`pre-commit`, `post-commit`, `pre-switch`, `wt hook <type>`, aliases) still resolve config at invocation via `execute_hook` / `HookAnnouncer::register`. See `src/commands/hook_plan.rs` and the `commands::hooks` module spec.
-
-### Background Hook Pipelines Run Concurrently, Per Source
-
-A `post-*` batch spawns one detached pipeline per source, and they run at once. Don't serialize them: `post-start` is documented for dev servers and `wt step tether`, so a user hook that never exits would block the project's forever, and `wt merge`'s batch spans two worktrees (`post-commit` anchors on the invoking worktree, the rest on the destination) so chaining also drops hooks behind a head whose worktree is already removed. That span is also why the flush can reach a pipeline whose anchor is gone: the merge removes `post-commit`'s worktree first, so the removal reports it through `HookAnnouncer::mark_worktree_removed` and the flush drops that pipeline rather than spawning it into a path whose git discovery would resolve to the primary worktree. The removal is what knows — where its fast rename into `.git/wt/trash/` fails, the fallback `git worktree remove` runs detached and the anchor is still on disk at the flush, so a filesystem probe would answer differently on the two paths. The cost is that two hooks touching one worktree's git state can collide — two `git pull`s there append to each other's `FETCH_HEAD` and both fail — which `wt hook --help` tells users to avoid by keeping dependent commands in one source.
-
-## Hook Output Logs
-
-`.git/wt/logs/` layout — per-branch and repo-wide log paths, plus the `sanitize_for_filename` filename rule: the `HookLog` spec in `src/commands/process.rs`. The top-level file-vs-directory split that `wt config state` walks: the "Log layout invariant" in `src/commands/config/state.rs`.
-
-## Coverage
-
-**`codecov/patch` gates the merge, not the design.** Write the change the design calls for, then deal with the check. A predicted red patch is never a reason to shelve or water down an improvement, and neither the code nor the tests get contorted to move the number. The patch target is `auto` (the base commit's project coverage), so a handful of missed lines flips a small patch red, and a refactor that only relocates existing uncovered lines pulls their misses in without changing behavior.
-
-**NEVER merge a PR with failing `codecov/patch` without explicit user approval.** It is marked "not required" in GitHub but still gates merge. On PR heads codecov posts **check runs** (codecov GitHub App), not commit statuses: poll with `gh pr checks <number>` or the check-runs API; the combined-status API (`/commits/<sha>/status`) never shows them, and the check run lands a few minutes after the `code-coverage` job finishes. On failure, close the gap where it's real — write tests, or delete code that's genuinely unused (a specialized error handler where falling through to the general one suffices; never a rarely-reached backstop that's load-bearing). Where it isn't real — misses that predate the change, or a path with no deterministic trigger — push the change and ask before merging, handing over the arithmetic: which lines, why they can't be covered, what the patch percentage comes to. Coverage runs include `--features shell-integration-tests` (CI `code-coverage` and local `task coverage`) — don't dismiss failures by claiming the feature is off. Investigation commands, moved-line false positives, and the "N functions mismatched" warning: `tests/CLAUDE.md`.
-
-## Benchmarks & Traces
-
-`cargo bench --bench list <filter>` (Criterion takes a positional substring filter; there's no `--skip`). `cargo run -p wt-perf -- timeline -- <args>` traces one `wt` invocation. Real-repo benchmarks clone rust-lang/rust on first run. Benchmarks run as a standalone scheduled workflow (`.github/workflows/benchmarks.yaml`, daily cron plus `workflow_dispatch`), not on PRs, so they never gate a merge; only `test (linux|macos|windows)` block it. Filter map, expected numbers, and trace queries: `benches/CLAUDE.md`.
-
-## Code Quality
-
-### Use Existing Dependencies
-
-Check `Cargo.toml` before hand-rolling a utility:
-
-| Need | Use | Not |
-|------|-----|-----|
-| Path normalization | `path_slash::PathExt::to_slash_lossy()` | `.to_string_lossy().replace('\\', "/")` |
-| Shell escaping | `shell_escape::unix::escape()` | manual quoting |
-| ANSI colors | `color_print::cformat!()` | raw escape codes |
-| Template var detection | `minijinja::undeclared_variables(false)` | regex/substring on `{{ var }}` |
-
-Delegation extends past utilities to **another tool's own rules** — where zsh
-reads its config, which TOML keys a schema accepts, how MiniJinja scopes a
-template binding. Ask the library; don't re-derive its rule inside `wt`. A
-re-derived rule is correct on the cases that motivated it and drifts silently
-afterwards. Where the library exposes no API that answers the question, keep
-the substitute no larger than the question and say in the code why it exists.
-
-### Don't Defend Improbable Environments
-
-No resolvable home directory, a config directory the user moved out from under
-the tool that owns it — `wt`'s behavior there is the least of that user's
-problems. Take the working environment as a precondition and drop the fallback
-chain rather than carrying code that is maintained forever and exercised by
-nobody. Dropping a fallback still means failing with an error, never
-`.expect()` — see **Error Handling**. Data safety is the exception, and it has
-its own section.
-
-### Other
-
-- **Don't suppress warnings** with `#[allow(dead_code)]` — delete the code or add `// TODO(topic): used by <upcoming work>`.
-- **System docstrings** — complex systems (state machines, cached state, cross-module coordination, non-obvious invalidation) get a module-level spec docstring (purpose, key decisions, contracts, invariants); keep it current. Exemplar: `commands/list/collect/mod.rs`.
-- **No test code in library code** — no `#[cfg(test)]` convenience methods on library types; tests call the real API or define their own helpers.
-- **Multiline strings** — plain literals with real embedded newlines (`r#"…"#` to avoid escaping `"`); never `\` continuation (silently strips following whitespace) or `concat!()`. Place long constants at module level.
-
-## Error Handling
-
-`anyhow` with context. `bail!` for business-logic errors (dirty worktree, missing branch, invalid state); `.context()` for wrapping I/O and external-command failures. Never `.expect()` / `.unwrap()` in a function returning `Result` — use `?`, `bail!`, or return an error.
-
-## Config Deprecation
-
-All config deprecation lives in one layer: pre-deserialization TOML migration in `src/config/deprecation.rs`. `migrate_content()` rewrites deprecated patterns into canonical form before serde parses; `check_and_migrate()` reuses it, and additionally detects patterns and emits per-process-deduped warnings (the user materializes migrations via `wt config update`). **Never silently drop an old config key** — that's a silent behavior change for users; migrate it.
-
-Every deprecation is one row in the `DEPRECATION_RULES` table: a single idempotent function that rewrites the pattern AND returns the `DeprecationKind`s for what it changed — there is no separate detection function, so detection and migration share one predicate and cannot drift. Detection runs the same functions against a scratch copy of the document (progressively, so a rule sees earlier rules' rewrites); the invariant for warning rules is **a warning fires exactly when `wt config update` would change the file**, pinned by `test_warning_fires_iff_update_changes` — add new edge cases to its battery. The row variant decides when the rewrite applies: `Structural` rewrites on every load; `UpdateOnly` only via `wt config update`, for deprecated forms that still work at runtime; `Silent` rewrites on every load with no warning — its function signature has no channel for a kind, which is what scopes the invariant to `Structural` and `UpdateOnly`. Table order is both the warning-emission order and the migration order. Each `DeprecationKind` carries its own display payload, so wording it is a match over the kinds — twice, in one file: `format_warning_lines()` names what a load still has ahead of it, `format_applied_lines()` what a config mutation's write already did. A config that can't be rewritten safely (a malformed value, an occupied destination key) is left untouched and unwarned — serde's type or unknown-field error is the messaging; an empty deprecated section is also left alone, with no message at all (it contributes no config). Adding a deprecation: (1) one idempotent migrate-and-report function; (2) a `DeprecationKind` variant plus its match arm in each of those two renderers; (3) a `DEPRECATION_RULES` row; (4) for a removed top-level section, add a `DeprecatedSection` to `DEPRECATED_SECTION_KEYS` (canonical key plus display form) so `warn_unknown_fields` defers to the deprecation messaging and suggests the correct config file. A silently-migrated rename (e.g. `pre-create` → `pre-start`) is a `Silent` row with no variant. Renaming a field within a section follows the same shape via a TOML-level rename function (see `migrate_negated_bool`); the struct never needs the old field since migration precedes serde.
-
-**What an update writes must load clean.** A rule that moves a section's table wholesale (`[select]` → `[switch.picker]`) removes the keys its destination struct has no field for and reports each one (`drop_unsupported_keys`); a key removal that empties a `[projects."<id>"]`-scoped section removes the section too. Otherwise the key or the empty section ends up at a path the user never typed, `warn_unknown_fields` names that path on every command, and `wt config update` — the command the deprecation hint points at — writes it into the file rather than clearing it, so the warning outlives every fix available to the user. `test_warning_fires_iff_update_changes` pins both halves: what the update writes raises no deprecation warning and no unknown-field warning. The removal is reported and the key had no home in either config file, so this does not conflict with "never silently drop a key". A key that is merely *misplaced* (valid in the other config, such as a user-only `commit.generation.command` in project config) stays, and keeps its redirect warning; that is why `drop_unsupported_keys` gets the union of the destination's schemas across config types. Those schemas must carry no `#[serde(alias)]`, which `schema_property_names` cannot see.
-
-## Adding CLI Commands
-
-Recipe, help-text placement, and flag-description conventions: `src/commands/CLAUDE.md`.
-
-## Accessor Function Naming
-
-| Prefix | Returns | Side effects | Absent → | Example |
-|--------|---------|--------------|----------|---------|
-| (bare noun) | `Option<T>` / `T` | none (may cache) | None/default | `config()`, `switch_previous()` |
-| `set_*` | `Result<()>` | writes state | errors | `set_config()` |
-| `require_*` | `Result<T>` | none | errors | `require_branch()` |
-| `fetch_*` | `Result<T>` | network I/O | errors | `fetch_pr_info()` |
-| `load_*` | `Result<T>` | file I/O | errors | `load_project_config()` |
-
-No `get_*` — bare nouns follow Rust stdlib convention.
-
-## Repository Caching
-
-`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 leaves the old answers in place.** The persistent entries are keyed on SHA pairs with no TTL, so 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. Nothing invalidates these on an upgrade, deliberately: a cache version is permanent machinery for a transition that has come up once. So when a generator behind one of `sha_cache`'s kinds changes, the PR description says what the old answers get wrong, which is where that trade gets decided.
-
-## Releases
-
-Use 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/Taskfile.yaml b/Taskfile.yaml
index c26a19cf7..87cc61db1 100644
--- a/Taskfile.yaml
+++ b/Taskfile.yaml
@@ -15,7 +15,7 @@ tasks:
profile-tests:
desc: Run the suite under CPU accounting and report where the time goes
- # tests/CLAUDE.md → Profiling the Suite covers how to read the numbers.
+ # tests/AGENTS.md → Profiling the Suite covers how to read the numbers.
cmds:
# Build first so the measurement covers the test run alone.
- cargo nextest run --no-run --features shell-integration-tests
diff --git a/benches/AGENTS.md b/benches/AGENTS.md
new file mode 100644
index 000000000..cf25466f6
--- /dev/null
+++ b/benches/AGENTS.md
@@ -0,0 +1,437 @@
+# Benchmark Guidelines
+
+See `list.rs` and `time_to_first_output.rs` headers for benchmark groups and run examples.
+
+## Quick Start
+
+Criterion's CLI takes a positional `FILTER` (substring inclusion) and `--exact`. There's no `--skip`; pick a filter that *includes* what you want instead.
+
+```bash
+# Fast iteration (one generated group, warm cache only)
+cargo bench --bench list skeleton/warm
+
+# Run specific group (all variants)
+cargo bench --bench list full
+
+# GH #461 scenario (50 branches at varying depths in the imported corpus)
+cargo bench --bench list large_repository
+
+# All list benchmarks (~1 hour)
+cargo bench --bench list
+
+# Time-to-first-output benchmarks
+cargo bench --bench time_to_first_output # all commands
+cargo bench --bench time_to_first_output remove # just remove
+
+# wt step prune (scan + removal on the squash-merged fixture)
+cargo bench --bench prune # generated variants
+cargo bench --bench prune --features large-repository-benches prune_large_repository # multi-gigabyte temporary fixture
+
+# Picker preview pre-compute (wt switch preview workload)
+cargo bench --bench picker_preview # all variants
+cargo bench --bench picker_preview warm # warm only
+
+# Shell completion (COMPLETE=$SHELL wt -- wt switch <Tab>) — one variant, no filter
+cargo bench --bench completion
+```
+
+## Fixtures and Benches
+
+Bench groups name measurements; fixture recipes name corpus provenance. Both
+bases produce ordinary Git repositories: `Generated` builds the corpus locally,
+while `Imported` copies a pinned upstream corpus. Preserve the state dimensions
+needed for coverage and fidelity, not historical recipes or the ability to
+recreate an old setup. A property does not get its own fixture identity merely
+because one benchmark studies it.
+Worktree, branch, and remote-ref counts are controlled population parameters;
+prune candidates are an overlay. Add another base only when the corpus itself
+cannot serve one of these roles.
+
+| Canonical base | `wt-perf setup` | Bench group(s) |
+|---|---|---|
+| `Generated { linked_worktrees: W, branchless_branches: B, remote_tracking_refs: R }` | `setup generated W B R --path <path>` | all generated benchmarks |
+| `Imported` | `setup imported --path <path>` | `large_repository` and `prune_large_repository` |
+
+`linked_worktrees` excludes the primary worktree. `branchless_branches` have
+no linked worktree. `remote_tracking_refs` excludes the `origin/main` and
+`origin/HEAD` pair every generated fixture has. The generated defaults are 7,
+50, and 0 respectively, giving ordinary benchmarks eight total worktrees plus
+branches spread across its history. The imported base always has the same
+eight total worktrees and fifty history-spread branches.
+
+Add prune state with `--prune-candidates M --prune-backdrop U`. Each count is
+a pair: one linked worktree and one branchless branch. The benchmark catalog
+applies it to generated and imported fixtures. This is an overlay on the
+canonical base, not a separate fixture recipe.
+
+Every benchmark recipe returns `FixtureRepo`, the owner of the temporary root
+plus the canonical primary/linked-worktree paths. Repo-bound benchmark
+subprocesses start through `wt_command`, and warm/cold matrices use
+`CacheState::WARM_AND_COLD`; keep lifecycle, environment isolation, and cache
+labels in those shared APIs.
+
+## Imported corpus
+
+`benches/imported-fixture` pins the corpus and commit.
+The first matching acquisition clones that revision; later runs reuse the
+revision-keyed source under `target/wt-perf/bench-repos/imported/`.
+Source construction is locked across processes, built in a temporary sibling,
+validated, then atomically renamed into place. Mutable benchmark fixtures are
+always fresh and have no shared lock or repair state.
+
+## Faster Iteration
+
+Criterion has no exclusion flag — narrow the run by picking a substring that matches only the variants you want. Benchmark IDs look like `<group>/<label>/<param>`, e.g. `skeleton/cold/1`, `worktree_scaling/warm/8`, `full/cold`, `large_repository/branches/warm`.
+
+**Pattern matching (positional `FILTER`):**
+```bash
+cargo bench --bench list scaling # All worktree_scaling/* variants
+cargo bench --bench list warm # Every benchmark whose ID contains "warm"
+cargo bench --bench list skeleton/warm # Just skeleton's warm variants
+cargo bench --bench list full # Both cache states of the combined fixture
+cargo bench --bench list -- --exact full/cold # One exact ID
+```
+
+To skip the slow large-repository and divergent groups, target `skeleton`, `worktree_scaling`, or `full`. Run them sequentially if you want more than one.
+
+The `full` group is the place to start when `wt list` regresses on a real mix of worktrees and branches: the cold/warm split says whether the cost is the persistent-cache fill (cold) or the per-process re-fork (warm). A `full` wall time can't be split by side (the git subprocesses overlap on the rayon pool), so to localize a regression, trace one invocation and read the profile's BY CONTEXT table ("Analyzing a trace" below); `worktree_scaling` and `divergent_branches` track the worktree side and branch side respectively at criterion cadence.
+
+## WORKTRUNK_FIRST_OUTPUT
+
+Setting `WORKTRUNK_FIRST_OUTPUT=1` causes commands to exit at the point where first
+user-visible output would appear. Used by `time_to_first_output` benchmarks to measure
+startup latency without output rendering or post-output work (mismatch warnings, hooks).
+
+Supported commands: `switch`, `remove`, `list`.
+
+`wt step prune` deliberately has no `WORKTRUNK_FIRST_OUTPUT` hook: its first
+output is data-dependent (the dry-run path collects and sorts every check
+result before printing anything, so e2e ≈ time-to-first-output already; the
+live path streams whichever check lands first). Use `benches/prune.rs` for
+cadence-tracked numbers and the `prune-*` spans (below) for phase attribution.
+
+## WORKTRUNK_PREVIEW_BENCH
+
+Setting `WORKTRUNK_PREVIEW_BENCH=1` runs `wt switch`'s interactive picker prelude
+end-to-end — collect, speculative spawn, skeleton, initial pre-compute, deferred
+pre-compute — and exits immediately after `PreviewOrchestrator::wait_for_idle()`,
+before skim launches and before any JSON serialization or stderr drain. Used by
+`picker_preview` benchmarks to measure the skeleton-time preview pool workload
+without standing up a PTY. Off-screen worktrees are demand-loaded only after skim
+starts and are intentionally outside this benchmark. Bypasses the picker's TTY
+check, like `WORKTRUNK_PICKER_DRY_RUN=1`.
+
+The hot path inside the env-gated block is identical to the dry-run path; only the
+post-drain output (cache JSON dump + stashed-warning drain) is conditional. Keep new
+post-drain work out of the bench path unless it's part of the workload being
+measured.
+
+## Cache Handling
+
+Worktrunk maintains a persistent SHA-keyed cache at `.git/wt/cache/` plus a git-config
+cache of the default branch at `worktrunk.default-branch`. Both survive process exits,
+so bench iterations read from prior iterations unless invalidated.
+
+**Rule:** explicitly choose cache state for every benchmark that runs a `wt`
+subcommand which populates these caches. Run ordinary warm/cold variants through
+`wt_perf::bench_wt`, the one home of the shared strategy. Destructive variants
+use `iter_custom`: each iteration builds a fresh fixture before starting the
+timer, measures only the command, and checks the postcondition before returning
+the accumulated duration. `remove_e2e` uses warm/cold no-hooks neighbors for
+cache cost and a warm with-hooks neighbor for hook cost;
+`prune_e2e/live` clears probe caches to preserve its probe-cold scenario.
+
+`invalidate_caches_auto` clears:
+
+- `.git/objects/info/commit-graph*`
+- `.git/wt/cache/` (all sha_cache kinds + ci-status + summaries)
+- `worktrunk.default-branch` (git config)
+
+`.git/packed-refs` is deliberately preserved: fixture setup runs `git gc`
+at the end, which packs every loose ref into `packed-refs`
+and prunes the loose copies. Deleting that file post-gc leaves the repo with
+no resolvable refs, so any bench that resolves a branch (e.g. the `with_vars`
+alias's `{{ commit }}` template var) blows up partway through warm-up.
+
+User state — `worktrunk.history`, `worktrunk.hints.*`, `worktrunk.state.<branch>.*`,
+`.git/wt/logs/`, `.git/wt/trash/` — is intentionally preserved. It doesn't affect
+read-path performance and benches may depend on it (e.g., branch markers set during
+setup).
+
+Worktree indexes survive every cache state. Git treats a missing index as every
+tracked file being staged for deletion, which changes the repository rather
+than cooling it. `invalidate_probe_caches` clears only `.git/wt/cache/`; the
+prune benches use it for the first-scan-after-fetch shape while git metadata
+stays warm.
+
+**Which commands populate `.git/wt/cache/`:**
+
+| Command | Populates? | Notes |
+|---------|------------|-------|
+| `wt list` | Yes | Post-skeleton tasks. Exits early under `WORKTRUNK_SKELETON_ONLY=1` / `WORKTRUNK_FIRST_OUTPUT=1` — those skip the writing phase. |
+| `wt remove` | Yes | `prepare_worktree_removal` → `compute_integration_lazy` writes `is-ancestor` / `has-added-changes` / `merge-add-probe` whenever `BranchDeletionMode` is not `ForceDelete` (CLI `--force` is `force_worktree`, not `--force-delete`). |
+| `wt step prune` | Yes | Every scanned worktree/branch runs `integration_reason` → the same probe writes as `wt remove`. First scan after new commits is cold; re-runs are warm (`prune_e2e/dry_run_probe_cold` vs `dry_run_warm`). |
+| `wt switch <branch>` | No | No sha_cache writers on the direct-switch path. |
+| `wt switch` (picker) | Yes | Preview pre-compute writes `picker-preview/{log,branch-diff,upstream-diff}-…` entries. Exercised under `WORKTRUNK_PREVIEW_BENCH=1` / `WORKTRUNK_PICKER_DRY_RUN=1`. |
+| `wt` (completion via `COMPLETE=$SHELL`) | No | Only `for-each-ref` + worktree list. |
+
+Clearing the default-branch cache as part of full invalidation is simpler than
+introducing a separate "warm default branch" mode.
+`invalidate_probe_caches` leaves it warm, like everything else outside
+`.git/wt/cache/`.
+
+**Bench fixtures don't exercise the wire path.** `setup_fake_remote` writes
+`refs/remotes/origin/HEAD` directly into every repo, so a cold-cache iteration
+falls through to the local `<r>/HEAD` lookup, never to `git ls-remote`. The
+cold cost we benchmark is the *configured-remote* cold cost, not the
+*fresh-clone* cold cost. A
+`cold_no_remote` mode (extending `invalidate_caches_auto` to also wipe
+`refs/remotes/origin/HEAD`) would close the gap if the wire-path cost is
+worth measuring at CI cadence.
+
+## Expected relationships
+
+- The 1- and 8-worktree rows track the endpoint cost of adding linked
+ worktrees under both cache modes.
+- Cold rows should be slower than their warm neighbors because they rebuild
+ the persistent caches named above.
+- Large-repository rows amplify history-walk and working-tree costs that generated
+ content cannot model faithfully.
+
+## Recording `wt remove` / `wt step prune` staging
+
+The removal commands interleave per-target work with parallel scans and
+detached background processes; a single e2e number hides which phase moved.
+Record them in two layers:
+
+**Criterion cadence** — `benches/remove.rs` and `benches/prune.rs`. The
+generated prune overlay adds 4 squash-merged worktrees and 4 squash-merged
+branches as candidates, plus 8 two-sided-diverged worktrees and 8 branches as
+backdrop. `prune_large_repository` layers 12 candidate pairs and 24 backdrop pairs
+onto the canonical imported base. Its source clone is cached, but the mutable
+multi-gigabyte fixture is built fresh for the benchmark process and removed
+when it exits. That group is opt-in via `--features large-repository-benches` and
+must never build on a hosted CI runner.
+
+| Variant | What it measures |
+|---------|------------------|
+| `prune_e2e/dry_run_probe_cold` | full parallel scan with `.git/wt/cache/` cleared; git's own caches stay warm, matching the first prune after fetching the default branch |
+| `prune_e2e/dry_run_warm` | steady-state re-scan with integration probes served from sha_cache |
+| `prune_e2e/dry_run_cold` | first scan with worktrunk caches, the default-branch cache, and git's commit graph cleared |
+| `prune_e2e/live` | probe-cold scan plus parallel removal of the 8 candidates |
+| `prune_large_repository/dry_run_warm` | steady-state scan at large-repository history and working-tree scale |
+| `prune_large_repository/dry_run_probe_cold` | the same scan with integration probes rerun; statuses stay stat-warm |
+| `remove_e2e/{warm,cold}/no_hooks` | full removal with and without persistent caches |
+| `remove_e2e/warm/with_hooks` | warm-cache neighbor isolating hook approval and spawning |
+| `first_output/remove` | single-target validation up to first output (`benches/time_to_first_output.rs`) |
+
+Full-cold and live at large-repository scale are **one-shot timelines, not
+criterion groups**. Full-cold adds commit-graph rebuilding; live consumes the
+candidates. Live removals run concurrently inside the `prune-scan` window,
+while packed candidate refs may serialize briefly on `packed-refs.lock`.
+
+An actual first checkout can be slower because every worktree status is
+stat-cold. The cache helpers preserve indexes because removing one changes
+staged state; use a fresh fixture when investigating checkout-cold status.
+The generated fixture can't show it — its statuses are milliseconds — so
+scale-sensitive changes need a one-shot on a fresh imported fixture (or
+`wt-perf timeline -- -C <repo> step prune --dry-run` on a real
+repository) alongside the criterion cadence. All large-repository numbers are
+I/O-bound and move with ambient machine load (sibling builds, Spotlight):
+treat them as shape, not thresholds, and compare Criterion verdicts with
+`uptime`.
+
+The probe-cold prune benches run through `bench_wt` with
+`CacheState::ProbeCold`. Fixture correctness is checked outside the timed
+loops: a post-setup dry-run pins the candidate count, and every live sample
+must consume its fresh fixture's candidate refs while retaining the backdrop.
+
+**Phase attribution** — `wt-perf timeline` plus the removal spans. Prune emits
+`prune-gather` (worktree+branch enumeration), `prune-scan` (the whole parallel
+check region), one `prune-check:<ref>` per scanned item, and one
+`prune-remove:<label>` per removed candidate; `wt remove` emits
+`internal-sweep` around its end-of-command janitor. The `prune-remove` spans
+sit *inside* the `prune-scan` window on the live path and overlap each other —
+removals execute concurrently on the worker pool, holding the scan lock's read
+side. A span covers any wait for the lock plus the removal itself; the
+exceptional candidates that take the write side (hook-bearing, `--foreground`,
+metadata-pruning — `removal_needs_write` in `src/commands/step/prune.rs`) also
+wait for every in-flight check and removal to drain first.
+
+```bash
+cargo run -p wt-perf -- setup generated 0 0 --prune-candidates 4 --prune-backdrop 8 --path target/wt-prune-generated
+# A freshly built fixture is already probe-cold (empty sha_cache).
+cargo run -p wt-perf -- timeline -- -C target/wt-prune-generated step prune --dry-run --min-age 0s
+cargo run -p wt-perf -- timeline -- -C target/wt-prune-generated step prune --min-age 0s
+```
+
+**Live prune at large-repository scale is a one-shot timeline, not a criterion group** —
+each live run consumes the candidates, and constructing the multi-gigabyte fixture
+costs minutes. Give setup a new explicit path; it refuses to overwrite an
+existing destination. The pinned source clone is reused, while the mutable
+fixture has no cache state to validate or repair. The probe-cold timeline keeps
+git metadata warm:
+
+```bash
+cargo run -p wt-perf -- setup imported --prune-candidates 12 --prune-backdrop 24 --path target/wt-prune-imported
+cargo run -p wt-perf -- timeline -- -C target/wt-prune-imported step prune --min-age 0s
+# For another run, remove target/wt-prune-imported explicitly or choose a new path.
+```
+
+**`wt remove` keeps working after its last message.** The in-process sweep
+(`run_internal_sweep`) runs before exit, while the shell wrapper waits on the
+process: one `pgrep` for `git fsmonitor--daemon` processes plus one `lsof` over
+the whole PID set. Two spawns whatever the machine-wide daemon count, so
+`remove_e2e` misses a fixed tail rather than one that grows with the machine.
+To observe it, run `wt-perf timeline -- remove <branch>` on a real machine and
+read the `internal-sweep` span; the `fsmonitor sweep: resolving sockets for N
+daemon(s) via one lsof` debug line gives the count.
+
+## Output Locations
+
+Ephemeral generated fixtures use the system temporary directory. Manual
+`wt-perf setup` fixtures live at the explicit `--path` and are never
+overwritten. The revision-keyed imported source and temporary
+imported runs live under `target/wt-perf/bench-repos/`; that directory is
+per-worktree and reaped by `cargo clean`.
+
+- Results: `target/criterion/`
+- Cached corpus source: `target/wt-perf/bench-repos/imported/source-<revision>/`
+- Temporary imported runs: `target/wt-perf/bench-repos/imported/runs/`
+- HTML reports: `target/criterion/*/report/index.html`
+
+## Performance Investigation with wt-perf
+
+Use `wt-perf` to set up benchmark repos and generate Chrome Trace Format for visualization.
+
+### Setting up benchmark repos
+
+```bash
+# Set up the default generated repo: 8 total worktrees and 50 branches.
+cargo run -p wt-perf -- setup generated --path target/wt-generated
+
+# `wt-perf setup --help` lists every recipe and its semantic count names.
+# Reproduce the completion fixture, including its remote-tracking-ref population:
+cargo run -p wt-perf -- setup generated 24 120 1400 --path target/wt-generated-completion
+
+# Build a fresh imported prune fixture from the cached pinned source:
+cargo run -p wt-perf -- setup imported --prune-candidates 12 --prune-backdrop 24 --path target/wt-prune-imported
+```
+
+### Generating traces
+
+`wt-perf timeline` runs a `wt` invocation with `-vv` (which writes the
+machine `trace.jsonl`), reads that back, and renders. Default mode is a
+sorted text timeline; `--chrome` emits Chrome Trace Format JSON for
+Perfetto/chrome://tracing. `--cold` invalidates caches first.
+
+```bash
+# Text timeline of one wt invocation
+cargo run -p wt-perf -- timeline -- list --progressive
+
+# Cold-cache run (invalidates the traced repo — the `-C` arg, else cwd)
+cargo run -p wt-perf -- timeline --cold -- -C target/wt-generated list --progressive
+
+# Chrome Trace Format JSON for Perfetto
+cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
+# Open in https://ui.perfetto.dev or chrome://tracing
+```
+
+`--progressive` is still required: `wt-perf timeline` runs wt with stdout
+piped to /dev/null, so TTY-gated events (`Skeleton rendered`, `First
+result received`) won't fire without it.
+
+For Chrome JSON from a `trace.jsonl` already captured to disk (e.g. a CI
+artifact), feed it to `wt-perf trace` instead:
+
+```bash
+wt -vv list --progressive --branches
+cargo run -p wt-perf -- trace .git/wt/logs/trace.jsonl > trace.json
+```
+
+The text-timeline summary reports `traced` (first → last record, what the
+spans actually cover) and `wall` (externally-measured
+spawn → wait, the true process duration). The gap between them is
+prelude/epilogue not visible to the trace — process spawn, dyld, code
+that runs before `init_logging` registers the trace epoch, and the exit
+path after the last span drops.
+
+### Analyzing a trace
+
+`wt config state logs profile [FILE]` answers the three questions below from a
+captured `trace.jsonl` without leaving the terminal: subprocess time by command
+type and by worktree (BY COMMAND TYPE / BY CONTEXT), the slowest individual
+jobs, the parallelism factor and peak concurrency, same-context duplicate
+commands (CACHE), and the collect milestones (KEY INTERVALS / PHASES).
+`--format=json` emits the same data for scripting.
+
+```bash
+wt -vv list --progressive
+wt config state logs profile # human report
+wt config state logs profile --format=json | jq .cache
+```
+
+For visual critical-path inspection — the one thing the aggregate report can't
+show — open the Chrome Trace JSON (`wt-perf timeline --chrome`, or `wt-perf
+trace` on an existing `trace.jsonl`) in <https://ui.perfetto.dev> or
+chrome://tracing.
+
+**A traced run skips prewarm's rev-parse batch, so its startup ordering is
+not quite the run users get.** At `-vv`, `logging::init` opens the log sinks
+through `log_files::try_create`, which calls `Repository::current()` and so
+resolves the git common dir in a fork the trace never sees (the subscriber
+isn't installed yet). `Repository::prewarm` gates each of its threads on the
+cache it populates: the git-config and user-config preloads still run — their
+spans appear in the trace — but the rev-parse batch is skipped because its
+product is already cached, so the per-worktree discovery (`WORKTREE_ROOTS`,
+`GIT_DIRS`, `CURRENT_BRANCHES`) happens on demand via `prewarm_info` instead
+of overlapped at startup.
+
+Three consequences when reading one:
+
+- The run's first fork (the common-dir rev-parse) is invisible — it lands in
+ the untraced gap before the first span.
+- Don't conclude the per-worktree discovery is on-demand in production because
+ the trace shows a `prewarm_info` refork mid-command; in production the
+ rev-parse batch covers it at startup.
+- Don't measure a startup change by trace alone. Time the real binary
+ (`hyperfine` on the shipped path) and, for a fork inventory that doesn't perturb
+ the run, put a logging shim named `git` at the front of `PATH` — a two-line
+ `sh` script that appends `"$*"` to a file and `exec`s the real git. That counts
+ every spawn with no verbosity flag set.
+
+### Performance questions
+
+Three questions drive `wt list` performance work:
+
+1. **Where does time go?** Which subprocess types consume the most total time? The category with the highest total is where optimization effort has the most impact — `by_type` and `slowest` in the profile.
+
+2. **How parallel are we?** Total subprocess time divided by wall time gives a parallelism factor. A factor of 4.0 means 4 commands running concurrently on average. Close to 1.0 means mostly serial execution with headroom to parallelize — `parallelism` and `peak_concurrency` in the profile.
+
+3. **What's on the critical path?** The critical path passes through serial phases (setup, finalization) plus the slowest work item in the parallel phase. The profile's `phases` (milestone gaps) and `by_context` (per-worktree totals — the worktree with the highest total is the likely parallel bottleneck) bound it, but the trace format doesn't capture task dependencies, so visualizing the trace in Perfetto is more useful here.
+
+### Generating traces from benchmark repos
+
+```bash
+# Trace the canonical imported fixture
+cargo run -p wt-perf -- setup imported --path target/wt-imported
+cargo run --release -q -- -vv -C target/wt-imported list --progressive --branches
+cargo run -p wt-perf -- trace target/wt-imported/.git/wt/logs/trace.jsonl > imported-trace.json
+```
+
+## Key Performance Insights
+
+**`git for-each-ref %(ahead-behind:BASE)` is O(commits), not O(refs)**
+
+This command walks the commit graph to compute divergence. Its cost on the
+imported corpus is driven primarily by history depth, not the number of
+rendered rows.
+
+**Branch-row costs** (rust-lang/rust with 50 branch-only rows):
+- Cold rows pay merge-base/merge-tree work per branch.
+- Warm rows reuse merge-tree, integration-probe, diff-stat, and ancestry entries.
+- Default rows still capture refs but skip branch-only integration and rendering tasks.
+
+The persistent SHA-keyed cache (`.git/wt/cache/`) amortizes the first-run cost across
+subsequent invocations. Cache entries are eternally valid since they're keyed on commit
+SHAs.
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index cf25466f6..43c994c2d 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -1,437 +1 @@
-# Benchmark Guidelines
-
-See `list.rs` and `time_to_first_output.rs` headers for benchmark groups and run examples.
-
-## Quick Start
-
-Criterion's CLI takes a positional `FILTER` (substring inclusion) and `--exact`. There's no `--skip`; pick a filter that *includes* what you want instead.
-
-```bash
-# Fast iteration (one generated group, warm cache only)
-cargo bench --bench list skeleton/warm
-
-# Run specific group (all variants)
-cargo bench --bench list full
-
-# GH #461 scenario (50 branches at varying depths in the imported corpus)
-cargo bench --bench list large_repository
-
-# All list benchmarks (~1 hour)
-cargo bench --bench list
-
-# Time-to-first-output benchmarks
-cargo bench --bench time_to_first_output # all commands
-cargo bench --bench time_to_first_output remove # just remove
-
-# wt step prune (scan + removal on the squash-merged fixture)
-cargo bench --bench prune # generated variants
-cargo bench --bench prune --features large-repository-benches prune_large_repository # multi-gigabyte temporary fixture
-
-# Picker preview pre-compute (wt switch preview workload)
-cargo bench --bench picker_preview # all variants
-cargo bench --bench picker_preview warm # warm only
-
-# Shell completion (COMPLETE=$SHELL wt -- wt switch <Tab>) — one variant, no filter
-cargo bench --bench completion
-```
-
-## Fixtures and Benches
-
-Bench groups name measurements; fixture recipes name corpus provenance. Both
-bases produce ordinary Git repositories: `Generated` builds the corpus locally,
-while `Imported` copies a pinned upstream corpus. Preserve the state dimensions
-needed for coverage and fidelity, not historical recipes or the ability to
-recreate an old setup. A property does not get its own fixture identity merely
-because one benchmark studies it.
-Worktree, branch, and remote-ref counts are controlled population parameters;
-prune candidates are an overlay. Add another base only when the corpus itself
-cannot serve one of these roles.
-
-| Canonical base | `wt-perf setup` | Bench group(s) |
-|---|---|---|
-| `Generated { linked_worktrees: W, branchless_branches: B, remote_tracking_refs: R }` | `setup generated W B R --path <path>` | all generated benchmarks |
-| `Imported` | `setup imported --path <path>` | `large_repository` and `prune_large_repository` |
-
-`linked_worktrees` excludes the primary worktree. `branchless_branches` have
-no linked worktree. `remote_tracking_refs` excludes the `origin/main` and
-`origin/HEAD` pair every generated fixture has. The generated defaults are 7,
-50, and 0 respectively, giving ordinary benchmarks eight total worktrees plus
-branches spread across its history. The imported base always has the same
-eight total worktrees and fifty history-spread branches.
-
-Add prune state with `--prune-candidates M --prune-backdrop U`. Each count is
-a pair: one linked worktree and one branchless branch. The benchmark catalog
-applies it to generated and imported fixtures. This is an overlay on the
-canonical base, not a separate fixture recipe.
-
-Every benchmark recipe returns `FixtureRepo`, the owner of the temporary root
-plus the canonical primary/linked-worktree paths. Repo-bound benchmark
-subprocesses start through `wt_command`, and warm/cold matrices use
-`CacheState::WARM_AND_COLD`; keep lifecycle, environment isolation, and cache
-labels in those shared APIs.
-
-## Imported corpus
-
-`benches/imported-fixture` pins the corpus and commit.
-The first matching acquisition clones that revision; later runs reuse the
-revision-keyed source under `target/wt-perf/bench-repos/imported/`.
-Source construction is locked across processes, built in a temporary sibling,
-validated, then atomically renamed into place. Mutable benchmark fixtures are
-always fresh and have no shared lock or repair state.
-
-## Faster Iteration
-
-Criterion has no exclusion flag — narrow the run by picking a substring that matches only the variants you want. Benchmark IDs look like `<group>/<label>/<param>`, e.g. `skeleton/cold/1`, `worktree_scaling/warm/8`, `full/cold`, `large_repository/branches/warm`.
-
-**Pattern matching (positional `FILTER`):**
-```bash
-cargo bench --bench list scaling # All worktree_scaling/* variants
-cargo bench --bench list warm # Every benchmark whose ID contains "warm"
-cargo bench --bench list skeleton/warm # Just skeleton's warm variants
-cargo bench --bench list full # Both cache states of the combined fixture
-cargo bench --bench list -- --exact full/cold # One exact ID
-```
-
-To skip the slow large-repository and divergent groups, target `skeleton`, `worktree_scaling`, or `full`. Run them sequentially if you want more than one.
-
-The `full` group is the place to start when `wt list` regresses on a real mix of worktrees and branches: the cold/warm split says whether the cost is the persistent-cache fill (cold) or the per-process re-fork (warm). A `full` wall time can't be split by side (the git subprocesses overlap on the rayon pool), so to localize a regression, trace one invocation and read the profile's BY CONTEXT table ("Analyzing a trace" below); `worktree_scaling` and `divergent_branches` track the worktree side and branch side respectively at criterion cadence.
-
-## WORKTRUNK_FIRST_OUTPUT
-
-Setting `WORKTRUNK_FIRST_OUTPUT=1` causes commands to exit at the point where first
-user-visible output would appear. Used by `time_to_first_output` benchmarks to measure
-startup latency without output rendering or post-output work (mismatch warnings, hooks).
-
-Supported commands: `switch`, `remove`, `list`.
-
-`wt step prune` deliberately has no `WORKTRUNK_FIRST_OUTPUT` hook: its first
-output is data-dependent (the dry-run path collects and sorts every check
-result before printing anything, so e2e ≈ time-to-first-output already; the
-live path streams whichever check lands first). Use `benches/prune.rs` for
-cadence-tracked numbers and the `prune-*` spans (below) for phase attribution.
-
-## WORKTRUNK_PREVIEW_BENCH
-
-Setting `WORKTRUNK_PREVIEW_BENCH=1` runs `wt switch`'s interactive picker prelude
-end-to-end — collect, speculative spawn, skeleton, initial pre-compute, deferred
-pre-compute — and exits immediately after `PreviewOrchestrator::wait_for_idle()`,
-before skim launches and before any JSON serialization or stderr drain. Used by
-`picker_preview` benchmarks to measure the skeleton-time preview pool workload
-without standing up a PTY. Off-screen worktrees are demand-loaded only after skim
-starts and are intentionally outside this benchmark. Bypasses the picker's TTY
-check, like `WORKTRUNK_PICKER_DRY_RUN=1`.
-
-The hot path inside the env-gated block is identical to the dry-run path; only the
-post-drain output (cache JSON dump + stashed-warning drain) is conditional. Keep new
-post-drain work out of the bench path unless it's part of the workload being
-measured.
-
-## Cache Handling
-
-Worktrunk maintains a persistent SHA-keyed cache at `.git/wt/cache/` plus a git-config
-cache of the default branch at `worktrunk.default-branch`. Both survive process exits,
-so bench iterations read from prior iterations unless invalidated.
-
-**Rule:** explicitly choose cache state for every benchmark that runs a `wt`
-subcommand which populates these caches. Run ordinary warm/cold variants through
-`wt_perf::bench_wt`, the one home of the shared strategy. Destructive variants
-use `iter_custom`: each iteration builds a fresh fixture before starting the
-timer, measures only the command, and checks the postcondition before returning
-the accumulated duration. `remove_e2e` uses warm/cold no-hooks neighbors for
-cache cost and a warm with-hooks neighbor for hook cost;
-`prune_e2e/live` clears probe caches to preserve its probe-cold scenario.
-
-`invalidate_caches_auto` clears:
-
-- `.git/objects/info/commit-graph*`
-- `.git/wt/cache/` (all sha_cache kinds + ci-status + summaries)
-- `worktrunk.default-branch` (git config)
-
-`.git/packed-refs` is deliberately preserved: fixture setup runs `git gc`
-at the end, which packs every loose ref into `packed-refs`
-and prunes the loose copies. Deleting that file post-gc leaves the repo with
-no resolvable refs, so any bench that resolves a branch (e.g. the `with_vars`
-alias's `{{ commit }}` template var) blows up partway through warm-up.
-
-User state — `worktrunk.history`, `worktrunk.hints.*`, `worktrunk.state.<branch>.*`,
-`.git/wt/logs/`, `.git/wt/trash/` — is intentionally preserved. It doesn't affect
-read-path performance and benches may depend on it (e.g., branch markers set during
-setup).
-
-Worktree indexes survive every cache state. Git treats a missing index as every
-tracked file being staged for deletion, which changes the repository rather
-than cooling it. `invalidate_probe_caches` clears only `.git/wt/cache/`; the
-prune benches use it for the first-scan-after-fetch shape while git metadata
-stays warm.
-
-**Which commands populate `.git/wt/cache/`:**
-
-| Command | Populates? | Notes |
-|---------|------------|-------|
-| `wt list` | Yes | Post-skeleton tasks. Exits early under `WORKTRUNK_SKELETON_ONLY=1` / `WORKTRUNK_FIRST_OUTPUT=1` — those skip the writing phase. |
-| `wt remove` | Yes | `prepare_worktree_removal` → `compute_integration_lazy` writes `is-ancestor` / `has-added-changes` / `merge-add-probe` whenever `BranchDeletionMode` is not `ForceDelete` (CLI `--force` is `force_worktree`, not `--force-delete`). |
-| `wt step prune` | Yes | Every scanned worktree/branch runs `integration_reason` → the same probe writes as `wt remove`. First scan after new commits is cold; re-runs are warm (`prune_e2e/dry_run_probe_cold` vs `dry_run_warm`). |
-| `wt switch <branch>` | No | No sha_cache writers on the direct-switch path. |
-| `wt switch` (picker) | Yes | Preview pre-compute writes `picker-preview/{log,branch-diff,upstream-diff}-…` entries. Exercised under `WORKTRUNK_PREVIEW_BENCH=1` / `WORKTRUNK_PICKER_DRY_RUN=1`. |
-| `wt` (completion via `COMPLETE=$SHELL`) | No | Only `for-each-ref` + worktree list. |
-
-Clearing the default-branch cache as part of full invalidation is simpler than
-introducing a separate "warm default branch" mode.
-`invalidate_probe_caches` leaves it warm, like everything else outside
-`.git/wt/cache/`.
-
-**Bench fixtures don't exercise the wire path.** `setup_fake_remote` writes
-`refs/remotes/origin/HEAD` directly into every repo, so a cold-cache iteration
-falls through to the local `<r>/HEAD` lookup, never to `git ls-remote`. The
-cold cost we benchmark is the *configured-remote* cold cost, not the
-*fresh-clone* cold cost. A
-`cold_no_remote` mode (extending `invalidate_caches_auto` to also wipe
-`refs/remotes/origin/HEAD`) would close the gap if the wire-path cost is
-worth measuring at CI cadence.
-
-## Expected relationships
-
-- The 1- and 8-worktree rows track the endpoint cost of adding linked
- worktrees under both cache modes.
-- Cold rows should be slower than their warm neighbors because they rebuild
- the persistent caches named above.
-- Large-repository rows amplify history-walk and working-tree costs that generated
- content cannot model faithfully.
-
-## Recording `wt remove` / `wt step prune` staging
-
-The removal commands interleave per-target work with parallel scans and
-detached background processes; a single e2e number hides which phase moved.
-Record them in two layers:
-
-**Criterion cadence** — `benches/remove.rs` and `benches/prune.rs`. The
-generated prune overlay adds 4 squash-merged worktrees and 4 squash-merged
-branches as candidates, plus 8 two-sided-diverged worktrees and 8 branches as
-backdrop. `prune_large_repository` layers 12 candidate pairs and 24 backdrop pairs
-onto the canonical imported base. Its source clone is cached, but the mutable
-multi-gigabyte fixture is built fresh for the benchmark process and removed
-when it exits. That group is opt-in via `--features large-repository-benches` and
-must never build on a hosted CI runner.
-
-| Variant | What it measures |
-|---------|------------------|
-| `prune_e2e/dry_run_probe_cold` | full parallel scan with `.git/wt/cache/` cleared; git's own caches stay warm, matching the first prune after fetching the default branch |
-| `prune_e2e/dry_run_warm` | steady-state re-scan with integration probes served from sha_cache |
-| `prune_e2e/dry_run_cold` | first scan with worktrunk caches, the default-branch cache, and git's commit graph cleared |
-| `prune_e2e/live` | probe-cold scan plus parallel removal of the 8 candidates |
-| `prune_large_repository/dry_run_warm` | steady-state scan at large-repository history and working-tree scale |
-| `prune_large_repository/dry_run_probe_cold` | the same scan with integration probes rerun; statuses stay stat-warm |
-| `remove_e2e/{warm,cold}/no_hooks` | full removal with and without persistent caches |
-| `remove_e2e/warm/with_hooks` | warm-cache neighbor isolating hook approval and spawning |
-| `first_output/remove` | single-target validation up to first output (`benches/time_to_first_output.rs`) |
-
-Full-cold and live at large-repository scale are **one-shot timelines, not
-criterion groups**. Full-cold adds commit-graph rebuilding; live consumes the
-candidates. Live removals run concurrently inside the `prune-scan` window,
-while packed candidate refs may serialize briefly on `packed-refs.lock`.
-
-An actual first checkout can be slower because every worktree status is
-stat-cold. The cache helpers preserve indexes because removing one changes
-staged state; use a fresh fixture when investigating checkout-cold status.
-The generated fixture can't show it — its statuses are milliseconds — so
-scale-sensitive changes need a one-shot on a fresh imported fixture (or
-`wt-perf timeline -- -C <repo> step prune --dry-run` on a real
-repository) alongside the criterion cadence. All large-repository numbers are
-I/O-bound and move with ambient machine load (sibling builds, Spotlight):
-treat them as shape, not thresholds, and compare Criterion verdicts with
-`uptime`.
-
-The probe-cold prune benches run through `bench_wt` with
-`CacheState::ProbeCold`. Fixture correctness is checked outside the timed
-loops: a post-setup dry-run pins the candidate count, and every live sample
-must consume its fresh fixture's candidate refs while retaining the backdrop.
-
-**Phase attribution** — `wt-perf timeline` plus the removal spans. Prune emits
-`prune-gather` (worktree+branch enumeration), `prune-scan` (the whole parallel
-check region), one `prune-check:<ref>` per scanned item, and one
-`prune-remove:<label>` per removed candidate; `wt remove` emits
-`internal-sweep` around its end-of-command janitor. The `prune-remove` spans
-sit *inside* the `prune-scan` window on the live path and overlap each other —
-removals execute concurrently on the worker pool, holding the scan lock's read
-side. A span covers any wait for the lock plus the removal itself; the
-exceptional candidates that take the write side (hook-bearing, `--foreground`,
-metadata-pruning — `removal_needs_write` in `src/commands/step/prune.rs`) also
-wait for every in-flight check and removal to drain first.
-
-```bash
-cargo run -p wt-perf -- setup generated 0 0 --prune-candidates 4 --prune-backdrop 8 --path target/wt-prune-generated
-# A freshly built fixture is already probe-cold (empty sha_cache).
-cargo run -p wt-perf -- timeline -- -C target/wt-prune-generated step prune --dry-run --min-age 0s
-cargo run -p wt-perf -- timeline -- -C target/wt-prune-generated step prune --min-age 0s
-```
-
-**Live prune at large-repository scale is a one-shot timeline, not a criterion group** —
-each live run consumes the candidates, and constructing the multi-gigabyte fixture
-costs minutes. Give setup a new explicit path; it refuses to overwrite an
-existing destination. The pinned source clone is reused, while the mutable
-fixture has no cache state to validate or repair. The probe-cold timeline keeps
-git metadata warm:
-
-```bash
-cargo run -p wt-perf -- setup imported --prune-candidates 12 --prune-backdrop 24 --path target/wt-prune-imported
-cargo run -p wt-perf -- timeline -- -C target/wt-prune-imported step prune --min-age 0s
-# For another run, remove target/wt-prune-imported explicitly or choose a new path.
-```
-
-**`wt remove` keeps working after its last message.** The in-process sweep
-(`run_internal_sweep`) runs before exit, while the shell wrapper waits on the
-process: one `pgrep` for `git fsmonitor--daemon` processes plus one `lsof` over
-the whole PID set. Two spawns whatever the machine-wide daemon count, so
-`remove_e2e` misses a fixed tail rather than one that grows with the machine.
-To observe it, run `wt-perf timeline -- remove <branch>` on a real machine and
-read the `internal-sweep` span; the `fsmonitor sweep: resolving sockets for N
-daemon(s) via one lsof` debug line gives the count.
-
-## Output Locations
-
-Ephemeral generated fixtures use the system temporary directory. Manual
-`wt-perf setup` fixtures live at the explicit `--path` and are never
-overwritten. The revision-keyed imported source and temporary
-imported runs live under `target/wt-perf/bench-repos/`; that directory is
-per-worktree and reaped by `cargo clean`.
-
-- Results: `target/criterion/`
-- Cached corpus source: `target/wt-perf/bench-repos/imported/source-<revision>/`
-- Temporary imported runs: `target/wt-perf/bench-repos/imported/runs/`
-- HTML reports: `target/criterion/*/report/index.html`
-
-## Performance Investigation with wt-perf
-
-Use `wt-perf` to set up benchmark repos and generate Chrome Trace Format for visualization.
-
-### Setting up benchmark repos
-
-```bash
-# Set up the default generated repo: 8 total worktrees and 50 branches.
-cargo run -p wt-perf -- setup generated --path target/wt-generated
-
-# `wt-perf setup --help` lists every recipe and its semantic count names.
-# Reproduce the completion fixture, including its remote-tracking-ref population:
-cargo run -p wt-perf -- setup generated 24 120 1400 --path target/wt-generated-completion
-
-# Build a fresh imported prune fixture from the cached pinned source:
-cargo run -p wt-perf -- setup imported --prune-candidates 12 --prune-backdrop 24 --path target/wt-prune-imported
-```
-
-### Generating traces
-
-`wt-perf timeline` runs a `wt` invocation with `-vv` (which writes the
-machine `trace.jsonl`), reads that back, and renders. Default mode is a
-sorted text timeline; `--chrome` emits Chrome Trace Format JSON for
-Perfetto/chrome://tracing. `--cold` invalidates caches first.
-
-```bash
-# Text timeline of one wt invocation
-cargo run -p wt-perf -- timeline -- list --progressive
-
-# Cold-cache run (invalidates the traced repo — the `-C` arg, else cwd)
-cargo run -p wt-perf -- timeline --cold -- -C target/wt-generated list --progressive
-
-# Chrome Trace Format JSON for Perfetto
-cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
-# Open in https://ui.perfetto.dev or chrome://tracing
-```
-
-`--progressive` is still required: `wt-perf timeline` runs wt with stdout
-piped to /dev/null, so TTY-gated events (`Skeleton rendered`, `First
-result received`) won't fire without it.
-
-For Chrome JSON from a `trace.jsonl` already captured to disk (e.g. a CI
-artifact), feed it to `wt-perf trace` instead:
-
-```bash
-wt -vv list --progressive --branches
-cargo run -p wt-perf -- trace .git/wt/logs/trace.jsonl > trace.json
-```
-
-The text-timeline summary reports `traced` (first → last record, what the
-spans actually cover) and `wall` (externally-measured
-spawn → wait, the true process duration). The gap between them is
-prelude/epilogue not visible to the trace — process spawn, dyld, code
-that runs before `init_logging` registers the trace epoch, and the exit
-path after the last span drops.
-
-### Analyzing a trace
-
-`wt config state logs profile [FILE]` answers the three questions below from a
-captured `trace.jsonl` without leaving the terminal: subprocess time by command
-type and by worktree (BY COMMAND TYPE / BY CONTEXT), the slowest individual
-jobs, the parallelism factor and peak concurrency, same-context duplicate
-commands (CACHE), and the collect milestones (KEY INTERVALS / PHASES).
-`--format=json` emits the same data for scripting.
-
-```bash
-wt -vv list --progressive
-wt config state logs profile # human report
-wt config state logs profile --format=json | jq .cache
-```
-
-For visual critical-path inspection — the one thing the aggregate report can't
-show — open the Chrome Trace JSON (`wt-perf timeline --chrome`, or `wt-perf
-trace` on an existing `trace.jsonl`) in <https://ui.perfetto.dev> or
-chrome://tracing.
-
-**A traced run skips prewarm's rev-parse batch, so its startup ordering is
-not quite the run users get.** At `-vv`, `logging::init` opens the log sinks
-through `log_files::try_create`, which calls `Repository::current()` and so
-resolves the git common dir in a fork the trace never sees (the subscriber
-isn't installed yet). `Repository::prewarm` gates each of its threads on the
-cache it populates: the git-config and user-config preloads still run — their
-spans appear in the trace — but the rev-parse batch is skipped because its
-product is already cached, so the per-worktree discovery (`WORKTREE_ROOTS`,
-`GIT_DIRS`, `CURRENT_BRANCHES`) happens on demand via `prewarm_info` instead
-of overlapped at startup.
-
-Three consequences when reading one:
-
-- The run's first fork (the common-dir rev-parse) is invisible — it lands in
- the untraced gap before the first span.
-- Don't conclude the per-worktree discovery is on-demand in production because
- the trace shows a `prewarm_info` refork mid-command; in production the
- rev-parse batch covers it at startup.
-- Don't measure a startup change by trace alone. Time the real binary
- (`hyperfine` on the shipped path) and, for a fork inventory that doesn't perturb
- the run, put a logging shim named `git` at the front of `PATH` — a two-line
- `sh` script that appends `"$*"` to a file and `exec`s the real git. That counts
- every spawn with no verbosity flag set.
-
-### Performance questions
-
-Three questions drive `wt list` performance work:
-
-1. **Where does time go?** Which subprocess types consume the most total time? The category with the highest total is where optimization effort has the most impact — `by_type` and `slowest` in the profile.
-
-2. **How parallel are we?** Total subprocess time divided by wall time gives a parallelism factor. A factor of 4.0 means 4 commands running concurrently on average. Close to 1.0 means mostly serial execution with headroom to parallelize — `parallelism` and `peak_concurrency` in the profile.
-
-3. **What's on the critical path?** The critical path passes through serial phases (setup, finalization) plus the slowest work item in the parallel phase. The profile's `phases` (milestone gaps) and `by_context` (per-worktree totals — the worktree with the highest total is the likely parallel bottleneck) bound it, but the trace format doesn't capture task dependencies, so visualizing the trace in Perfetto is more useful here.
-
-### Generating traces from benchmark repos
-
-```bash
-# Trace the canonical imported fixture
-cargo run -p wt-perf -- setup imported --path target/wt-imported
-cargo run --release -q -- -vv -C target/wt-imported list --progressive --branches
-cargo run -p wt-perf -- trace target/wt-imported/.git/wt/logs/trace.jsonl > imported-trace.json
-```
-
-## Key Performance Insights
-
-**`git for-each-ref %(ahead-behind:BASE)` is O(commits), not O(refs)**
-
-This command walks the commit graph to compute divergence. Its cost on the
-imported corpus is driven primarily by history depth, not the number of
-rendered rows.
-
-**Branch-row costs** (rust-lang/rust with 50 branch-only rows):
-- Cold rows pay merge-base/merge-tree work per branch.
-- Warm rows reuse merge-tree, integration-probe, diff-stat, and ancestry entries.
-- Default rows still capture refs but skip branch-only integration and rendering tasks.
-
-The persistent SHA-keyed cache (`.git/wt/cache/`) amortizes the first-run cost across
-subsequent invocations. Cache entries are eternally valid since they're keyed on commit
-SHAs.
diff --git a/benches/completion.rs b/benches/completion.rs
index 9149c59e0..a66004014 100644
--- a/benches/completion.rs
+++ b/benches/completion.rs
@@ -13,7 +13,7 @@
//! over a series of deliberately lopsided repos and still can't say which call
//! moved, because the calls within a wave overlap. Localizing a regression is a
//! trace's job here, exactly as it is for `full` — see "Analyzing a trace" in
-//! benches/CLAUDE.md, and note that a `-vv` run skips prewarm's rev-parse
+//! benches/AGENTS.md, and note that a `-vv` run skips prewarm's rev-parse
//! batch and so is not quite the run users get.
//!
//! The benchmark uses the same 24 linked worktrees and 120 branchless branches
diff --git a/benches/list.rs b/benches/list.rs
index d3de98c75..a8ac0c5b4 100644
--- a/benches/list.rs
+++ b/benches/list.rs
@@ -13,7 +13,7 @@
// Attribution: a `full` wall time can't be split by side (worktree- and
// branch-side git subprocesses overlap on the rayon pool), so to see where a
// regression lands, trace one invocation and read the profile's BY CONTEXT /
-// BY COMMAND TYPE tables — see `benches/CLAUDE.md` ("Analyzing a trace").
+// BY COMMAND TYPE tables — see `benches/AGENTS.md` ("Analyzing a trace").
// For per-side regression tracking at criterion cadence, `worktree_scaling`
// is the worktree side and `divergent_branches` the branch side.
//
@@ -190,7 +190,7 @@ fn bench_divergent_branches(c: &mut Criterion) {
/// history to traverse).
///
/// To see *where* a regression lands, trace one invocation and read the
-/// profile's BY CONTEXT / BY COMMAND TYPE tables — see `benches/CLAUDE.md`
+/// profile's BY CONTEXT / BY COMMAND TYPE tables — see `benches/AGENTS.md`
/// ("Analyzing a trace"); a criterion wall time can't be decomposed by side
/// because the worktree- and branch-side git subprocesses run concurrently on
/// the rayon pool. For
diff --git a/benches/picker_preview.rs b/benches/picker_preview.rs
index 353bc8351..a0554a709 100644
--- a/benches/picker_preview.rs
+++ b/benches/picker_preview.rs
@@ -24,7 +24,7 @@
// launches and before any JSON serialization / stderr drain. The PTY route
// (option 2 from the task: "spawn → first interactive-ready point") would
// require a TTY harness; the documented nextest/SIGTTOU pain on
-// `shell-integration-tests` (see project `CLAUDE.md`) makes that a follow-up
+// `shell-integration-tests` (see project `AGENTS.md`) makes that a follow-up
// rather than a prerequisite. The headless path captures the initial pool
// workload, which is the variable the optimization work in #2662 / #2683 /
// #2685 / #2704 actually pushes on.
diff --git a/docs/AGENTS.md b/docs/AGENTS.md
new file mode 100644
index 000000000..3081c2594
--- /dev/null
+++ b/docs/AGENTS.md
@@ -0,0 +1,308 @@
+# Documentation Site
+
+The Worktrunk site is built with Astro and Starlight and published at
+https://worktrunk.dev.
+
+## Development
+
+The project hook installs the site dependencies, fetches the demo assets, and
+starts the Astro dev server. Find this worktree's URL with `wt list`.
+
+To run it yourself:
+
+```bash
+npm --prefix docs install
+npm --prefix docs exec playwright install webkit
+npm --prefix docs run dev -- --host 127.0.0.1 --port 4321
+```
+
+The local production checks are:
+
+```bash
+npm --prefix docs run check
+npm --prefix docs test
+npm --prefix docs run build
+npm --prefix docs run test:site
+```
+
+`npm run build` writes `docs/dist/` and builds the Pagefind search index. Both
+`build` and `dev` pass `--force`, which clears Astro's content cache before
+rendering. Cached pages carry the URL of the Expressive Code stylesheet, whose
+hash comes from the code-rendering configuration and plugins, and Astro's cache
+key covers neither: a stale page links a stylesheet the server no longer serves,
+and every code block renders unstyled.
+
+The cache is cleared only when the server starts. When `astro.config.mjs`
+changes under a running dev server, through an edit or a merge, Astro restarts
+the server in place but keeps rendering content with the renderer it started
+with, and pages break the same way. Restart it with `wt hook post-start docs`;
+the new `astro dev --force` replaces the running server.
+
+### Verifying changes
+
+Text-only edits need the docs sync test and a production build. Visual changes
+also need browser verification with Playwright at desktop and mobile widths.
+Check the changed page, one command-reference page, search, the mobile menu,
+theme switching, anchor navigation, code copying, wide tables, and demo images.
+
+Always include the local dev-server link when handing off a docs change:
+
+```text
+View changes: http://127.0.0.1:<port>
+```
+
+## Site architecture
+
+| Path | Responsibility |
+|------|----------------|
+| `astro.config.mjs` | Starlight integration, navigation, metadata, and code rendering |
+| `src/content/docs/` | Canonical documentation Markdown |
+| `src/pages/index.astro` | Homepage route; renders the canonical `worktrunk.md` body |
+| `src/styles/custom.css` | Worktrunk's visual system and narrow Starlight adjustments |
+| `src/plugins/stable-heading-ids.mjs` | Stable public anchor IDs for Markdown headings |
+| `src/plugins/worktrunk-terminal.mjs` | Shell syntax, homepage comparison roles, prompts, copy behavior, Clap help roles, and ANSI-derived output styling |
+| `src/themes/worktrunk-code.mjs` | Light and dark syntax themes for source and command blocks |
+| `src/generated/terminal-styles.json` | Generated site-only span styles from ANSI command snapshots |
+| `src/components/Head.astro` | Social metadata, structured data, and analytics |
+| `tests/` | Renderer unit tests plus built-site and WebKit mobile checks |
+| `public/` | Files served unchanged at the site root |
+| `demos/` | VHS sources and scripts for the external demo assets |
+
+The site uses Starlight's own navigation, table of contents, responsive shell,
+search, code frames, copy controls, and theme selector. Keep overrides narrow.
+Before replacing a Starlight component, check whether configuration or CSS can
+express the change. Every full component override becomes an upstream merge
+surface.
+
+The visual direction is a warm technical field manual: ivory paper, dark ink,
+one orange accent, strong typography, and terminal output as the main visual
+material. Avoid generic product-site devices such as gradient headline text,
+glass cards, feature-card grids, decorative blobs, and animation without a
+clear navigational or explanatory purpose.
+
+## Content and route contract
+
+Public documentation routes are stable. Existing pages should keep their root
+paths, for example `src/content/docs/switch.md` is `/switch/`. The homepage
+renders `worktrunk.md`; `/worktrunk/` remains available for compatibility and
+has a canonical link to `/`.
+
+Use root-relative links in canonical Markdown:
+
+```markdown
+[hook templates](/hook/#template-variables)
+```
+
+The sync pipeline expands them to full `https://worktrunk.dev/...` URLs for
+README and agent-skill copies. Do not add framework-specific link syntax.
+`stable-heading-ids.mjs` defines the heading-anchor scheme, including the ids
+scoped under each subcommand section, and `test:site` verifies every built
+internal page link and fragment.
+
+Images and demos use root-relative paths into `public/`:
+
+```html
+<figure class="demo">
+<picture>
+ <source srcset="/assets/docs/dark/wt-switch.gif" media="(prefers-color-scheme: dark)">
+ <img src="/assets/docs/light/wt-switch.gif" alt="wt switch demo" width="1600" height="900">
+</picture>
+</figure>
+```
+
+## Documentation sync taxonomy
+
+`cargo test --test integration test_docs_are_in_sync` owns the complete sync
+pipeline. It updates generated files and then fails so the changes are visible.
+Run it again after reviewing those changes; the second run must pass.
+
+There are three source categories:
+
+1. **Command pages**: `src/cli/mod.rs` is primary for `config`, `hook`, `list`,
+ `merge`, `remove`, `step`, and `switch`. The sync test writes the generated
+ region in `docs/src/content/docs/{command}.md`, then generates the matching
+ `skills/worktrunk/reference/` page.
+2. **Non-command pages**: files such as `claude-code.md`, `extending.md`,
+ `faq.md`, `llm-commits.md`, `shell-integration.md`, `tips-patterns.md`, and
+ `worktrunk.md` are primary in `docs/src/content/docs/`. The sync test derives
+ the skill copy.
+3. **Skill-only pages**: `troubleshooting.md` is primary in
+ `skills/worktrunk/reference/` and has no site page. When adding one, add a
+ `linguist-generated=false` entry to `.gitattributes`.
+
+Never hand-edit a generated mirror.
+
+### Command-page generation
+
+Each command page keeps YAML frontmatter outside one generated region:
+
+```markdown
+---
+title: "wt list"
+description: "List worktrees and their status."
+sidebar:
+ order: 11
+---
+<!-- ⚠️ AUTO-GENERATED from `wt list --help-page` — edit src/cli/mod.rs to update -->
+
+[generated content]
+
+<!-- END AUTO-GENERATED -->
+```
+
+The bare close marker is paired with the open marker using a non-greedy match.
+`test_no_nested_auto_generated_markers` enforces the required invariant: an
+auto-generated region may not contain another auto-generated region.
+
+Each command has three pieces in `src/cli/mod.rs`:
+
+| Piece | Source | Purpose |
+|-------|--------|---------|
+| Definition | First `///` line | Short text for command lists |
+| Subdefinition | Second `///` line, when useful | Context below the terminal help header |
+| Full guide | `after_long_help` | Mental model, workflow, examples, and reference links |
+
+Terminal help displays the full guide after the options. The web page combines
+the definition and subdefinition as its lead, followed by the full guide. Do
+not repeat the lead at the start of `after_long_help`.
+
+Link text must still make sense when terminal help removes the URL. Prefer
+``[`wt merge`](/merge/)`` or a descriptive phrase over a bare destination
+heading.
+
+Config examples between `USER_CONFIG_START` / `USER_CONFIG_END` and
+`PROJECT_CONFIG_START` / `PROJECT_CONFIG_END` also generate commented TOML
+files. Put prose before a code block instead of adding standalone TOML comment
+lines that would become double-commented. End-of-line comments are fine.
+
+After changing help text, refresh both generated pages and help snapshots:
+
+```bash
+cargo test --test integration test_docs_are_in_sync
+cargo insta test --accept --test integration -- test_help
+```
+
+### Snapshot examples
+
+A command placeholder in `src/cli/mod.rs` expands from an integration snapshot:
+
+````markdown
+<!-- wt list -->
+```console
+$ wt list
+```
+````
+
+The mapping lives in `tests/integration_tests/readme_sync.rs`. The generated
+site page uses the real command plus ANSI-stripped output in one `console`
+fence. This keeps the Markdown readable on GitHub and lets the site renderer
+add prompts and command-only copy behavior without changing the source. The
+same sync pass writes `src/generated/terminal-styles.json` from the snapshot's
+ANSI spans, so the website preserves the CLI's exact semantic colors and text
+attributes while every portable Markdown surface remains plain text.
+
+To update an example:
+
+1. Change the test setup that owns the snapshot.
+2. Run the focused integration test.
+3. Accept the snapshot with `cargo insta accept`.
+4. Run `test_docs_are_in_sync` twice, reviewing the first run's edits.
+
+### Code-block convention
+
+Use ordinary fenced Markdown. There are no template shortcodes or encoded
+command parameters.
+
+- Use `bash` for commands a reader can copy as a complete recipe.
+- Use `console` when commands and captured output share a block. Prefix command
+ lines with `$ `; leave output unprefixed.
+- Use the actual data language (`toml`, `json`, `yaml`, and so on) for files and
+ structured output.
+- Name the file a sample belongs in, as a first-line comment holding its path
+ (`# .config/wt.toml`, `# ~/.config/worktrunk/config.toml`, `# mise.toml`).
+ Expressive Code lifts it into the block's file-name tab and drops it from the
+ rendered code, while the committed Markdown keeps it as a readable comment.
+ Where a path comment would be invalid or noisy in the committed sample — a
+ `json` file, or a fenced `markdown` fragment — put `title="<path>"` on the
+ fence instead.
+ Blocks that show values for one key rather than a whole file, and
+ counter-examples, stay untitled; the prose says what they are.
+
+Example:
+
+````markdown
+```console
+$ wt switch --create feature-auth
+✓ Created branch feature-auth from main
+```
+````
+
+Starlight and Expressive Code create the frame and copy button. The Worktrunk
+plugin highlights `console` commands as Bash, renders `$ ` as a prompt, and
+makes blocks copy their commands rather than their output. A block with one
+command copies it with its comment lines and blank recipe separators; a block
+with several gives each command its own copy button. Copied shell commands
+leave out trailing `#` comments, which zsh passes as arguments unless
+`interactivecomments` is set. Snapshot-backed output gets its exact ANSI roles
+from the generated style manifest, while hand-written output uses a
+conservative marker fallback. Generated Clap help fences carry the
+`wt-command-reference` marker, which the plugin expands into semantic command,
+option, value, and metadata roles. Committed Markdown must remain useful
+without the plugin.
+
+Config samples inside the `USER_CONFIG_START` / `PROJECT_CONFIG_START` regions
+of `src/cli/mod.rs` carry no file-name comment: the double-comment rule under
+"Command-page generation" above already rules out the standalone comment line
+the path would need, and those sections name their file once at the top.
+
+### Web-only post-processing
+
+`post_process_for_html()` in `src/help.rs` handles the few semantic differences
+between terminal and site output: experimental badges, CI color labels, demo
+figures, and a linked issue-report phrase. Do not route general Markdown
+through it and do not add pre-rendered ANSI HTML.
+
+### Subdocument expansion
+
+Use a subdocument placeholder to include a subcommand as a section of its
+parent page:
+
+```markdown
+<!-- subdoc: create -->
+```
+
+The generator raises the subcommand heading levels and appends its command
+reference. The comment is invisible in terminal help.
+
+## Template examples
+
+Every Worktrunk template expression shown in documentation needs a matching
+test in `tests/integration_tests/doc_templates.rs`. This is what catches parser
+and operator-precedence changes before they make an example misleading.
+
+## Demo assets
+
+Large GIFs and rendered social cards live in the separate
+`max-sixty/worktrunk-assets` repository. `task fetch-assets` copies published
+assets to `docs/public/assets/`, which is gitignored. The publish workflow does
+the same before building.
+
+To regenerate and publish demos:
+
+```bash
+./docs/demos/build docs
+./docs/demos/build social
+task publish-assets
+```
+
+See `docs/demos/AGENTS.md` for timing, terminal setup, validation, and recording
+guidance.
+
+Social-card SVG sources remain in `docs/public/`:
+
+- `social-card.svg` is the 1200 by 630 Open Graph source.
+- `github-social-card.svg` is the 1280 by 640 repository-preview source.
+
+Build their PNG outputs with `task build-social-cards`, then publish them with
+`task publish-assets`. `src/components/Head.astro` points social metadata at
+`/assets/social/social-card.png`.
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md
index da253e20f..43c994c2d 100644
--- a/docs/CLAUDE.md
+++ b/docs/CLAUDE.md
@@ -1,308 +1 @@
-# Documentation Site
-
-The Worktrunk site is built with Astro and Starlight and published at
-https://worktrunk.dev.
-
-## Development
-
-The project hook installs the site dependencies, fetches the demo assets, and
-starts the Astro dev server. Find this worktree's URL with `wt list`.
-
-To run it yourself:
-
-```bash
-npm --prefix docs install
-npm --prefix docs exec playwright install webkit
-npm --prefix docs run dev -- --host 127.0.0.1 --port 4321
-```
-
-The local production checks are:
-
-```bash
-npm --prefix docs run check
-npm --prefix docs test
-npm --prefix docs run build
-npm --prefix docs run test:site
-```
-
-`npm run build` writes `docs/dist/` and builds the Pagefind search index. Both
-`build` and `dev` pass `--force`, which clears Astro's content cache before
-rendering. Cached pages carry the URL of the Expressive Code stylesheet, whose
-hash comes from the code-rendering configuration and plugins, and Astro's cache
-key covers neither: a stale page links a stylesheet the server no longer serves,
-and every code block renders unstyled.
-
-The cache is cleared only when the server starts. When `astro.config.mjs`
-changes under a running dev server, through an edit or a merge, Astro restarts
-the server in place but keeps rendering content with the renderer it started
-with, and pages break the same way. Restart it with `wt hook post-start docs`;
-the new `astro dev --force` replaces the running server.
-
-### Verifying changes
-
-Text-only edits need the docs sync test and a production build. Visual changes
-also need browser verification with Playwright at desktop and mobile widths.
-Check the changed page, one command-reference page, search, the mobile menu,
-theme switching, anchor navigation, code copying, wide tables, and demo images.
-
-Always include the local dev-server link when handing off a docs change:
-
-```text
-View changes: http://127.0.0.1:<port>
-```
-
-## Site architecture
-
-| Path | Responsibility |
-|------|----------------|
-| `astro.config.mjs` | Starlight integration, navigation, metadata, and code rendering |
-| `src/content/docs/` | Canonical documentation Markdown |
-| `src/pages/index.astro` | Homepage route; renders the canonical `worktrunk.md` body |
-| `src/styles/custom.css` | Worktrunk's visual system and narrow Starlight adjustments |
-| `src/plugins/stable-heading-ids.mjs` | Stable public anchor IDs for Markdown headings |
-| `src/plugins/worktrunk-terminal.mjs` | Shell syntax, homepage comparison roles, prompts, copy behavior, Clap help roles, and ANSI-derived output styling |
-| `src/themes/worktrunk-code.mjs` | Light and dark syntax themes for source and command blocks |
-| `src/generated/terminal-styles.json` | Generated site-only span styles from ANSI command snapshots |
-| `src/components/Head.astro` | Social metadata, structured data, and analytics |
-| `tests/` | Renderer unit tests plus built-site and WebKit mobile checks |
-| `public/` | Files served unchanged at the site root |
-| `demos/` | VHS sources and scripts for the external demo assets |
-
-The site uses Starlight's own navigation, table of contents, responsive shell,
-search, code frames, copy controls, and theme selector. Keep overrides narrow.
-Before replacing a Starlight component, check whether configuration or CSS can
-express the change. Every full component override becomes an upstream merge
-surface.
-
-The visual direction is a warm technical field manual: ivory paper, dark ink,
-one orange accent, strong typography, and terminal output as the main visual
-material. Avoid generic product-site devices such as gradient headline text,
-glass cards, feature-card grids, decorative blobs, and animation without a
-clear navigational or explanatory purpose.
-
-## Content and route contract
-
-Public documentation routes are stable. Existing pages should keep their root
-paths, for example `src/content/docs/switch.md` is `/switch/`. The homepage
-renders `worktrunk.md`; `/worktrunk/` remains available for compatibility and
-has a canonical link to `/`.
-
-Use root-relative links in canonical Markdown:
-
-```markdown
-[hook templates](/hook/#template-variables)
-```
-
-The sync pipeline expands them to full `https://worktrunk.dev/...` URLs for
-README and agent-skill copies. Do not add framework-specific link syntax.
-`stable-heading-ids.mjs` defines the heading-anchor scheme, including the ids
-scoped under each subcommand section, and `test:site` verifies every built
-internal page link and fragment.
-
-Images and demos use root-relative paths into `public/`:
-
-```html
-<figure class="demo">
-<picture>
- <source srcset="/assets/docs/dark/wt-switch.gif" media="(prefers-color-scheme: dark)">
- <img src="/assets/docs/light/wt-switch.gif" alt="wt switch demo" width="1600" height="900">
-</picture>
-</figure>
-```
-
-## Documentation sync taxonomy
-
-`cargo test --test integration test_docs_are_in_sync` owns the complete sync
-pipeline. It updates generated files and then fails so the changes are visible.
-Run it again after reviewing those changes; the second run must pass.
-
-There are three source categories:
-
-1. **Command pages**: `src/cli/mod.rs` is primary for `config`, `hook`, `list`,
- `merge`, `remove`, `step`, and `switch`. The sync test writes the generated
- region in `docs/src/content/docs/{command}.md`, then generates the matching
- `skills/worktrunk/reference/` page.
-2. **Non-command pages**: files such as `claude-code.md`, `extending.md`,
- `faq.md`, `llm-commits.md`, `shell-integration.md`, `tips-patterns.md`, and
- `worktrunk.md` are primary in `docs/src/content/docs/`. The sync test derives
- the skill copy.
-3. **Skill-only pages**: `troubleshooting.md` is primary in
- `skills/worktrunk/reference/` and has no site page. When adding one, add a
- `linguist-generated=false` entry to `.gitattributes`.
-
-Never hand-edit a generated mirror.
-
-### Command-page generation
-
-Each command page keeps YAML frontmatter outside one generated region:
-
-```markdown
----
-title: "wt list"
-description: "List worktrees and their status."
-sidebar:
- order: 11
----
-<!-- ⚠️ AUTO-GENERATED from `wt list --help-page` — edit src/cli/mod.rs to update -->
-
-[generated content]
-
-<!-- END AUTO-GENERATED -->
-```
-
-The bare close marker is paired with the open marker using a non-greedy match.
-`test_no_nested_auto_generated_markers` enforces the required invariant: an
-auto-generated region may not contain another auto-generated region.
-
-Each command has three pieces in `src/cli/mod.rs`:
-
-| Piece | Source | Purpose |
-|-------|--------|---------|
-| Definition | First `///` line | Short text for command lists |
-| Subdefinition | Second `///` line, when useful | Context below the terminal help header |
-| Full guide | `after_long_help` | Mental model, workflow, examples, and reference links |
-
-Terminal help displays the full guide after the options. The web page combines
-the definition and subdefinition as its lead, followed by the full guide. Do
-not repeat the lead at the start of `after_long_help`.
-
-Link text must still make sense when terminal help removes the URL. Prefer
-``[`wt merge`](/merge/)`` or a descriptive phrase over a bare destination
-heading.
-
-Config examples between `USER_CONFIG_START` / `USER_CONFIG_END` and
-`PROJECT_CONFIG_START` / `PROJECT_CONFIG_END` also generate commented TOML
-files. Put prose before a code block instead of adding standalone TOML comment
-lines that would become double-commented. End-of-line comments are fine.
-
-After changing help text, refresh both generated pages and help snapshots:
-
-```bash
-cargo test --test integration test_docs_are_in_sync
-cargo insta test --accept --test integration -- test_help
-```
-
-### Snapshot examples
-
-A command placeholder in `src/cli/mod.rs` expands from an integration snapshot:
-
-````markdown
-<!-- wt list -->
-```console
-$ wt list
-```
-````
-
-The mapping lives in `tests/integration_tests/readme_sync.rs`. The generated
-site page uses the real command plus ANSI-stripped output in one `console`
-fence. This keeps the Markdown readable on GitHub and lets the site renderer
-add prompts and command-only copy behavior without changing the source. The
-same sync pass writes `src/generated/terminal-styles.json` from the snapshot's
-ANSI spans, so the website preserves the CLI's exact semantic colors and text
-attributes while every portable Markdown surface remains plain text.
-
-To update an example:
-
-1. Change the test setup that owns the snapshot.
-2. Run the focused integration test.
-3. Accept the snapshot with `cargo insta accept`.
-4. Run `test_docs_are_in_sync` twice, reviewing the first run's edits.
-
-### Code-block convention
-
-Use ordinary fenced Markdown. There are no template shortcodes or encoded
-command parameters.
-
-- Use `bash` for commands a reader can copy as a complete recipe.
-- Use `console` when commands and captured output share a block. Prefix command
- lines with `$ `; leave output unprefixed.
-- Use the actual data language (`toml`, `json`, `yaml`, and so on) for files and
- structured output.
-- Name the file a sample belongs in, as a first-line comment holding its path
- (`# .config/wt.toml`, `# ~/.config/worktrunk/config.toml`, `# mise.toml`).
- Expressive Code lifts it into the block's file-name tab and drops it from the
- rendered code, while the committed Markdown keeps it as a readable comment.
- Where a path comment would be invalid or noisy in the committed sample — a
- `json` file, or a fenced `markdown` fragment — put `title="<path>"` on the
- fence instead.
- Blocks that show values for one key rather than a whole file, and
- counter-examples, stay untitled; the prose says what they are.
-
-Example:
-
-````markdown
-```console
-$ wt switch --create feature-auth
-✓ Created branch feature-auth from main
-```
-````
-
-Starlight and Expressive Code create the frame and copy button. The Worktrunk
-plugin highlights `console` commands as Bash, renders `$ ` as a prompt, and
-makes blocks copy their commands rather than their output. A block with one
-command copies it with its comment lines and blank recipe separators; a block
-with several gives each command its own copy button. Copied shell commands
-leave out trailing `#` comments, which zsh passes as arguments unless
-`interactivecomments` is set. Snapshot-backed output gets its exact ANSI roles
-from the generated style manifest, while hand-written output uses a
-conservative marker fallback. Generated Clap help fences carry the
-`wt-command-reference` marker, which the plugin expands into semantic command,
-option, value, and metadata roles. Committed Markdown must remain useful
-without the plugin.
-
-Config samples inside the `USER_CONFIG_START` / `PROJECT_CONFIG_START` regions
-of `src/cli/mod.rs` carry no file-name comment: the double-comment rule under
-"Command-page generation" above already rules out the standalone comment line
-the path would need, and those sections name their file once at the top.
-
-### Web-only post-processing
-
-`post_process_for_html()` in `src/help.rs` handles the few semantic differences
-between terminal and site output: experimental badges, CI color labels, demo
-figures, and a linked issue-report phrase. Do not route general Markdown
-through it and do not add pre-rendered ANSI HTML.
-
-### Subdocument expansion
-
-Use a subdocument placeholder to include a subcommand as a section of its
-parent page:
-
-```markdown
-<!-- subdoc: create -->
-```
-
-The generator raises the subcommand heading levels and appends its command
-reference. The comment is invisible in terminal help.
-
-## Template examples
-
-Every Worktrunk template expression shown in documentation needs a matching
-test in `tests/integration_tests/doc_templates.rs`. This is what catches parser
-and operator-precedence changes before they make an example misleading.
-
-## Demo assets
-
-Large GIFs and rendered social cards live in the separate
-`max-sixty/worktrunk-assets` repository. `task fetch-assets` copies published
-assets to `docs/public/assets/`, which is gitignored. The publish workflow does
-the same before building.
-
-To regenerate and publish demos:
-
-```bash
-./docs/demos/build docs
-./docs/demos/build social
-task publish-assets
-```
-
-See `docs/demos/CLAUDE.md` for timing, terminal setup, validation, and recording
-guidance.
-
-Social-card SVG sources remain in `docs/public/`:
-
-- `social-card.svg` is the 1200 by 630 Open Graph source.
-- `github-social-card.svg` is the 1280 by 640 repository-preview source.
-
-Build their PNG outputs with `task build-social-cards`, then publish them with
-`task publish-assets`. `src/components/Head.astro` points social metadata at
-`/assets/social/social-card.png`.
diff --git a/docs/demos/AGENTS.md b/docs/demos/AGENTS.md
new file mode 100644
index 000000000..0af2c6fec
--- /dev/null
+++ b/docs/demos/AGENTS.md
@@ -0,0 +1,411 @@
+# Demo Development
+
+## Directory structure
+
+```
+docs/demos/
+ build # Unified build script
+ tapes/ # All VHS tape files (templated)
+ shared/ # Python library, themes, fixtures
+ tests/ # Tests for the build script and tape conventions
+ .deps/vhs/ # VHS fork clone and binary (gitignored, built on demand)
+
+docs/public/assets/ # Output GIFs (gitignored, shared with fetch-assets)
+ docs/ # Doc site demos (1600x900; wt-core-mobile is 576x432)
+ light/ # Light theme variants
+ dark/ # Dark theme variants
+ social/ # Social media demos (1200x700)
+ light/ # Light theme only
+```
+
+Tape files use template variables (`{{FONTSIZE}}`, `{{WIDTH}}`, `{{HEIGHT}}`) so the same tape produces different sizes for docs vs social.
+
+## Regenerating demos
+
+```bash
+./docs/demos/build docs # Doc site demos (1600x900, light + dark)
+./docs/demos/build social # Social media demos (1200x700, light only)
+./docs/demos/build docs --text # Text output instead of GIFs
+```
+
+Text output captures terminal frames as plain text. Works for all demos, though interactive demos (TUI navigation, Zellij tabs) produce less useful output since the visual interactions don't translate to text.
+
+Regenerate a single demo:
+
+```bash
+./docs/demos/build social --only wt-switch
+./docs/demos/build docs --only wt-merge
+./docs/demos/build docs --only wt-core-mobile
+```
+
+**Available demos:**
+
+| Target | Demos |
+|--------|-------|
+| docs | wt-core, wt-core-mobile, wt-switch, wt-list, wt-commit, wt-statusline, wt-merge, wt-switch-picker, wt-zellij-omnibus |
+| social | wt-switch, wt-statusline, wt-list, wt-list-remove, wt-hooks, wt-devserver, wt-commit, wt-merge, wt-switch-picker, wt-core, wt-zellij-omnibus |
+
+## Snapshot testing
+
+```bash
+./docs/demos/build docs --snapshot # Generate all snapshots
+./docs/demos/build docs --snapshot --only wt-list # Single demo
+```
+
+Snapshots capture command output (not terminal rendering) and are committed to `docs/demos/snapshots/`. Use them to catch regressions like new hints creeping in.
+
+**How to use:**
+1. After changing wt output, regenerate snapshots: `./docs/demos/build docs --snapshot`
+2. Review the diff - small changes (commit hashes, minor formatting) are expected
+3. Commit the updated snapshots alongside your changes
+
+**What changes are expected:**
+- Commit hashes change each run (demo repo is recreated)
+- Column widths may shift slightly
+
+**What changes indicate regressions:**
+- New hints or warnings appearing
+- Output format changes you didn't intend
+- New lines or missing output
+
+**TUI demo validation:**
+
+TUI demos (Zellij, Claude UI) can't use text snapshots because VHS only captures the outer terminal, not content inside terminal multiplexers. Instead, they use OCR-based validation:
+
+1. After recording, specific frames are extracted from the GIF using ffmpeg
+2. Tesseract OCR extracts text from those frames
+3. The text is validated for expected/forbidden patterns
+4. Validation runs automatically when building TUI demos with defined checkpoints
+
+Checkpoints are defined in `docs/demos/shared/validation.py`. To add validation to a TUI demo:
+1. Identify key frame numbers by examining the GIF (25fps, so frame 75 = 3 seconds; a negative frame counts back from the last, for the state a recording ends in)
+2. Define checkpoint patterns in `validation.py` with frame numbers, expected patterns, and forbidden patterns
+
+`wt-switch`, `wt-switch-picker`, `wt-statusline`, and `wt-zellij-omnibus` have checkpoints. Other TUI demos are skipped until checkpoints are added.
+
+**Measure the window; don't derive it.** A tape's Sleep directives don't fix where its content lands: command execution varies run to run, so the same tape gives GIFs whose frame counts differ by tens of frames. Anchor to the end (a negative `start`) where the content is near it, and prefer a window that stays generous under that drift. OCR each candidate range before committing to it — `extract_frames` plus `ocr_image` over `range(n-500, n, 20)` prints where a pattern actually lives.
+
+**A window is calibrated for one target's terminal size.** One tape records at each target's own size, so a line's on-screen lifetime differs between them: the docs terminal is ~33 rows and the social one ~24. `wt merge`'s generated commit message survives to the end of the docs recording and scrolls off the social one within a second. Set `targets=("docs",)` on a checkpoint that depends on that, rather than widening the window until it catches an 18-frame band in both.
+
+**Prerequisites for TUI validation:** `ffmpeg` and `tesseract` must be installed.
+
+**Limitations:**
+- Tab completion sequences are not replayed; only `Type "command"` + `Enter` patterns are extracted
+- TUI demos without defined checkpoints are skipped
+- OCR accuracy depends on font rendering quality
+
+## Prerequisites
+
+**Requires Go** — The VHS fork is built from source ([install Go](https://go.dev/dl/)).
+
+**Requires ffmpeg with libass** — The keystroke overlay uses ASS subtitles, and Homebrew's regular `ffmpeg` formula is built without libass while holding the linked name, so installing or upgrading `ffmpeg` at any point takes the overlay away. `check_ffmpeg_libass` puts the full build in front of it on PATH for the run when it finds the linked one can't draw subtitles, and otherwise exits with:
+
+```bash
+brew install ffmpeg-full
+```
+
+External dependencies are downloaded/built automatically on first run:
+- **VHS** — Custom fork with keystroke overlay (cloned and built from source)
+- **Claude Code binary** — Downloaded from Anthropic's release bucket
+- **Zellij plugin** — Downloaded from GitHub releases
+
+Demos that launch Claude Code (`wt-switch`, `wt-statusline`, `wt-zellij-omnibus`) require authentication. On macOS, the recorder reuses the current `claude auth login` credential from the user's Keychain. Other environments can provide an OAuth token or API key:
+
+```bash
+export CLAUDE_CODE_OAUTH_TOKEN=...
+# or
+export ANTHROPIC_API_KEY=...
+```
+
+Recording uses the authenticated account's Claude usage.
+
+## Publishing demos
+
+After building, publish to the assets repo:
+
+```bash
+task publish-assets
+```
+
+This copies `docs/public/assets/{docs,social}/` to the `worktrunk-assets` repo (sibling directory), commits, and pushes. The script clones the repo via `gh` if missing.
+
+To fetch published assets (without rebuilding):
+
+```bash
+task fetch-assets
+```
+
+Both build and fetch output to the same location (`docs/public/assets/`), so local builds override fetched assets.
+
+## Modifying the VHS fork
+
+The VHS fork is cloned to `docs/demos/.deps/vhs/` and built automatically. To modify it:
+
+```bash
+# 1. Make changes in the cloned repo
+cd docs/demos/.deps/vhs
+# ... edit files ...
+
+# 2. Rebuild and test
+go build -o vhs .
+cd ../../../..
+./docs/demos/build docs --only wt-switch-picker
+
+# 3. Commit and push to the fork
+cd docs/demos/.deps/vhs
+git add -A
+git commit -m "Description"
+git push origin keypress-overlay
+```
+
+**CRITICAL**: Push changes to `origin keypress-overlay`. The directory is gitignored—changes only persist in the fork repo.
+
+### Keystroke overlay timing
+
+Each keystroke event is timed by the video's own clock: `Record` writes one
+frame per tick and only while recording, so `recordedMS` in `vhs.go` turns that
+frame count into the timeline the finished GIF plays on, and an event's time is
+where it lands in the output. A `Hide` stretch records no frames and so
+contributes nothing. Measured, a keypress and the frame that answers it are
+within one frame of each other (25fps = 40ms), so nothing is added on top.
+
+**Keys pressed while the recording is hidden all land on the first visible
+frame**, since a hidden stretch records no frames to separate them. Every docs
+demo types its opening command before `Show` on purpose — the first frame
+carries the whole command, which
+`test_docs_demos_open_on_a_complete_command_before_execution` pins — so that
+command arrives in the overlay in one go, matching the prompt already on
+screen. Anything the overlay should track key by key happens after `Show`.
+
+To check the alignment of a recorded GIF, extract its frames and compare the
+frame where the overlay changes against the frame where the screen answers:
+
+```bash
+ffmpeg -i demo.gif -fps_mode passthrough /tmp/gif-frames/frame_%04d.png
+```
+
+## The mocked forge
+
+`fixtures/gh-mock.sh` answers every `gh` call from a file under
+`$HOME/.local/share/gh-mock` that `write_gh_mock_data` (in `shared/lib.py`)
+writes after the branches exist. Each file's first line is how long the mock
+waits before answering; the rest is the JSON body.
+
+Three things have to hold or the mock is never reached, and each one silently
+empties the CI column rather than failing:
+
+- **A parseable origin.** wt's CI detection parses the remote URL for an
+ owner/repo before it will call `gh` at all, and a bare filesystem path doesn't
+ parse. `prepare_base_repo` sets origin to `DEMO_ORIGIN_URL` and rewrites only
+ *push* to the local bare repo via `url.<bare>.pushInsteadOf` — plain
+ `git remote get-url` applies `insteadOf` but not `pushInsteadOf`, so rewriting
+ fetch too would hand wt the local path back.
+- **`gh --version` and `gh auth status` both exiting 0.** `CiToolsStatus::detect`
+ gates every forge call on them.
+- **`DEMO_PROJECT_ID` matching the URL.** It keys the approvals file, so a URL
+ change without it leaves every project command unapproved.
+
+The per-branch delays in `DEMO_PRS` are what make the CI column *stream*: wt
+runs one `gh pr list` per branch concurrently, so staggered delays land the cells
+one at a time behind a frame that already painted from local git. Keep the
+largest under the tape's post-command sleep — `wt list` renders progressively but
+still can't finish until every call returns.
+
+The PR bodies and comment threads also ride these responses. `detect_github`
+primes the picker's on-disk comments cache from the `gh pr list` payload, so the
+`comments` tab renders with no second call.
+
+## wt-switch-picker demo goals (interactive picker)
+
+The wt-switch-picker demo showcases the interactive picker (`wt switch` without
+args). The list itself is the subject here, so `prepare_picker` gives it sixteen
+worktrees — the shared set plus `PICKER_EXTRA_BRANCHES`, where every other demo
+keeps the shared four — and its table reads like a repo someone works in.
+
+It is also the one demo that records at its own size, `SIZE_DOCS_PICKER`: the
+same 1600x900 canvas as the rest in smaller text, which buys 139x34 instead of
+102x25. At the usual size the columns worth watching — CI status and the branch
+summary — fall off the right edge, and the preview pane is too short to page a
+diff through. `prepare_picker` is also the reason the Summary column renders at
+all: it writes the user config, and the column is gated on an LLM command being
+configured. `fixtures/llm-mock.sh` answers those calls, picking a summary from
+the paths in the diff, so each branch's row is its own sentence.
+
+Variety to preserve across all columns:
+
+| Column | Demonstration |
+|--------|---------------|
+| CI | PR number colored by state (`#4` failing, `#5` changes-requested, `#2` running, `#1` stale head) vs bare `#` (branch CI, passing and failing) vs none |
+| HEAD± | Large unstaged diff (+106 -14), small (+1), none |
+| Status | Staged changes (+), unstaged (!), untracked (?), ahead/behind (↕) |
+| main↕ | Some branches ahead-only, some ahead-and-behind |
+| main…± | Meaningful merge-base diffstats (small to 300+ lines) |
+
+Branch setup:
+- **alpha** — Large working tree changes, unpushed commits (so its PR head reads
+ as stale), and the ten-comment thread the `comments` tab pages through
+- **beta** — Staged changes, behind main, PR with CI running
+- **hooks** — Staged+unstaged changes, no remote, so no CI at all
+- **`PICKER_EXTRA_BRANCHES`** — each carries one commit of its own; a branch left
+ on main's tip renders as an empty row *and* borrows main's branch CI, since
+ branch CI is keyed by commit
+
+Two keystroke hazards the tape works around, both of which pick the wrong
+worktree rather than failing:
+
+- **Narrowing the list keeps the cursor's row index**, not the row. A query
+ matching several rows leaves the cursor on whichever row now sits at that
+ index, and clearing the query restores the old index. Either type a query that
+ matches exactly one row, or type it before moving the cursor at all.
+- **The filter matches PR number, title and author too**, not just the branch
+ name and path. Adding a PR to a branch can make a previously unambiguous query
+ match several rows.
+
+## Alt keybindings in tapes
+
+`Alt+p`, `Alt+"8"` and the rest reach the program only because `buildTtyCmd` in
+the VHS fork passes `-t macOptionIsMeta=true` to ttyd. Without it xterm.js hands
+macOS Option to the browser's own composition and the program receives the
+unmodified character — so an `Alt+p` in a tape types a literal `p` into the
+picker's query, with no error anywhere. Verify a modifier reaches the program by
+recording a tape that runs `cat > file`, sending the key, and reading the bytes:
+alt-p is `1b70`, a bare `p` is `70`.
+
+VHS's parser takes a string, `Enter` or `Tab` after `Alt+`, so a digit needs
+quoting: `Alt+"8"`, not `Alt+8` (which fails to parse).
+
+## Light/dark theme variants
+
+The docs build generates both light and dark GIF variants in separate directories under `docs/public/assets/docs/` (the layout at the top of this file):
+- `light/wt-core.gif` / `dark/wt-core.gif`
+- `light/wt-core-mobile.gif` / `dark/wt-core-mobile.gif` (576×432 responsive homepage source)
+- `light/wt-merge.gif` / `dark/wt-merge.gif`
+- `light/wt-switch-picker.gif` / `dark/wt-switch-picker.gif`
+
+Each theme starts from a freshly prepared demo environment because recording a tape changes its repository and worktrees.
+
+Social build generates light only (social media doesn't support theme-switching media queries).
+
+Each recording's environment carries its theme. The VHS terminal, Zellij, and the starship prompt take their colors from `docs/demos/shared/themes.py`, which reads the `--wt-*` custom properties in `docs/src/styles/custom.css` when the build runs, so a site palette change reaches the GIFs on the next recording. Claude Code and delta switch to their own light or dark theme.
+
+## Debugging a demo environment
+
+Use `--shell` to spawn an interactive fish shell with the demo environment:
+
+```bash
+./docs/demos/build social --only wt-switch --shell
+```
+
+This builds the demo and drops you into a fish shell with `HOME`, `PATH`, starship, and wt shell integration all configured. You're already in the demo repo and ready to test:
+
+```fish
+# Now you can manually test:
+claude # See what happens on first launch
+wt switch --create foo # Create a worktree
+wt switch --execute claude --create bar # Test the demo command
+```
+
+After fish exits, the debug environment remains at the path printed when the shell starts. Remove that directory manually when you no longer need it.
+
+## Timing guidelines
+
+Demo GIFs should feel natural—not rushed, but not lingering. The goal is to let viewers read and understand each step before moving on.
+
+| Context | Duration | Rationale |
+|---------|----------|-----------|
+| Simple output (one-liner) | 1.5s | Just enough to scan a short result |
+| List/table output | 2–2.5s | Tables need more time to scan visually |
+| Multi-line text (config, log) | 3s | Dense text requires reading time |
+| Long operations (merge, hooks) | Match actual | Use real duration; don't artificially shorten |
+| LLM operations | 4s | Show thinking + generated output |
+| Transitions (cd, switch) | 1–1.5s | Brief pause after context change |
+| Quick sequences (keystrokes) | 0.1–0.5s | Related actions feel like one gesture |
+| Tab completion (shows menu) | 400ms | Pause after Tab when menu appears for viewer to see options |
+| Tab completion (cycles selection) | 300ms | Pause after Tab cycles to show selected option |
+| Tab completion (auto-completes) | 0 | No pause needed when Tab completes to single result |
+| Tab completion (before Enter) | 50ms | Required after final Tab/selection before Enter; lets fish settle |
+| Tab cycling → execute | Enter, 50ms, Enter | When Tab cycling with pager open: first Enter accepts, second executes |
+| End hold (before exit) | 2–4s | Let final state sink in |
+| Pre-enter pause | 1s | For commands where output clears visible area: TUI takeover (`claude`) or heavy output (`wt merge`). |
+| Claude UI startup | 6s | Big visual change; wait for UI to render and settle |
+
+**Principles:**
+
+1. **Focus on output, not typing.** TypingSpeed is fast (28ms). Time is for reading results.
+2. **Match reality for slow operations.** If `wt merge` takes 8s, sleep 8s. Don't fake speed.
+3. **Group related actions.** Multiple keystrokes (↓↓) can be rapid; pause after the group.
+4. **End with breathing room.** Viewers need a moment to absorb the final state.
+5. **Twitter context.** These are viewed on phones in noisy feeds—slightly longer is better than too fast.
+6. **Type what users would type.** If a flag is needed for technical reasons (e.g., `--color=always` for VHS), handle it in the background setup (env var, git config) so the demo shows the natural command. Never show flags users wouldn't normally type.
+
+## Key files in the demo environment
+
+After spawning the shell, these files control Claude Code behavior:
+
+- `$HOME/.claude.json` - Claude Code global config (onboarding flags, marketplace settings)
+- `$HOME/.claude/settings.json` - Claude Code settings (statusLine config)
+- `$HOME/.config/worktrunk/config.toml` - Worktrunk user config
+- `$HOME/w/acme/.config/wt.toml` - Project hooks config
+
+Key fields in `.claude.json` for suppressing notifications:
+- `officialMarketplaceAutoInstalled: true` - should suppress marketplace auto-install
+- `numStartups: 100` - makes Claude think it's been run many times
+- `hasCompletedOnboarding: true` - skips onboarding
+- `announcementImpressions` - suppresses launch promotions
+- `passesUpsellSeenCount`, `passesLastSeenRemaining`, and `hasVisitedPasses` - suppress the guest-pass promotion, including after eligibility refresh
+
+## Viewing GIF results
+
+**Do NOT use `open` on the GIF** — that's for the user to do manually.
+
+Inline viewing options:
+```bash
+# Quick Look (macOS)
+qlmanage -p docs/public/assets/docs/light/wt-switch-picker.gif
+
+# iTerm2 inline images
+imgcat docs/public/assets/docs/light/wt-switch-picker.gif
+```
+
+## Reviewing demo GIFs
+
+After building demos, use a subagent to review for visual errors before publishing.
+
+**Extract frames and review:**
+```bash
+rm -rf /tmp/frames && mkdir -p /tmp/frames
+magick path/to/demo.gif -coalesce /tmp/frames/frame_%04d.png
+```
+
+Then spawn a haiku subagent with these instructions:
+
+```
+Review this demo GIF for visual errors.
+
+Read frames sampled throughout the recording — every 50th frame covers a
+~2000 frame GIF in ~40 images. Use the Read tool on:
+/tmp/frames/frame_0050.png, frame_0100.png, frame_0150.png, ... etc.
+
+Look for:
+1. SPLIT COMMANDS: Text split across panes (e.g., "gi" in one pane, "t diff" in another)
+2. ERRORS/WARNINGS: Shell errors like "Unknown command", red error text, warning messages
+3. WRONG LOCATION: Commands or output appearing in unexpected pane/tab
+4. VISUAL GLITCHES: Partial characters, cursor artifacts, broken layouts
+
+Report each issue with:
+- Frame number(s)
+- Description
+- Affected text
+
+If a frame shows an error like "Unknown command: t", examine nearby frames
+(±5) to understand the cause — likely a timing bug where a command was split.
+```
+
+## Cleaning up stale demo processes
+
+**NEVER run `pkill -f zellij`** — this kills the user's own Zellij session, not just demo processes.
+
+If stale Zellij processes from previous demo runs are causing issues, either:
+- Let them die on their own (they'll timeout)
+- Target only demo processes: `pkill -f "zellij.*wt-demos"`
+- Remove the demo directory and rebuild: `rm -rf /private/tmp/wt-demos`
diff --git a/docs/demos/CLAUDE.md b/docs/demos/CLAUDE.md
index 0af2c6fec..43c994c2d 100644
--- a/docs/demos/CLAUDE.md
+++ b/docs/demos/CLAUDE.md
@@ -1,411 +1 @@
-# Demo Development
-
-## Directory structure
-
-```
-docs/demos/
- build # Unified build script
- tapes/ # All VHS tape files (templated)
- shared/ # Python library, themes, fixtures
- tests/ # Tests for the build script and tape conventions
- .deps/vhs/ # VHS fork clone and binary (gitignored, built on demand)
-
-docs/public/assets/ # Output GIFs (gitignored, shared with fetch-assets)
- docs/ # Doc site demos (1600x900; wt-core-mobile is 576x432)
- light/ # Light theme variants
- dark/ # Dark theme variants
- social/ # Social media demos (1200x700)
- light/ # Light theme only
-```
-
-Tape files use template variables (`{{FONTSIZE}}`, `{{WIDTH}}`, `{{HEIGHT}}`) so the same tape produces different sizes for docs vs social.
-
-## Regenerating demos
-
-```bash
-./docs/demos/build docs # Doc site demos (1600x900, light + dark)
-./docs/demos/build social # Social media demos (1200x700, light only)
-./docs/demos/build docs --text # Text output instead of GIFs
-```
-
-Text output captures terminal frames as plain text. Works for all demos, though interactive demos (TUI navigation, Zellij tabs) produce less useful output since the visual interactions don't translate to text.
-
-Regenerate a single demo:
-
-```bash
-./docs/demos/build social --only wt-switch
-./docs/demos/build docs --only wt-merge
-./docs/demos/build docs --only wt-core-mobile
-```
-
-**Available demos:**
-
-| Target | Demos |
-|--------|-------|
-| docs | wt-core, wt-core-mobile, wt-switch, wt-list, wt-commit, wt-statusline, wt-merge, wt-switch-picker, wt-zellij-omnibus |
-| social | wt-switch, wt-statusline, wt-list, wt-list-remove, wt-hooks, wt-devserver, wt-commit, wt-merge, wt-switch-picker, wt-core, wt-zellij-omnibus |
-
-## Snapshot testing
-
-```bash
-./docs/demos/build docs --snapshot # Generate all snapshots
-./docs/demos/build docs --snapshot --only wt-list # Single demo
-```
-
-Snapshots capture command output (not terminal rendering) and are committed to `docs/demos/snapshots/`. Use them to catch regressions like new hints creeping in.
-
-**How to use:**
-1. After changing wt output, regenerate snapshots: `./docs/demos/build docs --snapshot`
-2. Review the diff - small changes (commit hashes, minor formatting) are expected
-3. Commit the updated snapshots alongside your changes
-
-**What changes are expected:**
-- Commit hashes change each run (demo repo is recreated)
-- Column widths may shift slightly
-
-**What changes indicate regressions:**
-- New hints or warnings appearing
-- Output format changes you didn't intend
-- New lines or missing output
-
-**TUI demo validation:**
-
-TUI demos (Zellij, Claude UI) can't use text snapshots because VHS only captures the outer terminal, not content inside terminal multiplexers. Instead, they use OCR-based validation:
-
-1. After recording, specific frames are extracted from the GIF using ffmpeg
-2. Tesseract OCR extracts text from those frames
-3. The text is validated for expected/forbidden patterns
-4. Validation runs automatically when building TUI demos with defined checkpoints
-
-Checkpoints are defined in `docs/demos/shared/validation.py`. To add validation to a TUI demo:
-1. Identify key frame numbers by examining the GIF (25fps, so frame 75 = 3 seconds; a negative frame counts back from the last, for the state a recording ends in)
-2. Define checkpoint patterns in `validation.py` with frame numbers, expected patterns, and forbidden patterns
-
-`wt-switch`, `wt-switch-picker`, `wt-statusline`, and `wt-zellij-omnibus` have checkpoints. Other TUI demos are skipped until checkpoints are added.
-
-**Measure the window; don't derive it.** A tape's Sleep directives don't fix where its content lands: command execution varies run to run, so the same tape gives GIFs whose frame counts differ by tens of frames. Anchor to the end (a negative `start`) where the content is near it, and prefer a window that stays generous under that drift. OCR each candidate range before committing to it — `extract_frames` plus `ocr_image` over `range(n-500, n, 20)` prints where a pattern actually lives.
-
-**A window is calibrated for one target's terminal size.** One tape records at each target's own size, so a line's on-screen lifetime differs between them: the docs terminal is ~33 rows and the social one ~24. `wt merge`'s generated commit message survives to the end of the docs recording and scrolls off the social one within a second. Set `targets=("docs",)` on a checkpoint that depends on that, rather than widening the window until it catches an 18-frame band in both.
-
-**Prerequisites for TUI validation:** `ffmpeg` and `tesseract` must be installed.
-
-**Limitations:**
-- Tab completion sequences are not replayed; only `Type "command"` + `Enter` patterns are extracted
-- TUI demos without defined checkpoints are skipped
-- OCR accuracy depends on font rendering quality
-
-## Prerequisites
-
-**Requires Go** — The VHS fork is built from source ([install Go](https://go.dev/dl/)).
-
-**Requires ffmpeg with libass** — The keystroke overlay uses ASS subtitles, and Homebrew's regular `ffmpeg` formula is built without libass while holding the linked name, so installing or upgrading `ffmpeg` at any point takes the overlay away. `check_ffmpeg_libass` puts the full build in front of it on PATH for the run when it finds the linked one can't draw subtitles, and otherwise exits with:
-
-```bash
-brew install ffmpeg-full
-```
-
-External dependencies are downloaded/built automatically on first run:
-- **VHS** — Custom fork with keystroke overlay (cloned and built from source)
-- **Claude Code binary** — Downloaded from Anthropic's release bucket
-- **Zellij plugin** — Downloaded from GitHub releases
-
-Demos that launch Claude Code (`wt-switch`, `wt-statusline`, `wt-zellij-omnibus`) require authentication. On macOS, the recorder reuses the current `claude auth login` credential from the user's Keychain. Other environments can provide an OAuth token or API key:
-
-```bash
-export CLAUDE_CODE_OAUTH_TOKEN=...
-# or
-export ANTHROPIC_API_KEY=...
-```
-
-Recording uses the authenticated account's Claude usage.
-
-## Publishing demos
-
-After building, publish to the assets repo:
-
-```bash
-task publish-assets
-```
-
-This copies `docs/public/assets/{docs,social}/` to the `worktrunk-assets` repo (sibling directory), commits, and pushes. The script clones the repo via `gh` if missing.
-
-To fetch published assets (without rebuilding):
-
-```bash
-task fetch-assets
-```
-
-Both build and fetch output to the same location (`docs/public/assets/`), so local builds override fetched assets.
-
-## Modifying the VHS fork
-
-The VHS fork is cloned to `docs/demos/.deps/vhs/` and built automatically. To modify it:
-
-```bash
-# 1. Make changes in the cloned repo
-cd docs/demos/.deps/vhs
-# ... edit files ...
-
-# 2. Rebuild and test
-go build -o vhs .
-cd ../../../..
-./docs/demos/build docs --only wt-switch-picker
-
-# 3. Commit and push to the fork
-cd docs/demos/.deps/vhs
-git add -A
-git commit -m "Description"
-git push origin keypress-overlay
-```
-
-**CRITICAL**: Push changes to `origin keypress-overlay`. The directory is gitignored—changes only persist in the fork repo.
-
-### Keystroke overlay timing
-
-Each keystroke event is timed by the video's own clock: `Record` writes one
-frame per tick and only while recording, so `recordedMS` in `vhs.go` turns that
-frame count into the timeline the finished GIF plays on, and an event's time is
-where it lands in the output. A `Hide` stretch records no frames and so
-contributes nothing. Measured, a keypress and the frame that answers it are
-within one frame of each other (25fps = 40ms), so nothing is added on top.
-
-**Keys pressed while the recording is hidden all land on the first visible
-frame**, since a hidden stretch records no frames to separate them. Every docs
-demo types its opening command before `Show` on purpose — the first frame
-carries the whole command, which
-`test_docs_demos_open_on_a_complete_command_before_execution` pins — so that
-command arrives in the overlay in one go, matching the prompt already on
-screen. Anything the overlay should track key by key happens after `Show`.
-
-To check the alignment of a recorded GIF, extract its frames and compare the
-frame where the overlay changes against the frame where the screen answers:
-
-```bash
-ffmpeg -i demo.gif -fps_mode passthrough /tmp/gif-frames/frame_%04d.png
-```
-
-## The mocked forge
-
-`fixtures/gh-mock.sh` answers every `gh` call from a file under
-`$HOME/.local/share/gh-mock` that `write_gh_mock_data` (in `shared/lib.py`)
-writes after the branches exist. Each file's first line is how long the mock
-waits before answering; the rest is the JSON body.
-
-Three things have to hold or the mock is never reached, and each one silently
-empties the CI column rather than failing:
-
-- **A parseable origin.** wt's CI detection parses the remote URL for an
- owner/repo before it will call `gh` at all, and a bare filesystem path doesn't
- parse. `prepare_base_repo` sets origin to `DEMO_ORIGIN_URL` and rewrites only
- *push* to the local bare repo via `url.<bare>.pushInsteadOf` — plain
- `git remote get-url` applies `insteadOf` but not `pushInsteadOf`, so rewriting
- fetch too would hand wt the local path back.
-- **`gh --version` and `gh auth status` both exiting 0.** `CiToolsStatus::detect`
- gates every forge call on them.
-- **`DEMO_PROJECT_ID` matching the URL.** It keys the approvals file, so a URL
- change without it leaves every project command unapproved.
-
-The per-branch delays in `DEMO_PRS` are what make the CI column *stream*: wt
-runs one `gh pr list` per branch concurrently, so staggered delays land the cells
-one at a time behind a frame that already painted from local git. Keep the
-largest under the tape's post-command sleep — `wt list` renders progressively but
-still can't finish until every call returns.
-
-The PR bodies and comment threads also ride these responses. `detect_github`
-primes the picker's on-disk comments cache from the `gh pr list` payload, so the
-`comments` tab renders with no second call.
-
-## wt-switch-picker demo goals (interactive picker)
-
-The wt-switch-picker demo showcases the interactive picker (`wt switch` without
-args). The list itself is the subject here, so `prepare_picker` gives it sixteen
-worktrees — the shared set plus `PICKER_EXTRA_BRANCHES`, where every other demo
-keeps the shared four — and its table reads like a repo someone works in.
-
-It is also the one demo that records at its own size, `SIZE_DOCS_PICKER`: the
-same 1600x900 canvas as the rest in smaller text, which buys 139x34 instead of
-102x25. At the usual size the columns worth watching — CI status and the branch
-summary — fall off the right edge, and the preview pane is too short to page a
-diff through. `prepare_picker` is also the reason the Summary column renders at
-all: it writes the user config, and the column is gated on an LLM command being
-configured. `fixtures/llm-mock.sh` answers those calls, picking a summary from
-the paths in the diff, so each branch's row is its own sentence.
-
-Variety to preserve across all columns:
-
-| Column | Demonstration |
-|--------|---------------|
-| CI | PR number colored by state (`#4` failing, `#5` changes-requested, `#2` running, `#1` stale head) vs bare `#` (branch CI, passing and failing) vs none |
-| HEAD± | Large unstaged diff (+106 -14), small (+1), none |
-| Status | Staged changes (+), unstaged (!), untracked (?), ahead/behind (↕) |
-| main↕ | Some branches ahead-only, some ahead-and-behind |
-| main…± | Meaningful merge-base diffstats (small to 300+ lines) |
-
-Branch setup:
-- **alpha** — Large working tree changes, unpushed commits (so its PR head reads
- as stale), and the ten-comment thread the `comments` tab pages through
-- **beta** — Staged changes, behind main, PR with CI running
-- **hooks** — Staged+unstaged changes, no remote, so no CI at all
-- **`PICKER_EXTRA_BRANCHES`** — each carries one commit of its own; a branch left
- on main's tip renders as an empty row *and* borrows main's branch CI, since
- branch CI is keyed by commit
-
-Two keystroke hazards the tape works around, both of which pick the wrong
-worktree rather than failing:
-
-- **Narrowing the list keeps the cursor's row index**, not the row. A query
- matching several rows leaves the cursor on whichever row now sits at that
- index, and clearing the query restores the old index. Either type a query that
- matches exactly one row, or type it before moving the cursor at all.
-- **The filter matches PR number, title and author too**, not just the branch
- name and path. Adding a PR to a branch can make a previously unambiguous query
- match several rows.
-
-## Alt keybindings in tapes
-
-`Alt+p`, `Alt+"8"` and the rest reach the program only because `buildTtyCmd` in
-the VHS fork passes `-t macOptionIsMeta=true` to ttyd. Without it xterm.js hands
-macOS Option to the browser's own composition and the program receives the
-unmodified character — so an `Alt+p` in a tape types a literal `p` into the
-picker's query, with no error anywhere. Verify a modifier reaches the program by
-recording a tape that runs `cat > file`, sending the key, and reading the bytes:
-alt-p is `1b70`, a bare `p` is `70`.
-
-VHS's parser takes a string, `Enter` or `Tab` after `Alt+`, so a digit needs
-quoting: `Alt+"8"`, not `Alt+8` (which fails to parse).
-
-## Light/dark theme variants
-
-The docs build generates both light and dark GIF variants in separate directories under `docs/public/assets/docs/` (the layout at the top of this file):
-- `light/wt-core.gif` / `dark/wt-core.gif`
-- `light/wt-core-mobile.gif` / `dark/wt-core-mobile.gif` (576×432 responsive homepage source)
-- `light/wt-merge.gif` / `dark/wt-merge.gif`
-- `light/wt-switch-picker.gif` / `dark/wt-switch-picker.gif`
-
-Each theme starts from a freshly prepared demo environment because recording a tape changes its repository and worktrees.
-
-Social build generates light only (social media doesn't support theme-switching media queries).
-
-Each recording's environment carries its theme. The VHS terminal, Zellij, and the starship prompt take their colors from `docs/demos/shared/themes.py`, which reads the `--wt-*` custom properties in `docs/src/styles/custom.css` when the build runs, so a site palette change reaches the GIFs on the next recording. Claude Code and delta switch to their own light or dark theme.
-
-## Debugging a demo environment
-
-Use `--shell` to spawn an interactive fish shell with the demo environment:
-
-```bash
-./docs/demos/build social --only wt-switch --shell
-```
-
-This builds the demo and drops you into a fish shell with `HOME`, `PATH`, starship, and wt shell integration all configured. You're already in the demo repo and ready to test:
-
-```fish
-# Now you can manually test:
-claude # See what happens on first launch
-wt switch --create foo # Create a worktree
-wt switch --execute claude --create bar # Test the demo command
-```
-
-After fish exits, the debug environment remains at the path printed when the shell starts. Remove that directory manually when you no longer need it.
-
-## Timing guidelines
-
-Demo GIFs should feel natural—not rushed, but not lingering. The goal is to let viewers read and understand each step before moving on.
-
-| Context | Duration | Rationale |
-|---------|----------|-----------|
-| Simple output (one-liner) | 1.5s | Just enough to scan a short result |
-| List/table output | 2–2.5s | Tables need more time to scan visually |
-| Multi-line text (config, log) | 3s | Dense text requires reading time |
-| Long operations (merge, hooks) | Match actual | Use real duration; don't artificially shorten |
-| LLM operations | 4s | Show thinking + generated output |
-| Transitions (cd, switch) | 1–1.5s | Brief pause after context change |
-| Quick sequences (keystrokes) | 0.1–0.5s | Related actions feel like one gesture |
-| Tab completion (shows menu) | 400ms | Pause after Tab when menu appears for viewer to see options |
-| Tab completion (cycles selection) | 300ms | Pause after Tab cycles to show selected option |
-| Tab completion (auto-completes) | 0 | No pause needed when Tab completes to single result |
-| Tab completion (before Enter) | 50ms | Required after final Tab/selection before Enter; lets fish settle |
-| Tab cycling → execute | Enter, 50ms, Enter | When Tab cycling with pager open: first Enter accepts, second executes |
-| End hold (before exit) | 2–4s | Let final state sink in |
-| Pre-enter pause | 1s | For commands where output clears visible area: TUI takeover (`claude`) or heavy output (`wt merge`). |
-| Claude UI startup | 6s | Big visual change; wait for UI to render and settle |
-
-**Principles:**
-
-1. **Focus on output, not typing.** TypingSpeed is fast (28ms). Time is for reading results.
-2. **Match reality for slow operations.** If `wt merge` takes 8s, sleep 8s. Don't fake speed.
-3. **Group related actions.** Multiple keystrokes (↓↓) can be rapid; pause after the group.
-4. **End with breathing room.** Viewers need a moment to absorb the final state.
-5. **Twitter context.** These are viewed on phones in noisy feeds—slightly longer is better than too fast.
-6. **Type what users would type.** If a flag is needed for technical reasons (e.g., `--color=always` for VHS), handle it in the background setup (env var, git config) so the demo shows the natural command. Never show flags users wouldn't normally type.
-
-## Key files in the demo environment
-
-After spawning the shell, these files control Claude Code behavior:
-
-- `$HOME/.claude.json` - Claude Code global config (onboarding flags, marketplace settings)
-- `$HOME/.claude/settings.json` - Claude Code settings (statusLine config)
-- `$HOME/.config/worktrunk/config.toml` - Worktrunk user config
-- `$HOME/w/acme/.config/wt.toml` - Project hooks config
-
-Key fields in `.claude.json` for suppressing notifications:
-- `officialMarketplaceAutoInstalled: true` - should suppress marketplace auto-install
-- `numStartups: 100` - makes Claude think it's been run many times
-- `hasCompletedOnboarding: true` - skips onboarding
-- `announcementImpressions` - suppresses launch promotions
-- `passesUpsellSeenCount`, `passesLastSeenRemaining`, and `hasVisitedPasses` - suppress the guest-pass promotion, including after eligibility refresh
-
-## Viewing GIF results
-
-**Do NOT use `open` on the GIF** — that's for the user to do manually.
-
-Inline viewing options:
-```bash
-# Quick Look (macOS)
-qlmanage -p docs/public/assets/docs/light/wt-switch-picker.gif
-
-# iTerm2 inline images
-imgcat docs/public/assets/docs/light/wt-switch-picker.gif
-```
-
-## Reviewing demo GIFs
-
-After building demos, use a subagent to review for visual errors before publishing.
-
-**Extract frames and review:**
-```bash
-rm -rf /tmp/frames && mkdir -p /tmp/frames
-magick path/to/demo.gif -coalesce /tmp/frames/frame_%04d.png
-```
-
-Then spawn a haiku subagent with these instructions:
-
-```
-Review this demo GIF for visual errors.
-
-Read frames sampled throughout the recording — every 50th frame covers a
-~2000 frame GIF in ~40 images. Use the Read tool on:
-/tmp/frames/frame_0050.png, frame_0100.png, frame_0150.png, ... etc.
-
-Look for:
-1. SPLIT COMMANDS: Text split across panes (e.g., "gi" in one pane, "t diff" in another)
-2. ERRORS/WARNINGS: Shell errors like "Unknown command", red error text, warning messages
-3. WRONG LOCATION: Commands or output appearing in unexpected pane/tab
-4. VISUAL GLITCHES: Partial characters, cursor artifacts, broken layouts
-
-Report each issue with:
-- Frame number(s)
-- Description
-- Affected text
-
-If a frame shows an error like "Unknown command: t", examine nearby frames
-(±5) to understand the cause — likely a timing bug where a command was split.
-```
-
-## Cleaning up stale demo processes
-
-**NEVER run `pkill -f zellij`** — this kills the user's own Zellij session, not just demo processes.
-
-If stale Zellij processes from previous demo runs are causing issues, either:
-- Let them die on their own (they'll timeout)
-- Target only demo processes: `pkill -f "zellij.*wt-demos"`
-- Remove the demo directory and rebuild: `rm -rf /private/tmp/wt-demos`
diff --git a/docs/demos/shared/lib.py b/docs/demos/shared/lib.py
index 50b310d56..ffdc64bfc 100644
--- a/docs/demos/shared/lib.py
+++ b/docs/demos/shared/lib.py
@@ -1271,10 +1271,8 @@ def prepare_demo_repo(env: DemoEnv, repo_root: Path, hooks_config: str = None):
if hooks_config is None:
hooks_config = '[pre-merge]\ntest = "cargo nextest run"\n'
(env.repo / ".config" / "wt.toml").write_text(hooks_config)
- claude_md_dir = env.repo / ".claude"
- claude_md_dir.mkdir(exist_ok=True)
- (claude_md_dir / "CLAUDE.md").write_text("# Acme App\n\nRust project. Run `cargo test` for tests.\n")
- git(["-C", str(env.repo), "add", ".config/wt.toml", ".claude/CLAUDE.md"])
+ (env.repo / "AGENTS.md").write_text("# Acme App\n\nRust project. Run `cargo test` for tests.\n")
+ git(["-C", str(env.repo), "add", ".config/wt.toml", "AGENTS.md"])
commit_dated(env.repo, "Add project hooks", "5d")
git(["-C", str(env.repo), "push", "-q"])
diff --git a/docs/src/content/docs/tips-patterns.md b/docs/src/content/docs/tips-patterns.md
index 9893b02ab..a70c007a5 100644
--- a/docs/src/content/docs/tips-patterns.md
+++ b/docs/src/content/docs/tips-patterns.md
@@ -468,7 +468,7 @@ This lets one agent session hand off work to another that runs in the background
The [worktrunk skill](/claude-code/) includes guidance for Claude Code (and other agent CLIs that load it) to execute this pattern. To enable it, request it explicitly ("spawn a parallel worktree for...") or add to your project instructions (`CLAUDE.md` or `AGENTS.md`):
-```markdown title="CLAUDE.md"
+```markdown title="AGENTS.md"
When I ask you to spawn parallel worktrees, use the agent handoff pattern
from the worktrunk skill.
```
diff --git a/flake.nix b/flake.nix
index ac43d3af7..2fef12bb5 100644
--- a/flake.nix
+++ b/flake.nix
@@ -155,7 +155,7 @@
# tests/ fixtures (prebuilt _git/ trees, .sh scripts, no-extension
# git database files). Default features only — shell-integration-
# tests wants a PTY and more shells than this derivation carries;
- # the devShell below is where that set lives (see tests/CLAUDE.md →
+ # the devShell below is where that set lives (see tests/AGENTS.md →
# "Feature Flags, Not Runtime Skipping").
worktrunk-tests = craneLib.cargoTest (
commonArgs
diff --git a/plugins/worktrunk/AGENTS.md b/plugins/worktrunk/AGENTS.md
new file mode 100644
index 000000000..a11a4af1c
--- /dev/null
+++ b/plugins/worktrunk/AGENTS.md
@@ -0,0 +1,167 @@
+# Worktrunk Plugin Guidelines (Claude Code + Codex)
+
+## Directory Layout
+
+This directory (`plugins/worktrunk/`) is the Claude Code + Codex payload. Each
+tool hardcodes its loader path with no fallback, so the repo root carries one
+pointer per tool: Claude's and Codex's both `source → ./plugins/worktrunk`,
+while Gemini resolves its extension at the repo root itself; Gemini's hooks
+call the canonical `hooks/wt.sh` below.
+
+```
+worktrunk/ ← repo root = marketplace root
+├── .claude-plugin/marketplace.json ← Claude pointer (source → ./plugins/worktrunk)
+├── .agents/plugins/marketplace.json← Codex pointer (source → ./plugins/worktrunk)
+├── .claude/skills/ ← authored repo-local maintainer skills
+├── .agents/skills → ../.claude/skills
+│ Codex repo-skill pointer
+├── gemini-extension.json ← Gemini manifest (extensionPath = repo root)
+├── hooks/hooks.json ← Gemini activity hooks (call the wt.sh below)
+├── skills/ ← real dir; Gemini reads ${extensionPath}/skills directly
+└── plugins/worktrunk/ ← plugin root (Claude + Codex resolve source here)
+ ├── .claude-plugin/plugin.json ← Claude manifest (metadata only — NO `hooks`
+ │ or `skills` keys; components load by
+ │ convention, see below)
+ ├── .codex-plugin/plugin.json ← Codex manifest (Codex's required wrapper)
+ ├── hooks/hooks.json ← Claude activity + WorktreeCreate/Remove hooks,
+ │ discovered by convention at this exact path
+ │ (#3417; Codex is kept off it by its inline
+ │ manifest, #3362)
+ ├── hooks/wt.sh ← canonical hook shim; Claude reaches it via
+ │ $CLAUDE_PLUGIN_ROOT, Codex via $PLUGIN_ROOT,
+ │ Gemini via
+ │ ${extensionPath}/plugins/worktrunk/hooks/wt.sh
+ ├── hooks/wt.cmd ← finds Git Bash for cmd.exe, which is what runs
+ │ a Codex `commandWindows`, then runs wt.sh (#4007)
+ ├── skills/ ← generated real-file mirror of repo-root
+ │ skills/ (test_docs_are_in_sync; never
+ │ hand-edit) — real files because Codex's
+ │ installer drops symlinks, see below
+ ├── AGENTS.md / README.md
+ └── (Codex activity hooks live *inline* in .codex-plugin/plugin.json's
+ `hooks` key — see Known Limitations below)
+```
+
+The repo-local maintainer skills are separate from the distributed plugin
+skills. `.claude/skills/` is their authored home, and the relative
+`.agents/skills` symlink lets Codex discover the same files. On Windows
+checkouts with `core.symlinks=false`, Git materializes the link as a plain file
+and Codex loads none of these repo-local skills. This limitation is accepted;
+installed plugins use the real-file mirror below and are unaffected.
+
+Path resolution differs by tool, all verified end-to-end against the real CLIs:
+
+- **Claude** (claude-cli 2.1.207): `.claude-plugin/marketplace.json` `source:
+ "./plugins/worktrunk"`. Claude reads
+ `plugins/worktrunk/.claude-plugin/plugin.json` — the same wrapper convention
+ as the marketplace root, and the only manifest location `claude plugin
+ validate` accepts (a bare `plugin.json` at the plugin root loads through an
+ undocumented fallback but fails validation). The manifest deliberately
+ carries no `version` field: installs pin the marketplace git SHA, so a
+ semver here would be a second version to maintain with nothing consuming
+ it — `claude plugin validate`'s missing-`version` warning is accepted.
+ Components load by **convention**, and the manifest must not name them:
+ - Hooks are discovered at `hooks/hooks.json`. The loader does not honor the
+ string-path `hooks` manifest override for plugin loads, so a renamed file
+ silently loads nothing (#3417) and a `hooks` key pointing at the
+ conventional path is dead config that can only mask a mislocated file.
+ - Skills are auto-discovered by scanning `skills/` for `<dir>/SKILL.md`; a
+ `skills` manifest array only *adds* directories to that scan, so listing
+ the defaults is redundant.
+
+ `$CLAUDE_PLUGIN_ROOT` is the plugin root.
+- **Codex** (codex-cli 0.144.1): `.agents/plugins/marketplace.json` `source`
+ object `{ "source": "local", "path": "./plugins/worktrunk" }`. Codex reads
+ `plugins/worktrunk/.codex-plugin/plugin.json`. Skills load by convention —
+ with no `skills` manifest key, Codex scans `<plugin-root>/skills/`; an
+ explicit `"skills": "./skills/"` names the same directory, so the manifest
+ carries no `skills` key. The scanned tree is the real-file mirror ("Plugin
+ skills are a generated mirror" below).
+- **Gemini**: `gemini-extension.json` at the repo root; `${extensionPath}` is
+ the repo root, so `${extensionPath}/skills/` is the repo-root `skills/`
+ directly and `hooks/hooks.json` (repo root) calls the canonical shim at
+ `${extensionPath}/plugins/worktrunk/hooks/wt.sh`. No symlink or copy.
+
+All three tools pick up the whole `skills/` set — Gemini reads the repo-root
+directory, Claude and Codex ship the plugin mirror — so a new repo-root skill
+ships everywhere once `test_docs_are_in_sync` regenerates the mirror, provided
+its directory contains a `SKILL.md` (`test_plugin_layout_is_consolidated`
+enforces that; a directory without one is silently ignored). Claude-only
+skills reach the other tools too (accepted tradeoff — see Known Limitations
+below).
+
+### Plugin skills are a generated mirror
+
+`plugins/worktrunk/skills/` is a real-file mirror of the authored repo-root
+`skills/`, regenerated — symlinks dereferenced, stale files deleted — by the
+`sync_plugin_skills_mirror` stage of `test_docs_are_in_sync`; never hand-edit
+it. Repo-root `skills/` stays the authored home: Gemini reads it directly and
+the docs sync writes into it.
+
+The mirror holds real files because of how the plugin ships, verified
+end-to-end against codex-cli 0.144.1 (scratch marketplaces through
+`codex plugin marketplace add` + `codex plugin add`, skill inventory read with
+`codex debug prompt-input`):
+
+- `codex plugin add` copies the plugin into
+ `$CODEX_HOME/plugins/cache/<marketplace>/<plugin>/<version>` with a copier
+ that handles only regular files and directories, silently skipping symlink
+ entries (`copy_dir_recursive` in `codex-rs/core-plugins/src/store.rs`), and
+ sessions load from that cache copy. A symlink anywhere in the tree — a
+ top-level `skills` link or one nested under `reference/` — ships no
+ content. No manifest value can bridge it: manifest paths must stay within
+ the plugin root (`..` and absolute paths are rejected,
+ `resolve_manifest_path` in `codex-rs/core-plugins/src/manifest.rs`).
+- Codex's convention scan (`default_skill_roots`, the empty-`skills` branch of
+ `plugin_skill_roots` in `codex-rs/core-plugins/src/loader.rs`) reads the
+ mirror like any directory.
+- Claude's installer dereferences symlinks, so a symlinked `skills/` worked
+ for Claude; the mirror serves it identically. A symlink also materializes as
+ a plain text file on Windows checkouts, which shipped no skills from a
+ Windows clone to Claude or Codex.
+
+`test_plugin_layout_is_consolidated` pins the no-symlinks invariant;
+`test_docs_are_in_sync` pins content equality with repo-root `skills/`.
+
+## Known Limitations
+
+### Status stays on the launch worktree (Claude)
+
+Claude marker hooks resolve through `-C "$CLAUDE_PROJECT_DIR"`. `EnterWorktree` does not change that directory, so the marker stays on the launch worktree for the session. Sessions launched outside a repository have no activity marker.
+
+### Status persists after user interrupt (Claude)
+
+The Claude hooks track activity via git config (`worktrunk.state.{branch}.marker`):
+- `UserPromptSubmit` → 🤖 (working)
+- `Notification`, `PreToolUse`(`AskUserQuestion`), `PermissionRequest`, `Stop` → 💬 (waiting for input)
+- `SessionEnd` → clears status
+
+An `EnterWorktree` that `wt config plugins claude approve-enter-worktree` approves shows no dialog, so it leaves the marker alone; the approval and the marker share one `PermissionRequest` command because Claude Code runs matching hooks in parallel (skills/wt-switch-create/rationale.md, "The confirmation hook").
+
+The 💬 transitions overlap deliberately: `Notification` covers the documented permission/idle path, but on platforms where it doesn't fire (VS Code extension, Windows CLI) `PermissionRequest` and `Stop` still mark the wait; `PreToolUse`(`AskUserQuestion`) catches the built-in question picker, which fires no `Notification` on any platform ([claude-code#13024](https://github.com/anthropics/claude-code/issues/13024)). There is currently no transition back to 🤖 once a turn-end/permission marker is set except a fresh `UserPromptSubmit`, so 💬 can persist into resumed work after a permission grant (the original symptom in [#2916](https://github.com/max-sixty/worktrunk/issues/2916)).
+
+**Problem**: If the user interrupts Claude Code (Escape/Ctrl+C), the 🤖 status persists because there's no `UserInterrupt` hook. The `Stop` hook explicitly does not fire on user interrupt.
+
+**Tracking**: [claude-code#9516](https://github.com/anthropics/claude-code/issues/9516)
+
+### Codex activity hooks
+
+Claude's hooks live in the standalone `hooks/hooks.json` its loader discovers by convention (see Directory Layout above); the Codex manifest carries `hooks` as an **inline object**, `{ "hooks": { … } }`, embedding a Codex-tailored hooks file directly. The inline form is deliberate:
+
+- **Why inline for Codex, not a path or an absent key.** Claude and Codex share one payload dir, and Codex *also* auto-discovers `hooks/hooks.json` at the plugin root by convention (`DEFAULT_HOOKS_CONFIG_FILE`, the `None` branch of `load_plugin_hooks`) — which once surfaced Worktrunk's *Claude* events in a Codex session ([#3362](https://github.com/max-sixty/worktrunk/issues/3362)). The Codex manifest carries its own hooks **inline**, taking Codex's `Some(Inline)` branch (`resolve_manifest_hooks` in `codex-rs/core-plugins/src/manifest.rs`), which **overrides** convention discovery. The inline object is both the functional definition of the Codex-native events and the thing that keeps Codex off the shared `hooks/hooks.json`, so the two toolchains coexist on one file: Claude discovers it, Codex ignores it. (Scoping via the filename instead — `hooks/claude-hooks.json` — breaks Claude's discovery, [#3417](https://github.com/max-sixty/worktrunk/issues/3417); the inline override makes it unnecessary.)
+- **Why `$PLUGIN_ROOT`, not `$CLAUDE_PLUGIN_ROOT`.** Codex exports both to hook commands (`PLUGIN_ROOT` native, `CLAUDE_PLUGIN_ROOT` as an OOTB-compat alias — `codex-rs/hooks/src/engine/discovery.rs`). The Codex file uses the native `$PLUGIN_ROOT` so nothing Claude-branded appears in a Codex session.
+
+- **Why every hook also carries `commandWindows`.** Codex runs a hook `command` through the platform shell — `/bin/sh -lc` on Unix, `cmd.exe /C` on Windows (`default_shell_command` in `codex-rs/hooks/src/engine/command_runner.rs`). Under `cmd.exe` the leading bare `bash` resolves through the Windows PATH to `System32\bash.exe`, the WSL launcher rather than Git Bash, which in a sandboxed session fails outright (`Bash/Service/CreateInstance/E_ACCESSDENIED`) and turns every prompt, permission, stop, and session-end event into a "Hook failed" banner ([#4007](https://github.com/max-sixty/worktrunk/issues/4007)). Only the bare *name* is the problem — Git for Windows is a requirement either way — so the per-handler `commandWindows` key, which **replaces** `command` on Windows (`command_windows.unwrap_or(command)` in `codex-rs/hooks/src/engine/discovery.rs`), calls `hooks/wt.cmd`: a shim that resolves `bash.exe` by path the way `find_git_bash` does in `src/shell_exec.rs` (derived from `where git.exe`, then the system-wide and per-user install defaults, `Git\bin\bash.exe` before `Git\usr\bin\bash.exe` because the former is the wrapper that puts `uname` and friends on PATH for a caller outside Git Bash) and then runs the same `wt.sh` every other integration goes through, so worktrunk's own resolution order lives in one script rather than in two languages. The `git.exe` lookup uses `where`'s `$PATH:` prefix and runs the absolute path it returns: an unscoped `where`, like cmd's own bare-name lookup, searches the current directory first, which for a hook is the user's project — so a `git.exe` committed to a repo would choose the bash every event runs (`test_shim_ignores_a_git_in_the_current_directory`). `where` itself is spelled `%SystemRoot%\System32\where.exe` for the same reason — it is `System32\where.exe` rather than a cmd built-in, so cmd resolves that bare name from the current directory too (`test_shim_ignores_a_where_in_the_current_directory`). Both of those see only the *wrong* bash; a lookup that finds nothing falls through to `%ProgramFiles%\Git`, which resolves on any Windows box, so `test_shim_derives_bash_from_the_git_on_path` points both install-default variables at an empty directory and leaves the derive branch as the only route to a bash. The Windows commands brace the plugin root as `${PLUGIN_ROOT}`, which Codex substitutes textually before the shell runs (`source.env` fold in `discovery.rs`); the unbraced `$PLUGIN_ROOT` the Unix commands use survives to the shell, and `cmd.exe` would pass it through literally. `|| exit /b 0` is the cmd.exe spelling of the Unix `|| true` — a marker is decoration, and a nonzero exit is what raises the banner. `test_codex_windows_hook_commands_set_the_marker` runs the real commands the way Codex spawns them, on the Windows leg of CI. `SessionEnd` carries `timeout: 3` because that is Codex's ceiling for the event (`SESSION_END_MAX_TIMEOUT_SEC` in `codex-rs/hooks/src/events/session_end.rs`; omitting the key takes the 1s default, and a larger value is clamped with a warning), and a hook that exceeds it is reported as an error — the same "Hook failed" banner — so the longer Windows chain has no more budget to ask for.
+
+The events (Codex's `HookEventsToml` vocabulary, verified against `codex-rs/config/src/hook_config.rs`):
+- `UserPromptSubmit` → 🤖 (working)
+- `PermissionRequest`, `Stop` → 💬 (waiting for input)
+- `SessionEnd` → clears the marker
+
+`Stop` fires at turn-end, so 🤖 returns to 💬 when a turn completes. `SessionEnd` clears the marker when the main thread ends.
+
+Codex and Gemini marker commands still resolve from the hook process's cwd. When either harness exposes a stable session project directory, pass that directory to Worktrunk with global `-C`, as Claude does with `$CLAUDE_PROJECT_DIR`.
+
+### Accepted tradeoff: shared `skills/` exposes `wt-switch-create`
+
+Codex's mirrored `skills/` and Gemini's `${extensionPath}/skills/` both carry the entire skill set, including `wt-switch-create`, which depends on Claude session-cwd switching (`EnterWorktree`) that neither provides. Accepted: a tool loading a skill it can't act on is harmless, and a single authored `skills/` keeps the `worktrunk` skill single-source across all three tools and the docs sync. Don't add per-tool skills subtrees to exclude it.
diff --git a/plugins/worktrunk/CLAUDE.md b/plugins/worktrunk/CLAUDE.md
index 9ca8ceecf..43c994c2d 100644
--- a/plugins/worktrunk/CLAUDE.md
+++ b/plugins/worktrunk/CLAUDE.md
@@ -1,167 +1 @@
-# Worktrunk Plugin Guidelines (Claude Code + Codex)
-
-## Directory Layout
-
-This directory (`plugins/worktrunk/`) is the Claude Code + Codex payload. Each
-tool hardcodes its loader path with no fallback, so the repo root carries one
-pointer per tool: Claude's and Codex's both `source → ./plugins/worktrunk`,
-while Gemini resolves its extension at the repo root itself; Gemini's hooks
-call the canonical `hooks/wt.sh` below.
-
-```
-worktrunk/ ← repo root = marketplace root
-├── .claude-plugin/marketplace.json ← Claude pointer (source → ./plugins/worktrunk)
-├── .agents/plugins/marketplace.json← Codex pointer (source → ./plugins/worktrunk)
-├── .claude/skills/ ← authored repo-local maintainer skills
-├── .agents/skills → ../.claude/skills
-│ Codex repo-skill pointer
-├── gemini-extension.json ← Gemini manifest (extensionPath = repo root)
-├── hooks/hooks.json ← Gemini activity hooks (call the wt.sh below)
-├── skills/ ← real dir; Gemini reads ${extensionPath}/skills directly
-└── plugins/worktrunk/ ← plugin root (Claude + Codex resolve source here)
- ├── .claude-plugin/plugin.json ← Claude manifest (metadata only — NO `hooks`
- │ or `skills` keys; components load by
- │ convention, see below)
- ├── .codex-plugin/plugin.json ← Codex manifest (Codex's required wrapper)
- ├── hooks/hooks.json ← Claude activity + WorktreeCreate/Remove hooks,
- │ discovered by convention at this exact path
- │ (#3417; Codex is kept off it by its inline
- │ manifest, #3362)
- ├── hooks/wt.sh ← canonical hook shim; Claude reaches it via
- │ $CLAUDE_PLUGIN_ROOT, Codex via $PLUGIN_ROOT,
- │ Gemini via
- │ ${extensionPath}/plugins/worktrunk/hooks/wt.sh
- ├── hooks/wt.cmd ← finds Git Bash for cmd.exe, which is what runs
- │ a Codex `commandWindows`, then runs wt.sh (#4007)
- ├── skills/ ← generated real-file mirror of repo-root
- │ skills/ (test_docs_are_in_sync; never
- │ hand-edit) — real files because Codex's
- │ installer drops symlinks, see below
- ├── CLAUDE.md / README.md
- └── (Codex activity hooks live *inline* in .codex-plugin/plugin.json's
- `hooks` key — see Known Limitations below)
-```
-
-The repo-local maintainer skills are separate from the distributed plugin
-skills. `.claude/skills/` is their authored home, and the relative
-`.agents/skills` symlink lets Codex discover the same files. On Windows
-checkouts with `core.symlinks=false`, Git materializes the link as a plain file
-and Codex loads none of these repo-local skills. This limitation is accepted;
-installed plugins use the real-file mirror below and are unaffected.
-
-Path resolution differs by tool, all verified end-to-end against the real CLIs:
-
-- **Claude** (claude-cli 2.1.207): `.claude-plugin/marketplace.json` `source:
- "./plugins/worktrunk"`. Claude reads
- `plugins/worktrunk/.claude-plugin/plugin.json` — the same wrapper convention
- as the marketplace root, and the only manifest location `claude plugin
- validate` accepts (a bare `plugin.json` at the plugin root loads through an
- undocumented fallback but fails validation). The manifest deliberately
- carries no `version` field: installs pin the marketplace git SHA, so a
- semver here would be a second version to maintain with nothing consuming
- it — `claude plugin validate`'s missing-`version` warning is accepted.
- Components load by **convention**, and the manifest must not name them:
- - Hooks are discovered at `hooks/hooks.json`. The loader does not honor the
- string-path `hooks` manifest override for plugin loads, so a renamed file
- silently loads nothing (#3417) and a `hooks` key pointing at the
- conventional path is dead config that can only mask a mislocated file.
- - Skills are auto-discovered by scanning `skills/` for `<dir>/SKILL.md`; a
- `skills` manifest array only *adds* directories to that scan, so listing
- the defaults is redundant.
-
- `$CLAUDE_PLUGIN_ROOT` is the plugin root.
-- **Codex** (codex-cli 0.144.1): `.agents/plugins/marketplace.json` `source`
- object `{ "source": "local", "path": "./plugins/worktrunk" }`. Codex reads
- `plugins/worktrunk/.codex-plugin/plugin.json`. Skills load by convention —
- with no `skills` manifest key, Codex scans `<plugin-root>/skills/`; an
- explicit `"skills": "./skills/"` names the same directory, so the manifest
- carries no `skills` key. The scanned tree is the real-file mirror ("Plugin
- skills are a generated mirror" below).
-- **Gemini**: `gemini-extension.json` at the repo root; `${extensionPath}` is
- the repo root, so `${extensionPath}/skills/` is the repo-root `skills/`
- directly and `hooks/hooks.json` (repo root) calls the canonical shim at
- `${extensionPath}/plugins/worktrunk/hooks/wt.sh`. No symlink or copy.
-
-All three tools pick up the whole `skills/` set — Gemini reads the repo-root
-directory, Claude and Codex ship the plugin mirror — so a new repo-root skill
-ships everywhere once `test_docs_are_in_sync` regenerates the mirror, provided
-its directory contains a `SKILL.md` (`test_plugin_layout_is_consolidated`
-enforces that; a directory without one is silently ignored). Claude-only
-skills reach the other tools too (accepted tradeoff — see Known Limitations
-below).
-
-### Plugin skills are a generated mirror
-
-`plugins/worktrunk/skills/` is a real-file mirror of the authored repo-root
-`skills/`, regenerated — symlinks dereferenced, stale files deleted — by the
-`sync_plugin_skills_mirror` stage of `test_docs_are_in_sync`; never hand-edit
-it. Repo-root `skills/` stays the authored home: Gemini reads it directly and
-the docs sync writes into it.
-
-The mirror holds real files because of how the plugin ships, verified
-end-to-end against codex-cli 0.144.1 (scratch marketplaces through
-`codex plugin marketplace add` + `codex plugin add`, skill inventory read with
-`codex debug prompt-input`):
-
-- `codex plugin add` copies the plugin into
- `$CODEX_HOME/plugins/cache/<marketplace>/<plugin>/<version>` with a copier
- that handles only regular files and directories, silently skipping symlink
- entries (`copy_dir_recursive` in `codex-rs/core-plugins/src/store.rs`), and
- sessions load from that cache copy. A symlink anywhere in the tree — a
- top-level `skills` link or one nested under `reference/` — ships no
- content. No manifest value can bridge it: manifest paths must stay within
- the plugin root (`..` and absolute paths are rejected,
- `resolve_manifest_path` in `codex-rs/core-plugins/src/manifest.rs`).
-- Codex's convention scan (`default_skill_roots`, the empty-`skills` branch of
- `plugin_skill_roots` in `codex-rs/core-plugins/src/loader.rs`) reads the
- mirror like any directory.
-- Claude's installer dereferences symlinks, so a symlinked `skills/` worked
- for Claude; the mirror serves it identically. A symlink also materializes as
- a plain text file on Windows checkouts, which shipped no skills from a
- Windows clone to Claude or Codex.
-
-`test_plugin_layout_is_consolidated` pins the no-symlinks invariant;
-`test_docs_are_in_sync` pins content equality with repo-root `skills/`.
-
-## Known Limitations
-
-### Status stays on the launch worktree (Claude)
-
-Claude marker hooks resolve through `-C "$CLAUDE_PROJECT_DIR"`. `EnterWorktree` does not change that directory, so the marker stays on the launch worktree for the session. Sessions launched outside a repository have no activity marker.
-
-### Status persists after user interrupt (Claude)
-
-The Claude hooks track activity via git config (`worktrunk.state.{branch}.marker`):
-- `UserPromptSubmit` → 🤖 (working)
-- `Notification`, `PreToolUse`(`AskUserQuestion`), `PermissionRequest`, `Stop` → 💬 (waiting for input)
-- `SessionEnd` → clears status
-
-An `EnterWorktree` that `wt config plugins claude approve-enter-worktree` approves shows no dialog, so it leaves the marker alone; the approval and the marker share one `PermissionRequest` command because Claude Code runs matching hooks in parallel (skills/wt-switch-create/rationale.md, "The confirmation hook").
-
-The 💬 transitions overlap deliberately: `Notification` covers the documented permission/idle path, but on platforms where it doesn't fire (VS Code extension, Windows CLI) `PermissionRequest` and `Stop` still mark the wait; `PreToolUse`(`AskUserQuestion`) catches the built-in question picker, which fires no `Notification` on any platform ([claude-code#13024](https://github.com/anthropics/claude-code/issues/13024)). There is currently no transition back to 🤖 once a turn-end/permission marker is set except a fresh `UserPromptSubmit`, so 💬 can persist into resumed work after a permission grant (the original symptom in [#2916](https://github.com/max-sixty/worktrunk/issues/2916)).
-
-**Problem**: If the user interrupts Claude Code (Escape/Ctrl+C), the 🤖 status persists because there's no `UserInterrupt` hook. The `Stop` hook explicitly does not fire on user interrupt.
-
-**Tracking**: [claude-code#9516](https://github.com/anthropics/claude-code/issues/9516)
-
-### Codex activity hooks
-
-Claude's hooks live in the standalone `hooks/hooks.json` its loader discovers by convention (see Directory Layout above); the Codex manifest carries `hooks` as an **inline object**, `{ "hooks": { … } }`, embedding a Codex-tailored hooks file directly. The inline form is deliberate:
-
-- **Why inline for Codex, not a path or an absent key.** Claude and Codex share one payload dir, and Codex *also* auto-discovers `hooks/hooks.json` at the plugin root by convention (`DEFAULT_HOOKS_CONFIG_FILE`, the `None` branch of `load_plugin_hooks`) — which once surfaced Worktrunk's *Claude* events in a Codex session ([#3362](https://github.com/max-sixty/worktrunk/issues/3362)). The Codex manifest carries its own hooks **inline**, taking Codex's `Some(Inline)` branch (`resolve_manifest_hooks` in `codex-rs/core-plugins/src/manifest.rs`), which **overrides** convention discovery. The inline object is both the functional definition of the Codex-native events and the thing that keeps Codex off the shared `hooks/hooks.json`, so the two toolchains coexist on one file: Claude discovers it, Codex ignores it. (Scoping via the filename instead — `hooks/claude-hooks.json` — breaks Claude's discovery, [#3417](https://github.com/max-sixty/worktrunk/issues/3417); the inline override makes it unnecessary.)
-- **Why `$PLUGIN_ROOT`, not `$CLAUDE_PLUGIN_ROOT`.** Codex exports both to hook commands (`PLUGIN_ROOT` native, `CLAUDE_PLUGIN_ROOT` as an OOTB-compat alias — `codex-rs/hooks/src/engine/discovery.rs`). The Codex file uses the native `$PLUGIN_ROOT` so nothing Claude-branded appears in a Codex session.
-
-- **Why every hook also carries `commandWindows`.** Codex runs a hook `command` through the platform shell — `/bin/sh -lc` on Unix, `cmd.exe /C` on Windows (`default_shell_command` in `codex-rs/hooks/src/engine/command_runner.rs`). Under `cmd.exe` the leading bare `bash` resolves through the Windows PATH to `System32\bash.exe`, the WSL launcher rather than Git Bash, which in a sandboxed session fails outright (`Bash/Service/CreateInstance/E_ACCESSDENIED`) and turns every prompt, permission, stop, and session-end event into a "Hook failed" banner ([#4007](https://github.com/max-sixty/worktrunk/issues/4007)). Only the bare *name* is the problem — Git for Windows is a requirement either way — so the per-handler `commandWindows` key, which **replaces** `command` on Windows (`command_windows.unwrap_or(command)` in `codex-rs/hooks/src/engine/discovery.rs`), calls `hooks/wt.cmd`: a shim that resolves `bash.exe` by path the way `find_git_bash` does in `src/shell_exec.rs` (derived from `where git.exe`, then the system-wide and per-user install defaults, `Git\bin\bash.exe` before `Git\usr\bin\bash.exe` because the former is the wrapper that puts `uname` and friends on PATH for a caller outside Git Bash) and then runs the same `wt.sh` every other integration goes through, so worktrunk's own resolution order lives in one script rather than in two languages. The `git.exe` lookup uses `where`'s `$PATH:` prefix and runs the absolute path it returns: an unscoped `where`, like cmd's own bare-name lookup, searches the current directory first, which for a hook is the user's project — so a `git.exe` committed to a repo would choose the bash every event runs (`test_shim_ignores_a_git_in_the_current_directory`). `where` itself is spelled `%SystemRoot%\System32\where.exe` for the same reason — it is `System32\where.exe` rather than a cmd built-in, so cmd resolves that bare name from the current directory too (`test_shim_ignores_a_where_in_the_current_directory`). Both of those see only the *wrong* bash; a lookup that finds nothing falls through to `%ProgramFiles%\Git`, which resolves on any Windows box, so `test_shim_derives_bash_from_the_git_on_path` points both install-default variables at an empty directory and leaves the derive branch as the only route to a bash. The Windows commands brace the plugin root as `${PLUGIN_ROOT}`, which Codex substitutes textually before the shell runs (`source.env` fold in `discovery.rs`); the unbraced `$PLUGIN_ROOT` the Unix commands use survives to the shell, and `cmd.exe` would pass it through literally. `|| exit /b 0` is the cmd.exe spelling of the Unix `|| true` — a marker is decoration, and a nonzero exit is what raises the banner. `test_codex_windows_hook_commands_set_the_marker` runs the real commands the way Codex spawns them, on the Windows leg of CI. `SessionEnd` carries `timeout: 3` because that is Codex's ceiling for the event (`SESSION_END_MAX_TIMEOUT_SEC` in `codex-rs/hooks/src/events/session_end.rs`; omitting the key takes the 1s default, and a larger value is clamped with a warning), and a hook that exceeds it is reported as an error — the same "Hook failed" banner — so the longer Windows chain has no more budget to ask for.
-
-The events (Codex's `HookEventsToml` vocabulary, verified against `codex-rs/config/src/hook_config.rs`):
-- `UserPromptSubmit` → 🤖 (working)
-- `PermissionRequest`, `Stop` → 💬 (waiting for input)
-- `SessionEnd` → clears the marker
-
-`Stop` fires at turn-end, so 🤖 returns to 💬 when a turn completes. `SessionEnd` clears the marker when the main thread ends.
-
-Codex and Gemini marker commands still resolve from the hook process's cwd. When either harness exposes a stable session project directory, pass that directory to Worktrunk with global `-C`, as Claude does with `$CLAUDE_PROJECT_DIR`.
-
-### Accepted tradeoff: shared `skills/` exposes `wt-switch-create`
-
-Codex's mirrored `skills/` and Gemini's `${extensionPath}/skills/` both carry the entire skill set, including `wt-switch-create`, which depends on Claude session-cwd switching (`EnterWorktree`) that neither provides. Accepted: a tool loading a skill it can't act on is harmless, and a single authored `skills/` keeps the `worktrunk` skill single-source across all three tools and the docs sync. Don't add per-tool skills subtrees to exclude it.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
index 160968f61..6e9a8d2b1 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
@@ -460,7 +460,7 @@ This lets one agent session hand off work to another that runs in the background
The [worktrunk skill](https://worktrunk.dev/claude-code/) includes guidance for Claude Code (and other agent CLIs that load it) to execute this pattern. To enable it, request it explicitly ("spawn a parallel worktree for...") or add to your project instructions (`CLAUDE.md` or `AGENTS.md`):
-```markdown title="CLAUDE.md"
+```markdown title="AGENTS.md"
When I ask you to spawn parallel worktrees, use the agent handoff pattern
from the worktrunk skill.
```
diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.md
index 160968f61..6e9a8d2b1 100644
--- a/skills/worktrunk/reference/tips-patterns.md
+++ b/skills/worktrunk/reference/tips-patterns.md
@@ -460,7 +460,7 @@ This lets one agent session hand off work to another that runs in the background
The [worktrunk skill](https://worktrunk.dev/claude-code/) includes guidance for Claude Code (and other agent CLIs that load it) to execute this pattern. To enable it, request it explicitly ("spawn a parallel worktree for...") or add to your project instructions (`CLAUDE.md` or `AGENTS.md`):
-```markdown title="CLAUDE.md"
+```markdown title="AGENTS.md"
When I ask you to spawn parallel worktrees, use the agent handoff pattern
from the worktrunk skill.
```
diff --git a/src/commands/AGENTS.md b/src/commands/AGENTS.md
new file mode 100644
index 000000000..b6d62fc14
--- /dev/null
+++ b/src/commands/AGENTS.md
@@ -0,0 +1,244 @@
+# Debugging Interactive Terminal Commands
+
+When debugging TUI commands like `wt switch` (interactive picker), use the `tmux-cli` skill (preferred) or MCP's `node-terminal` tools to test interactively.
+
+## Debugging Workflow
+
+### 1. Create Test Environment
+
+```bash
+cargo run -p wt-perf -- setup generated 5 2 0 --path target/wt-picker-test
+```
+
+This creates a varied repository with linked worktrees and branch-only rows for
+the picker.
+
+### 2. Test Interactively
+
+#### Option A: tmux-cli skill (preferred, if available)
+
+Load the `tmux-cli` skill, then use the `tmux-cli` tool. Install if needed: `uv tool install claude-code-tools` (requires tmux).
+
+```bash
+# Launch shell in test repo
+pane=$(tmux-cli launch "zsh")
+tmux-cli send "cd target/wt-picker-test" --pane=$pane
+tmux-cli wait_idle --pane=$pane
+
+# Run with debug logging
+tmux-cli send "RUST_LOG=worktrunk=debug cargo run --quiet -- switch 2> debug.log" --pane=$pane
+tmux-cli wait_idle --pane=$pane
+
+# Test interaction (e.g., select option 3)
+tmux-cli send "3" --pane=$pane
+tmux-cli wait_idle --pane=$pane
+
+# Capture output
+tmux-cli capture --pane=$pane
+```
+
+#### Option B: MCP node-terminal
+
+MCP terminals use pseudo-TTY, not real terminals. If tests pass in MCP but users report issues, the bug is likely environment-specific. Always test on the actual problematic repository.
+
+```typescript
+// Create terminal and navigate to test repo
+mcp__node-terminal__terminal_create({ sessionId: "test" })
+mcp__node-terminal__terminal_write({ sessionId: "test", input: "cd target/wt-picker-test" })
+mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
+
+// Run with debug logging
+mcp__node-terminal__terminal_write({
+ sessionId: "test",
+ input: "RUST_LOG=worktrunk=debug cargo run --quiet -- switch 2> debug.log"
+})
+mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
+
+// Test the interaction
+mcp__node-terminal__terminal_write({ sessionId: "test", input: "3" })
+mcp__node-terminal__terminal_read({ sessionId: "test" })
+```
+
+### 3. Analyze Logs
+
+```bash
+tail -100 debug.log | grep -E "error|hang|stuck"
+```
+
+## Important Flags
+
+- **`-C <path>`**: Set working directory (alternative to `cd`)
+- **`--source`**: Use local source (only needed with installed `wt`, not with `cargo run`)
+
+```bash
+# Testing with cargo run (already uses local source):
+cargo run --quiet -- -C /path/to/repo switch
+
+# Testing with installed wt:
+wt --source -C /path/to/repo switch
+```
+
+## Adding a CLI Command
+
+1. Add the subcommand to the `Cli` enum in `src/cli/mod.rs`.
+2. Implement it in `src/commands/` (e.g. `src/commands/mycommand.rs`).
+3. Add an `after_long_help` attribute — it is the source of truth for `docs/src/content/docs/{command}.md`.
+4. Run `cargo test --test integration test_docs_are_in_sync`. Editing help text also changes the rendered `--help` snapshots, which that test leaves untouched — regenerate them with `cargo insta test --accept --test integration -- test_help` (or run the pre-merge hook, which does both).
+
+All stdout goes through anstream: `worktrunk::styling::println` for anything a person reads, and `crate::output::print_json` for a `--format=json` answer — every surface but `wt switch --format=json`, which emits its single result as one compact line. anstream's macros drop a `BrokenPipe` write error where std's panic, so `wt … | head -3` never exits 101.
+
+Color resolves in exactly one place, anstream's `AutoStream::choice`: the process-global `ColorChoice` first, then the tty check with `NO_COLOR` / `CLICOLOR_FORCE`. A command whose stdout is a renderer's payload says so once at the top of its `run` with `ColorChoice::Always.write_global()`, then prints normally — the statusline, which a shell prompt or Claude Code captures and re-renders, and `--help-page`, whose escapes the docs pipeline turns into HTML spans (`--plain` writes `Never`, for portable markdown). Neither consumer is ever a tty, so without the global their escapes would be stripped every time.
+
+`wt list`'s progressive table applies that choice itself rather than writing through an anstream stream, because a strip would eat its cursor-control CSI along with the color; it reads the resolved choice from `AutoStream::choice`, so the single resolution point still holds. The test suite forces `CLICOLOR_FORCE=1`, so `test_color_follows_the_consumer` in `tests/integration_tests/output_system_guard.rs` pins the unforced behavior.
+
+## Branch Argument Conventions
+
+Every branch-name argument carries a completer (shell completion) and the
+`non_empty_branch` value parser (rejects `--branch=` at the parse boundary, so
+an empty value surfaces as a clear usage error instead of a garbled
+`Branch has no worktree`):
+
+```rust
+/// Target branch (defaults to current)
+#[arg(long, add = crate::completion::branch_value_completer(), value_parser = crate::cli::non_empty_branch)]
+branch: Option<String>,
+```
+
+**Available completers:**
+- `branch_value_completer()` - Completes with branch names
+- `worktree_branch_completer()` - Completes with branch names, suppresses when --create flag present
+- `worktree_only_completer()` - Completes with branches that have a worktree
+- `local_branches_completer()` - Completes with local branch names, excludes remote-only
+
+Pick the completer that fits the argument; `value_parser = crate::cli::non_empty_branch` is the same on all of them.
+
+## CLI Flag Descriptions
+
+Keep the first line of flag and argument descriptions brief—aim for 3-6 words. Use parenthetical defaults sparingly, only when the default isn't obvious from context.
+
+**Good examples:**
+- `/// Skip approval prompts`
+- `/// Show CI status and LLM summaries`
+- `/// Target branch (defaults to default branch)`
+
+**Bad examples (too verbose):**
+- `/// Auto-approve project commands without saving approvals.`
+- `/// Show CI status, conflict detection, and complete diff statistics`
+
+The help text should be scannable. Users reading `wt switch --help` need to quickly understand what each flag does without parsing long sentences.
+
+## `--dry-run` and `-v`
+
+`--dry-run` previews the mutation a command would perform without performing it. A command that changes nothing has nothing to preview, so it carries no `--dry-run`; its inspection output belongs to `-v` instead. `wt step eval` expands a template and prints the result, so it lists the available variables under `-v`, not behind a `--dry-run`.
+
+The flags answer different questions: `--dry-run` is "what would this change?", `-v` is "what is this doing?" (template variables, expansion, echoed `$ git …` subprocesses).
+
+A `--dry-run` preview is the command's answer, so it prints to stdout (pageable when long), on the same stream as the command's `--format=json` form; progress and status stay on stderr. Both flags render in the gutter house style: `format_heading` for sections, `format_with_gutter` / `format_bash_with_gutter` for quoted blocks, `info_message` / `hint_message` for status lines. The `/writing-user-outputs` skill covers the helpers, the full stdout/stderr split, and when to page.
+
+## CLI Help Text Placement
+
+Help text has three levels:
+
+1. **`about`** (single-line doc comment) → Short title after command name
+2. **`long_about`** (multi-line doc comment, 1-2 sentences) → Brief summary before options
+3. **`after_long_help`** → Examples and detailed docs after options
+
+**Pattern for complex commands:**
+
+```rust
+/// Merge worktree into target branch
+///
+/// Commits, squashes, rebases, runs hooks, merges to target, and removes the worktree.
+#[command(
+ after_long_help = r#"## Examples
+
+```console
+wt merge
+```
+"#
+)]
+Merge { ... }
+```
+
+This renders as:
+```
+wt merge - Merge worktree into target branch
+
+Commits, squashes, rebases, runs hooks, merges to target, and removes the worktree.
+
+Usage: wt merge [OPTIONS] [TARGET]
+
+Options:
+ ...
+
+## Examples
+...
+```
+
+**Pattern for simple commands:**
+
+```rust
+/// Rebase onto target
+Rebase { ... }
+```
+
+No `long_about` or `after_long_help` needed when the short description is self-explanatory.
+
+**When to use `long_about`:** Add a 1-2 sentence summary when the short description doesn't convey the full behavior (e.g., `wt merge` does more than just "merge").
+
+**Why:** Users see context before options for complex commands, but options stay near the top. Examples and detailed docs follow after.
+
+## Command Documentation Guidelines
+
+When writing or updating command docs in `docs/src/content/docs/`, follow this structure and these principles. Load the `documentation` skill for additional guidance.
+
+### Structure
+
+Each command page should follow this order:
+
+1. **Intro paragraph** — One or two sentences: what the command does and when to use it. Integrate key behavioral distinctions (e.g., "Switching to an existing worktree is just a directory change. With `--create`, hooks run.")
+2. **Examples** — Common use cases with brief labels, immediately after intro
+3. **Feature sections** — Deeper explanation of major features (e.g., "Creating worktrees", "Shortcuts")
+4. **Hooks** — Brief summary with link to `/hook/` for details
+5. **Technical details** — Implementation details like argument resolution, pushed to the bottom
+6. **Command reference** — Auto-generated from `--help-page`, always last
+
+### Writing Style
+
+- **Indicative mood over imperative** — "The `--create` flag creates..." not "Use `--create` to create..."
+- **Spaced em-dashes** — "instant — no stashing" not "instant—no stashing"
+- **No second person** — Describe behavior, don't address the reader
+- **Concrete examples** — Real commands, actual output, specific scenarios
+- **Link to dedicated pages** — Don't duplicate content from `/hook/`, `/configuration/`, etc.
+
+### What to Avoid
+
+- AI-slop: series of headings with 3-5 bullets each
+- Redundant content that duplicates other pages
+- Technical details at the top (push Operation/Resolution sections down)
+- Wrapper sections that just contain one subsection (remove "Operation" if it only contains "How Arguments Are Resolved")
+- Presuming user intent — describe what the command does, not why users run it
+
+### Example: Don't Presume Intent
+
+```markdown
+# Bad — presumes why users run the command
+See which worktrees need attention.
+
+# Good — describes what it does
+Show all worktrees with their status.
+```
+
+Users run `wt list` for many reasons: checking status, finding a branch, remembering what they were working on, scripting. The intro should describe the command's behavior, not assume the user's goal.
+
+### Example: Good Intro
+
+```markdown
+Navigate between worktrees or create new ones. Switching to an existing
+worktree is just a directory change. With `--create`, a new branch and
+worktree are created, and hooks run.
+```
+
+### Updating These Guidelines
+
+As command docs are improved, update this section to capture new patterns that emerge.
diff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.md
index b6d62fc14..43c994c2d 100644
--- a/src/commands/CLAUDE.md
+++ b/src/commands/CLAUDE.md
@@ -1,244 +1 @@
-# Debugging Interactive Terminal Commands
-
-When debugging TUI commands like `wt switch` (interactive picker), use the `tmux-cli` skill (preferred) or MCP's `node-terminal` tools to test interactively.
-
-## Debugging Workflow
-
-### 1. Create Test Environment
-
-```bash
-cargo run -p wt-perf -- setup generated 5 2 0 --path target/wt-picker-test
-```
-
-This creates a varied repository with linked worktrees and branch-only rows for
-the picker.
-
-### 2. Test Interactively
-
-#### Option A: tmux-cli skill (preferred, if available)
-
-Load the `tmux-cli` skill, then use the `tmux-cli` tool. Install if needed: `uv tool install claude-code-tools` (requires tmux).
-
-```bash
-# Launch shell in test repo
-pane=$(tmux-cli launch "zsh")
-tmux-cli send "cd target/wt-picker-test" --pane=$pane
-tmux-cli wait_idle --pane=$pane
-
-# Run with debug logging
-tmux-cli send "RUST_LOG=worktrunk=debug cargo run --quiet -- switch 2> debug.log" --pane=$pane
-tmux-cli wait_idle --pane=$pane
-
-# Test interaction (e.g., select option 3)
-tmux-cli send "3" --pane=$pane
-tmux-cli wait_idle --pane=$pane
-
-# Capture output
-tmux-cli capture --pane=$pane
-```
-
-#### Option B: MCP node-terminal
-
-MCP terminals use pseudo-TTY, not real terminals. If tests pass in MCP but users report issues, the bug is likely environment-specific. Always test on the actual problematic repository.
-
-```typescript
-// Create terminal and navigate to test repo
-mcp__node-terminal__terminal_create({ sessionId: "test" })
-mcp__node-terminal__terminal_write({ sessionId: "test", input: "cd target/wt-picker-test" })
-mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
-
-// Run with debug logging
-mcp__node-terminal__terminal_write({
- sessionId: "test",
- input: "RUST_LOG=worktrunk=debug cargo run --quiet -- switch 2> debug.log"
-})
-mcp__node-terminal__terminal_send_key({ sessionId: "test", key: "enter" })
-
-// Test the interaction
-mcp__node-terminal__terminal_write({ sessionId: "test", input: "3" })
-mcp__node-terminal__terminal_read({ sessionId: "test" })
-```
-
-### 3. Analyze Logs
-
-```bash
-tail -100 debug.log | grep -E "error|hang|stuck"
-```
-
-## Important Flags
-
-- **`-C <path>`**: Set working directory (alternative to `cd`)
-- **`--source`**: Use local source (only needed with installed `wt`, not with `cargo run`)
-
-```bash
-# Testing with cargo run (already uses local source):
-cargo run --quiet -- -C /path/to/repo switch
-
-# Testing with installed wt:
-wt --source -C /path/to/repo switch
-```
-
-## Adding a CLI Command
-
-1. Add the subcommand to the `Cli` enum in `src/cli/mod.rs`.
-2. Implement it in `src/commands/` (e.g. `src/commands/mycommand.rs`).
-3. Add an `after_long_help` attribute — it is the source of truth for `docs/src/content/docs/{command}.md`.
-4. Run `cargo test --test integration test_docs_are_in_sync`. Editing help text also changes the rendered `--help` snapshots, which that test leaves untouched — regenerate them with `cargo insta test --accept --test integration -- test_help` (or run the pre-merge hook, which does both).
-
-All stdout goes through anstream: `worktrunk::styling::println` for anything a person reads, and `crate::output::print_json` for a `--format=json` answer — every surface but `wt switch --format=json`, which emits its single result as one compact line. anstream's macros drop a `BrokenPipe` write error where std's panic, so `wt … | head -3` never exits 101.
-
-Color resolves in exactly one place, anstream's `AutoStream::choice`: the process-global `ColorChoice` first, then the tty check with `NO_COLOR` / `CLICOLOR_FORCE`. A command whose stdout is a renderer's payload says so once at the top of its `run` with `ColorChoice::Always.write_global()`, then prints normally — the statusline, which a shell prompt or Claude Code captures and re-renders, and `--help-page`, whose escapes the docs pipeline turns into HTML spans (`--plain` writes `Never`, for portable markdown). Neither consumer is ever a tty, so without the global their escapes would be stripped every time.
-
-`wt list`'s progressive table applies that choice itself rather than writing through an anstream stream, because a strip would eat its cursor-control CSI along with the color; it reads the resolved choice from `AutoStream::choice`, so the single resolution point still holds. The test suite forces `CLICOLOR_FORCE=1`, so `test_color_follows_the_consumer` in `tests/integration_tests/output_system_guard.rs` pins the unforced behavior.
-
-## Branch Argument Conventions
-
-Every branch-name argument carries a completer (shell completion) and the
-`non_empty_branch` value parser (rejects `--branch=` at the parse boundary, so
-an empty value surfaces as a clear usage error instead of a garbled
-`Branch has no worktree`):
-
-```rust
-/// Target branch (defaults to current)
-#[arg(long, add = crate::completion::branch_value_completer(), value_parser = crate::cli::non_empty_branch)]
-branch: Option<String>,
-```
-
-**Available completers:**
-- `branch_value_completer()` - Completes with branch names
-- `worktree_branch_completer()` - Completes with branch names, suppresses when --create flag present
-- `worktree_only_completer()` - Completes with branches that have a worktree
-- `local_branches_completer()` - Completes with local branch names, excludes remote-only
-
-Pick the completer that fits the argument; `value_parser = crate::cli::non_empty_branch` is the same on all of them.
-
-## CLI Flag Descriptions
-
-Keep the first line of flag and argument descriptions brief—aim for 3-6 words. Use parenthetical defaults sparingly, only when the default isn't obvious from context.
-
-**Good examples:**
-- `/// Skip approval prompts`
-- `/// Show CI status and LLM summaries`
-- `/// Target branch (defaults to default branch)`
-
-**Bad examples (too verbose):**
-- `/// Auto-approve project commands without saving approvals.`
-- `/// Show CI status, conflict detection, and complete diff statistics`
-
-The help text should be scannable. Users reading `wt switch --help` need to quickly understand what each flag does without parsing long sentences.
-
-## `--dry-run` and `-v`
-
-`--dry-run` previews the mutation a command would perform without performing it. A command that changes nothing has nothing to preview, so it carries no `--dry-run`; its inspection output belongs to `-v` instead. `wt step eval` expands a template and prints the result, so it lists the available variables under `-v`, not behind a `--dry-run`.
-
-The flags answer different questions: `--dry-run` is "what would this change?", `-v` is "what is this doing?" (template variables, expansion, echoed `$ git …` subprocesses).
-
-A `--dry-run` preview is the command's answer, so it prints to stdout (pageable when long), on the same stream as the command's `--format=json` form; progress and status stay on stderr. Both flags render in the gutter house style: `format_heading` for sections, `format_with_gutter` / `format_bash_with_gutter` for quoted blocks, `info_message` / `hint_message` for status lines. The `/writing-user-outputs` skill covers the helpers, the full stdout/stderr split, and when to page.
-
-## CLI Help Text Placement
-
-Help text has three levels:
-
-1. **`about`** (single-line doc comment) → Short title after command name
-2. **`long_about`** (multi-line doc comment, 1-2 sentences) → Brief summary before options
-3. **`after_long_help`** → Examples and detailed docs after options
-
-**Pattern for complex commands:**
-
-```rust
-/// Merge worktree into target branch
-///
-/// Commits, squashes, rebases, runs hooks, merges to target, and removes the worktree.
-#[command(
- after_long_help = r#"## Examples
-
-```console
-wt merge
-```
-"#
-)]
-Merge { ... }
-```
-
-This renders as:
-```
-wt merge - Merge worktree into target branch
-
-Commits, squashes, rebases, runs hooks, merges to target, and removes the worktree.
-
-Usage: wt merge [OPTIONS] [TARGET]
-
-Options:
- ...
-
-## Examples
-...
-```
-
-**Pattern for simple commands:**
-
-```rust
-/// Rebase onto target
-Rebase { ... }
-```
-
-No `long_about` or `after_long_help` needed when the short description is self-explanatory.
-
-**When to use `long_about`:** Add a 1-2 sentence summary when the short description doesn't convey the full behavior (e.g., `wt merge` does more than just "merge").
-
-**Why:** Users see context before options for complex commands, but options stay near the top. Examples and detailed docs follow after.
-
-## Command Documentation Guidelines
-
-When writing or updating command docs in `docs/src/content/docs/`, follow this structure and these principles. Load the `documentation` skill for additional guidance.
-
-### Structure
-
-Each command page should follow this order:
-
-1. **Intro paragraph** — One or two sentences: what the command does and when to use it. Integrate key behavioral distinctions (e.g., "Switching to an existing worktree is just a directory change. With `--create`, hooks run.")
-2. **Examples** — Common use cases with brief labels, immediately after intro
-3. **Feature sections** — Deeper explanation of major features (e.g., "Creating worktrees", "Shortcuts")
-4. **Hooks** — Brief summary with link to `/hook/` for details
-5. **Technical details** — Implementation details like argument resolution, pushed to the bottom
-6. **Command reference** — Auto-generated from `--help-page`, always last
-
-### Writing Style
-
-- **Indicative mood over imperative** — "The `--create` flag creates..." not "Use `--create` to create..."
-- **Spaced em-dashes** — "instant — no stashing" not "instant—no stashing"
-- **No second person** — Describe behavior, don't address the reader
-- **Concrete examples** — Real commands, actual output, specific scenarios
-- **Link to dedicated pages** — Don't duplicate content from `/hook/`, `/configuration/`, etc.
-
-### What to Avoid
-
-- AI-slop: series of headings with 3-5 bullets each
-- Redundant content that duplicates other pages
-- Technical details at the top (push Operation/Resolution sections down)
-- Wrapper sections that just contain one subsection (remove "Operation" if it only contains "How Arguments Are Resolved")
-- Presuming user intent — describe what the command does, not why users run it
-
-### Example: Don't Presume Intent
-
-```markdown
-# Bad — presumes why users run the command
-See which worktrees need attention.
-
-# Good — describes what it does
-Show all worktrees with their status.
-```
-
-Users run `wt list` for many reasons: checking status, finding a branch, remembering what they were working on, scripting. The intro should describe the command's behavior, not assume the user's goal.
-
-### Example: Good Intro
-
-```markdown
-Navigate between worktrees or create new ones. Switching to an existing
-worktree is just a directory change. With `--create`, a new branch and
-worktree are created, and hooks run.
-```
-
-### Updating These Guidelines
-
-As command docs are improved, update this section to capture new patterns that emerge.
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index e6cf653bf..f435465ad 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -669,7 +669,7 @@ pub fn alias_error_wrapper(alias_name: String) -> ErrorWrapper {
/// Signal-derived child exits bypass the wrapper and `failure_strategy`:
/// the error is returned as `Interrupted` (exiting `128 + signal`) so the
/// enclosing loop aborts. This enforces the project-wide Ctrl-C cancellation
-/// policy — see the "Signal Handling" section of the root `CLAUDE.md` for
+/// policy — see the "Signal Handling" section of the root `AGENTS.md` for
/// the rationale.
fn handle_command_error(
err: anyhow::Error,
diff --git a/src/commands/config/codex.rs b/src/commands/config/codex.rs
index cfb120d59..6b8f22cb9 100644
--- a/src/commands/config/codex.rs
+++ b/src/commands/config/codex.rs
@@ -43,7 +43,7 @@ pub fn handle_codex_install(yes: bool) -> Result<()> {
eprintln!("{}", success_message("Codex plugin installed"));
// The Codex plugin ships activity-marker hooks inline in its manifest
// (`hooks` key in .codex-plugin/plugin.json), using `Stop` to return
- // 🤖 → 💬 and `SessionEnd` to clear the marker. See CLAUDE.md → "Plugin
+ // 🤖 → 💬 and `SessionEnd` to clear the marker. See AGENTS.md → "Plugin
// Layout".
eprintln!(
"{}",
diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rs
index 21f0c3b5d..870f9af37 100644
--- a/src/commands/hook_plan.rs
+++ b/src/commands/hook_plan.rs
@@ -2,7 +2,7 @@
//!
//! # The invariant
//!
-//! `CLAUDE.md` → "Project Commands Run Only After Approval". Project-defined
+//! `AGENTS.md` → "Project Commands Run Only After Approval". Project-defined
//! hook commands are arbitrary code shipped in a repo the user may have just
//! cloned; they run only after the approval gate clears them.
//!
@@ -232,7 +232,7 @@ impl HookPlan {
/// Build an approved plan without prompting: project pipelines whose
/// commands are already approved survive, the rest are dropped (user
- /// pipelines always survive). Strictly the CLAUDE.md "consult the
+ /// pipelines always survive). Strictly the AGENTS.md "consult the
/// approval state read-only and run only the already-approved commands,
/// skipping the rest" rule. An absent `project_id` (unresolvable
/// identifier) drops every project pipeline — fail-closed, never run
diff --git a/src/commands/list/AGENTS.md b/src/commands/list/AGENTS.md
new file mode 100644
index 000000000..513a1eae2
--- /dev/null
+++ b/src/commands/list/AGENTS.md
@@ -0,0 +1,70 @@
+# List Command Architecture
+
+## Skeleton-First Rendering
+
+The `wt list` command uses skeleton-first rendering: a placeholder table appears
+immediately (~50ms), then cells fill in as data arrives. This gives users
+instant feedback even when git operations are slow.
+
+**The skeleton must render as fast as possible.** Every operation before the
+skeleton adds perceived latency. Users notice 50ms vs 150ms.
+
+## Rendering Phases
+
+### Phase 1: Pre-Skeleton
+
+Minimal operations before showing anything. Runs a **fixed number of git commands**
+(O(1), not O(N) per worktree) through batching. See `collect/mod.rs` module
+docstring for the exact command list and first-run behavior.
+
+### Phase 2: Skeleton Render
+
+The skeleton shows:
+- Branch names (known from worktree list)
+- Paths (known from worktree list)
+- Abbreviated commit hashes (git's `%h`, from the commit-details batch the
+ skeleton already waits on for sort order — see `collect/mod.rs`). This is
+ also a detached row's Branch cell, which has no branch name to show
+- Placeholder gutter symbols (`·`)
+- Loading indicators for computed columns
+
+### Phase 3: Post-Skeleton
+
+Everything else runs after the skeleton appears:
+- Previous branch lookup, integration target calculation
+- URL template expansion (parallelized)
+- All background tasks (status, diffs, CI, URL health checks)
+
+Results update cells progressively as they complete.
+
+## Adding New Features
+
+Default: defer to post-skeleton. Only add a pre-skeleton operation when the
+skeleton literally cannot render without the data. Current exceptions, all
+small local reads: column sizing (the CI column's cached width hint), custom
+`[list.custom-columns]` expansion (values come from the in-memory config snapshot and
+must be measured for layout), and the picker's CI cache prime (paints the column
+instantly; the live CiStatus task the picker runs refreshes each cell behind the
+first frame). Template expansion and other file I/O wait; new columns can render a
+placeholder until data arrives.
+
+## Benchmarking Skeleton Time
+
+```bash
+WORKTRUNK_SKELETON_ONLY=1 hyperfine 'wt list'
+```
+
+Measures pure skeleton latency. Target: <60ms.
+
+## Code Structure
+
+- `collect/` — orchestrates collection, manages pre/post-skeleton phases, task definitions and execution (see `collect/mod.rs` module docstring for phase details)
+- `render.rs` — row formatting, skeleton rows, cell rendering
+- `layout.rs` — column width calculation
+- `progressive_table.rs` — terminal rendering with in-place updates; reserves
+ blank rows below the table so the shell prompt printed after exit renders
+ into pre-scrolled rows instead of jerking the settled table up. It writes to
+ a raw stdout rather than an anstream stream, since a strip would eat its
+ cursor-control CSI, so it applies the color decision to content itself —
+ every row, header, and footer through `prepare`; the module docstring covers
+ the split
diff --git a/src/commands/list/CLAUDE.md b/src/commands/list/CLAUDE.md
index 513a1eae2..43c994c2d 100644
--- a/src/commands/list/CLAUDE.md
+++ b/src/commands/list/CLAUDE.md
@@ -1,70 +1 @@
-# List Command Architecture
-
-## Skeleton-First Rendering
-
-The `wt list` command uses skeleton-first rendering: a placeholder table appears
-immediately (~50ms), then cells fill in as data arrives. This gives users
-instant feedback even when git operations are slow.
-
-**The skeleton must render as fast as possible.** Every operation before the
-skeleton adds perceived latency. Users notice 50ms vs 150ms.
-
-## Rendering Phases
-
-### Phase 1: Pre-Skeleton
-
-Minimal operations before showing anything. Runs a **fixed number of git commands**
-(O(1), not O(N) per worktree) through batching. See `collect/mod.rs` module
-docstring for the exact command list and first-run behavior.
-
-### Phase 2: Skeleton Render
-
-The skeleton shows:
-- Branch names (known from worktree list)
-- Paths (known from worktree list)
-- Abbreviated commit hashes (git's `%h`, from the commit-details batch the
- skeleton already waits on for sort order — see `collect/mod.rs`). This is
- also a detached row's Branch cell, which has no branch name to show
-- Placeholder gutter symbols (`·`)
-- Loading indicators for computed columns
-
-### Phase 3: Post-Skeleton
-
-Everything else runs after the skeleton appears:
-- Previous branch lookup, integration target calculation
-- URL template expansion (parallelized)
-- All background tasks (status, diffs, CI, URL health checks)
-
-Results update cells progressively as they complete.
-
-## Adding New Features
-
-Default: defer to post-skeleton. Only add a pre-skeleton operation when the
-skeleton literally cannot render without the data. Current exceptions, all
-small local reads: column sizing (the CI column's cached width hint), custom
-`[list.custom-columns]` expansion (values come from the in-memory config snapshot and
-must be measured for layout), and the picker's CI cache prime (paints the column
-instantly; the live CiStatus task the picker runs refreshes each cell behind the
-first frame). Template expansion and other file I/O wait; new columns can render a
-placeholder until data arrives.
-
-## Benchmarking Skeleton Time
-
-```bash
-WORKTRUNK_SKELETON_ONLY=1 hyperfine 'wt list'
-```
-
-Measures pure skeleton latency. Target: <60ms.
-
-## Code Structure
-
-- `collect/` — orchestrates collection, manages pre/post-skeleton phases, task definitions and execution (see `collect/mod.rs` module docstring for phase details)
-- `render.rs` — row formatting, skeleton rows, cell rendering
-- `layout.rs` — column width calculation
-- `progressive_table.rs` — terminal rendering with in-place updates; reserves
- blank rows below the table so the shell prompt printed after exit renders
- into pre-scrolled rows instead of jerking the settled table up. It writes to
- a raw stdout rather than an anstream stream, since a strip would eat its
- cursor-control CSI, so it applies the color decision to content itself —
- every row, header, and footer through `prepare`; the module docstring covers
- the split
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 9f98137a2..855b6a87d 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -44,7 +44,7 @@
//! `worktrunk.default-branch` nor `refs/remotes/<remote>/HEAD` is set.
//! 100 ms – 2 s on the wire. The result persists to
//! `worktrunk.default-branch` so subsequent runs are a cache hit. This is
-//! worktrunk's one accepted wire-path exception — see CLAUDE.md →
+//! worktrunk's one accepted wire-path exception — see AGENTS.md →
//! "Network Access".
//!
//! ### #6 — the batched commit-details fork
@@ -188,7 +188,7 @@
//! Reproduce end-to-end via
//! `cargo bench --bench time_to_first_output -- list`; for a per-phase
//! breakdown, capture a trace and run the phase-duration SQL query from
-//! `benches/CLAUDE.md`:
+//! `benches/AGENTS.md`:
//!
//! ```bash
//! RUST_LOG=debug ./target/release/wt -C <repo> list --progressive \
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 362b991b5..fb28fc446 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -87,7 +87,7 @@
//! RUST_LOG=debug ./target/release/wt -C <repo> switch \
//! 2> >(cargo run -p wt-perf --release -q -- trace > trace.json)
//! # Open trace.json in Perfetto, or run the phase-duration SQL query
-//! # documented in benches/CLAUDE.md §"What's on the critical path?".
+//! # documented in benches/AGENTS.md §"What's on the critical path?".
//! ```
mod items;
@@ -1315,7 +1315,7 @@ impl CommandCollector for PickerCollector {
/// `post-remove` anchor). The picker can't prompt mid-render, so it runs the
/// removal's hooks only when they're already approved (e.g. from a prior
/// `wt remove` / `wt merge`) and skips them otherwise — unapproved project
-/// commands must never run. See CLAUDE.md → "Project Commands Run Only After
+/// commands must never run. See AGENTS.md → "Project Commands Run Only After
/// Approval".
fn approved_removal_plan(
repo: &Repository,
@@ -1775,7 +1775,7 @@ pub fn handle_picker(
// status (see `populate_from_cache`), then fetched live and streamed in — the
// same 30–60s-TTL cache plus live fetch as `wt list --full`. The picker's
// lifetime is bounded by the user, so a slow forge call never blocks anything
- // (see the "Network Access" notes in CLAUDE.md). The `pr` preview tab reads
+ // (see the "Network Access" notes in AGENTS.md). The `pr` preview tab reads
// the same live status. `--prs` rows carry their own number from the explicit
// `--prs` forge call.
diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rs
index cfcca4499..e04dc3ce7 100644
--- a/src/commands/picker/prs.rs
+++ b/src/commands/picker/prs.rs
@@ -495,7 +495,7 @@ fn listed_pr_row(
/// in-flight bookkeeping, so skim's UI thread never blocks and a row can't spawn
/// a duplicate fetch on every repaint. `COLLECT_POOL` bounds how many run at once,
/// and the picker's lifetime is user-bounded, so a slow forge call never blocks
-/// the command (see the "Network Access" notes in CLAUDE.md).
+/// the command (see the "Network Access" notes in AGENTS.md).
///
/// The comments fetch goes through [`spawn_comments_fetch`], the same entry point
/// a worktree row uses once its CI fetch surfaces a PR — so the two row types
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 6eb50a47b..8e0027165 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -487,7 +487,7 @@ fn spawn_detached_exec_windows(
/// `git worktree list`, and a classified orphan a `SIGTERM`→`SIGKILL` wait
/// bounded by `REAP_KILL_DEADLINE` — both flat in the daemon count too (see
/// the `internal-sweep` / `enumerate-fsmonitor-daemons` trace spans and
-/// benches/CLAUDE.md § Recording `wt remove` / `wt step prune` staging).
+/// benches/AGENTS.md § Recording `wt remove` / `wt step prune` staging).
///
/// Steps:
///
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 79f8e9814..12178838d 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -311,7 +311,7 @@ fn create_command_log(spec: &PipelineSpec, log_dir: &Path, name: &str) -> anyhow
/// convention established by `shell_exec`. That lets `exit_code()` and
/// `interrupt_signal()` work consistently and the `wt hook run-pipeline`
/// process exits 130 on SIGINT and 143 on SIGTERM — the expectation the
-/// "Signal Handling" section of the project `CLAUDE.md` sets for every
+/// "Signal Handling" section of the project `AGENTS.md` sets for every
/// command loop.
///
/// Non-signal failures carry the child's exit code verbatim so log readers
diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rs
index 7db99a7b3..760fdc256 100644
--- a/src/commands/step/rebase.rs
+++ b/src/commands/step/rebase.rs
@@ -99,7 +99,7 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
/// A forwarded Ctrl-C/SIGTERM kills git mid-rebase and leaves the worktree in
/// `REBASING` state, which is otherwise indistinguishable from a merge
/// conflict. The interrupt is surfaced as `Interrupted` *before* the conflict
-/// check, per the signal-handling policy in `CLAUDE.md`: otherwise a user who
+/// check, per the signal-handling policy in `AGENTS.md`: otherwise a user who
/// aborts `wt merge` gets conflict-resolution guidance and a non-130 exit code
/// instead of a clean interrupt. When the kill left the worktree mid-rebase,
/// the interrupt carries a recovery hint — git ran in capture mode, so none
diff --git a/src/completion.rs b/src/completion.rs
index 8b9e54752..c0947f9cf 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -27,7 +27,7 @@
//! uses; see the call site. A change to any of this is measured against
//! `benches/completion.rs`, which runs one repo big enough in every dimension
//! to make the difference visible — and *not* against a `-vv` trace, which
-//! skips prewarm's rev-parse batch (benches/CLAUDE.md, "Analyzing a trace").
+//! skips prewarm's rev-parse batch (benches/AGENTS.md, "Analyzing a trace").
use std::cell::RefCell;
use std::ffi::{OsStr, OsString};
@@ -688,7 +688,7 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
/// - **`template_references_var` per command** (minijinja, not a substring) —
/// scoped to each command rather than the cross-command union returned by
/// `referenced_vars_for_config`, so a non-forwarding sibling referencing
-/// `{{ args }}` can't flip mirroring on. Satisfies CLAUDE.md's "Use Existing
+/// `{{ args }}` can't flip mirroring on. Satisfies AGENTS.md's "Use Existing
/// Dependencies" rule.
/// - **Exactly one forwarder.** Zero means the alias ignores CLI positionals;
/// many means args fan out and mirroring any one would mislead.
diff --git a/src/config/approvals.rs b/src/config/approvals.rs
index 42a9bc81f..34b5249c7 100644
--- a/src/config/approvals.rs
+++ b/src/config/approvals.rs
@@ -70,7 +70,7 @@ struct ApprovedProject {
/// the guard is compiled out and step 3 resolves the real user config
/// directory. In-process unit tests must not resolve here, directly or via
/// [`Approvals::load`]; they pass tempdir-backed paths instead. See
-/// `tests/CLAUDE.md`.
+/// `tests/AGENTS.md`.
pub fn approvals_path() -> Option<PathBuf> {
if let Ok(path) = std::env::var("WORKTRUNK_APPROVALS_PATH") {
return Some(PathBuf::from(path));
@@ -80,7 +80,7 @@ pub fn approvals_path() -> Option<PathBuf> {
panic!(
"WORKTRUNK_APPROVALS_PATH not set in test. Subprocess tests set it via TestRepo. \
An in-process unit test must pass explicit tempdir paths to the mutation \
- methods and must not resolve the approvals path globally. See tests/CLAUDE.md."
+ methods and must not resolve the approvals path globally. See tests/AGENTS.md."
);
#[cfg(not(test))]
diff --git a/src/config/user/path.rs b/src/config/user/path.rs
index 6bdbdb3c6..b07b40c19 100644
--- a/src/config/user/path.rs
+++ b/src/config/user/path.rs
@@ -54,7 +54,7 @@ pub fn is_config_path_explicit() -> bool {
///
/// The guard fires for lib-crate tests only; a bin-crate test links this crate
/// in non-test mode, so `src/commands/` and `src/output/` stay uncovered. See
-/// `tests/CLAUDE.md`.
+/// `tests/AGENTS.md`.
pub fn config_path() -> Option<PathBuf> {
// Priority 1: CLI --config flag
if let Some(path) = CONFIG_PATH.get() {
diff --git a/src/git/error.rs b/src/git/error.rs
index d2b03d51c..654ea4d3a 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -142,7 +142,7 @@ pub trait ErrorExt {
/// per the shell convention (130 SIGINT, 143 SIGTERM) — rather than
/// continuing.
///
- /// See the "Signal Handling" section of the project `CLAUDE.md` for
+ /// See the "Signal Handling" section of the project `AGENTS.md` for
/// the rationale and the full list of loops that apply this policy.
fn interrupt_signal(&self) -> Option<i32>;
}
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index f5d807a46..725efdb21 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -404,7 +404,7 @@ impl Repository {
/// call per repo may run `git ls-remote` (100 ms–2 s); the result is
/// then persisted to `worktrunk.default-branch` and every subsequent
/// call is a local cache hit. No other detection helper may add a
- /// similar fallback. See `CLAUDE.md` → "Network Access" for the policy.
+ /// similar fallback. See `AGENTS.md` → "Network Access" for the policy.
///
/// Detection strategy:
/// 1. Check worktrunk cache (`git config worktrunk.default-branch`)
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index d3d3493e7..3ccb02fbb 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -482,7 +482,7 @@ impl Repository {
/// Every argument that names a worktree routes through here, so they all
/// accept the same vocabulary: the shortcuts, a branch name, and the path
/// of the worktree itself. wt addresses worktrees by branch (see the
- /// "Worktree Model" section of `CLAUDE.md`), so the branch is tried first
+ /// "Worktree Model" section of `AGENTS.md`), so the branch is tried first
/// and a path only answers what a branch name cannot — a detached worktree,
/// or one of several checkouts of the same branch.
///
diff --git a/src/priority.rs b/src/priority.rs
index 910e63ba2..b2c4661f3 100644
--- a/src/priority.rs
+++ b/src/priority.rs
@@ -80,7 +80,7 @@ pub fn in_background_hook() -> bool {
}
/// Extracted comparison so tests can exercise the match without mutating
-/// process-global environment state (forbidden per `tests/CLAUDE.md`).
+/// process-global environment state (forbidden per `tests/AGENTS.md`).
fn is_background_hook_value(value: Option<&OsStr>) -> bool {
value == Some(OsStr::new(BACKGROUND_HOOK_VALUE))
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 346edcbe3..61d054e7f 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -684,7 +684,7 @@ pub fn scrub_git_discovery_env_vars(cmd: &mut std::process::Command) {
/// missing config file as empty), and `GIT_CONFIG_COUNT` with its numbered
/// keys and values — git's environment spelling of `-c` — supplies the two
/// settings the suite needs in the denied config's place. What each entry is
-/// for, and why `-c` precedence keeps this list short: `tests/CLAUDE.md` →
+/// for, and why `-c` precedence keeps this list short: `tests/AGENTS.md` →
/// Git Config Isolation.
pub const HERMETIC_TEST_GIT_ENV: [(&str, &str); 7] = [
("GIT_CONFIG_GLOBAL", "/nonexistent/wt/gitconfig"),
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index a5f48e11a..f6a56f964 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -447,7 +447,7 @@ const TEST_IDENTITY_EMAIL: &str = "[email protected]";
/// settings. The hermetic latch (`shell_exec::enable_hermetic_test_env`)
/// puts both on every `Cmd` child, so an in-process git resolves those
/// rather than the developer's — see the Git Config Isolation section of
-/// `tests/CLAUDE.md`.
+/// `tests/AGENTS.md`.
///
/// `protocol.allow = never` with a `file` exception is the config spelling of
/// `GIT_ALLOW_PROTOCOL=file` (see [`GIT_ALLOWED_PROTOCOLS`] for why the suite
@@ -869,7 +869,7 @@ pub fn test_tempdir() -> TempDir {
/// Hundreds of thousands of stale entries cost nothing to ignore but are
/// expensive to enumerate, and `git::recover::recover_from_path` reads every
/// ancestor directory of a deleted CWD — the measured cost is in
-/// `tests/CLAUDE.md` → Profiling the Suite. One fixed directory never grows.
+/// `tests/AGENTS.md` → Profiling the Suite. One fixed directory never grows.
fn isolated_test_cwd() -> &'static Path {
static ISOLATED_CWD: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
let dir = test_temp_root().join("isolated-cwd");
diff --git a/src/trace/profile.rs b/src/trace/profile.rs
index 24430bc99..ebf6ca60d 100644
--- a/src/trace/profile.rs
+++ b/src/trace/profile.rs
@@ -2,7 +2,7 @@
//!
//! Where [`parse`](super::parse) turns trace lines into [`TraceEntry`] values and
//! [`chrome`](super::chrome) exports them for Perfetto, this module answers the
-//! three questions [`benches/CLAUDE.md`] poses about a single `wt` invocation
+//! three questions [`benches/AGENTS.md`] poses about a single `wt` invocation
//! without leaving the terminal:
//!
//! - **Where does time go?** — [`Profile::by_type`] groups subprocesses by command
@@ -27,7 +27,7 @@
//! the `-vv` diagnostic report (`diagnostic.md`, which embeds the rendered text). The struct's `Serialize` impl
//! is the single canonical JSON source.
//!
-//! [`benches/CLAUDE.md`]: ../../../benches/CLAUDE.md
+//! [`benches/AGENTS.md`]: ../../../benches/AGENTS.md
use std::collections::{BTreeMap, HashMap, HashSet};
use std::time::Duration;
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
new file mode 100644
index 000000000..554fc792e
--- /dev/null
+++ b/tests/AGENTS.md
@@ -0,0 +1,747 @@
+# Testing Guidelines
+
+## Running the Suite
+
+```bash
+cargo run -- hook pre-merge --yes # all tests + lints
+pre-commit run --all-files # lints only
+cargo nextest run --all-features # full suite, fastest runner
+cargo nextest run --all-features -E 'test(/^integration_tests::list_layout::/)' # one module
+cargo test --lib --bins # unit tests
+cargo test --test integration # integration (no shell tests)
+cargo test --test integration --features shell-integration-tests # + shell tests
+```
+
+Every binary the suite spawns is `wt` itself — the mock commands are the same binary linked under other names, dispatching on argv[0] (`testing::mock_stub`) — so no run can spawn missing or stale code: cargo rebuilds a package's own binaries whenever its integration tests build, under every runner and filter, and `wt_bin()` resolves `CARGO_BIN_EXE_wt` — naming that just-built binary — into a hardlink pinned under `target/debug/wt-test-bin/`, which a concurrent `cargo build`'s uplift can't unlink mid-run (see No Retries); outside a cargo runner the suite panics ("CARGO_BIN_EXE_wt not set") rather than guessing a path. `cargo build --bin wt` recompiling right after a test run is the bin-only build being a separate cached unit (a different feature graph), not evidence the tests ran stale code.
+
+**Claude Code web:** `task setup-web` installs zsh, fish, Nushell, PowerShell, `jq`, `lsof`, `gh`, pre-commit, and the Cargo dev tools. Install `task` first if needed: `sh -c "$(curl --location https://taskfile.dev/install.sh)" -- -d -b ~/bin` then `export PATH="$HOME/bin:$PATH"`. Tests that need an unprivileged uid skip automatically when running as root, which both this environment and Codex Cloud do; that covers the permission tests and the `wt remove` stuck-directory pair, the only automated coverage of that path.
+
+**Shell/PTY tests** (`shell-integration-tests` feature): approval prompts, picker, progressive rendering, shell wrappers.
+
+**The gate runs one platform, so `#[cfg(unix)]` hides dead code from it.** A helper, const, or import whose every use sits behind `#[cfg(unix)]` is live locally and dead on Windows, where `-D warnings` fails `test (windows)` with "never used". Gate the item with the same predicate as its uses. Cross-compiling to check locally doesn't work: the C build scripts (tree-sitter, libmimalloc-sys) fail before the Rust lint runs.
+
+## One Result Per Test, Whatever Runs It
+
+Five runners execute this suite — `cargo test`, `cargo nextest run`, `cargo llvm-cov nextest`, `cargo bench`, and the Nix `worktrunk-tests` derivation — and CI uses several of them on the same commit. **A test's result must not depend on which one started it.**
+
+So `.config/nextest.toml` carries no setting that changes what a test observes: no `[env]`, no setup scripts. Anything load-bearing goes where every runner sees it — the harness-latched floor in `shell_exec` for git environment (see Git Config Isolation), `.cargo/config.toml` for `COLUMNS`, the fixture for behavior.
+
+A nextest-only knob doesn't fail loudly when another runner misses it. It yields a *different result*, and the runner that disagrees is typically `cargo llvm-cov` — whose numbers gate a merge, and whose disagreement therefore reads as a coverage regression rather than as missing configuration.
+
+## Profiling the Suite
+
+```bash
+task profile-tests # CPU accounting plus per-test timings
+```
+
+The integration binary dominates: ~2,200 tests averaging ~1s, each spawning `wt` and `git` against a fresh fixture copy. Two thirds of the suite's CPU is kernel time, so the cost is process creation and filesystem churn rather than computation, and it sits in a broad middle rather than in a few outliers. Track `user`/`sys` from the `time` line; wall time is unreliable whenever a sibling worktree is building or testing, which on this project is most of the time. Per-test durations land in `target/nextest/default/junit.xml`.
+
+The fixtures put their temp directories under `test_temp_root()` (`$TMPDIR/wt`) rather than directly in the system temp dir, and `test_tempdir()` is the fixture-side replacement for `TempDir::new()`. Entries in the shared temp root are cheap to ignore but expensive to enumerate, and `git::recover::recover_from_path` reads every ancestor directory of a deleted CWD — its own unit test ran 14.2s against a temp root holding 454k leaked entries, 0.06s once the leak stopped. That root's short name is load-bearing: a unix socket path can't exceed 104 bytes on macOS, and `test_copy_ignored_skips_non_regular_files` binds one 89 bytes in.
+
+Process-scoped scratch space belongs in a fixed directory, not a `TempDir` in a `static`: statics don't run destructors at process exit, so under nextest's process-per-test model that leaks one directory per test into a temp root nothing reliably sweeps (macOS clears it only at boot). To check for a recurrence, run the suite with `TMPDIR` pointed at a fresh directory and see what survives.
+
+## Coverage Investigation
+
+`task coverage` runs the suite through nextest and writes an HTML report to `target/llvm-cov/html/index.html`. Coverage uses the same process isolation as the regular suite: PTY tests must not share one crowded test process. Both CI (the `coverage` workflow) and local `task coverage` pass `--features shell-integration-tests`, so code behind that flag is compiled and measured.
+
+When `codecov/patch` fails, investigate before declaring ready (the merge gate itself is in the root `AGENTS.md` → Coverage):
+
+```bash
+task coverage
+cargo llvm-cov report --show-missing-lines | grep <file> # authoritative miss list; same lines codecov counts
+```
+
+Since cargo-llvm-cov 0.9.0 that column collapses consecutive misses into ranges (`12-18`, not `12, 13, …`), so expand a range before comparing it against a codecov line list.
+
+For each uncovered function, either write a test (integration tests via `assert_cmd_snapshot!` do capture subprocess coverage) or document why it's intentionally untested.
+
+**Querying codecov directly** serves two cases the local report can't: disputing a posted check, and running in CI, where `task coverage` isn't installed. Prefer measuring everywhere else.
+
+```bash
+API=https://api.codecov.io/api/v2/github/max-sixty/repos/worktrunk
+# Full SHAs throughout; an abbreviation 404s. `?pullid=N` compares the PR's
+# *current* head, so name both SHAs to ask about an earlier commit.
+curl -sL "$API/compare/?base=<base-sha>&head=<head-sha>" > "${TMPDIR:-/tmp}/codecov.json"
+
+# Patch coverage per file. `.name` is an object, and the files carrying patch
+# lines are the ones with `has_diff`:
+jq '.files[] | select(.has_diff) | {name: .name.head, patch: .totals.patch}' "${TMPDIR:-/tmp}/codecov.json"
+
+# The missed patch lines in one file. `.coverage.head` is a LineType enum
+# (0=hit, 1=miss, 2=partial), and `.added` keeps context lines inside a hunk
+# from reading as patch misses:
+jq '.files[] | select(.name.head == "<path>") | .lines[]
+ | select(.is_diff and .added and .coverage.head == 1) | {line: .number.head, code: .value}' "${TMPDIR:-/tmp}/codecov.json"
+
+# Whole-file line coverage at one commit. No trailing slash after the path —
+# the route swallows it and answers 404 "coverage info not found":
+curl -sL "$API/file_report/<path>?sha=<sha>"
+```
+
+Per-file `.totals.patch` (equivalently `.totals.head.diff`, `[files, lines, hits, misses, …]`) holds that file's patch numbers, and the posted percentage aggregates them over the files in the PR's own diff. The top-level `totals.base.diff` is a different quantity: the base's coverage of those lines. Commit messages arrive with raw newlines in them, so the JSON is strictly invalid — `jq` copes, Python needs `json.loads(…, strict=False)`.
+
+**A compare listing files the PR never touched** means the merge-base has no report, so codecov walked back to the newest ancestor that does and diffed from there. The posted patch check still scopes to the PR's own diff; it's the API object that widens. Every main commit uploads from the `coverage` workflow, so this points at a failed or missing run on the base commit.
+
+**`skim` fails with E0554 (`#![feature]` on stable):** the local `cargo-llvm-cov` predates 0.7.0, which stopped putting the coverage flags in global `RUSTFLAGS` and started instrumenting only workspace crates. Older versions leak `--cfg=coverage` into every dependency, and `skim` gates a nightly feature on it. Install the version the `code-coverage` job pins rather than working around it (`--no-cfg-coverage` also avoids it; `--no-rustc-wrapper` reinstates it).
+
+**Moved and re-indented lines:** codecov counts every line the diff touches as part of the patch, including one the change only relocated — a `git mv`, or a body re-indented because it moved inside a new wrapper. Pre-existing uncovered lines then count against a patch that changed no behavior. Verify against `main` (under the old path, for a rename): if the lines are identical there, the misses predate the change, and the fix is to say so to the user rather than undo the move.
+
+**"N functions have mismatched data" warning:** `cargo llvm-cov` merges profiles from multiple compilation targets with minor codegen differences (typically 5–20 functions). Expected, harmless, no suppression flag exists ([LLVM #97574](https://github.com/llvm/llvm-project/issues/97574)).
+
+PTY tests need extra setup to be measured at all — they `env_clear()` the subprocess, so LLVM env vars must be passed through explicitly. See "Coverage in PTY Tests" below.
+
+## Running `wt` Commands in Tests
+
+**Use the correct helper to ensure test isolation.** Tests that spawn `wt` must
+be isolated from the host environment to prevent:
+
+- **Directive leakage**: Test commands writing to the user's shell directive file
+- **Config pollution**: Tests reading/writing the user's real config
+- **Git interference**: Host GIT_* environment variables affecting test behavior (the developer's *config* is denied a layer lower — see Git Config Isolation below)
+- **Network access**: a fixture's `https://` remote URL becoming a real connect, with no timeout bounding it (`GIT_ALLOWED_PROTOCOLS` in `src/testing/mod.rs`)
+
+### With a TestRepo fixture (most tests)
+
+Use `repo.wt_command()` which returns a pre-configured Command:
+
+```rust
+// ✅ GOOD: Simple case
+let output = repo.wt_command()
+ .args(["switch", "--create", "feature"])
+ .output()?;
+
+// ✅ GOOD: With additional configuration (piped stdin, etc.)
+let mut cmd = repo.wt_command();
+cmd.args(["switch", "--create", "feature"])
+ .stdin(Stdio::piped());
+```
+
+```rust
+// ❌ BAD: Missing isolation - inherits host environment
+let output = Command::new(wt_bin())
+ .args(["switch", "--create", "feature"])
+ .current_dir(repo.root_path())
+ .output()?;
+```
+
+### Without a TestRepo (e.g., readme_sync tests)
+
+Use the free function `wt_command()`:
+
+```rust
+use crate::common::wt_command;
+
+// ✅ GOOD: Isolated from host environment
+let output = wt_command()
+ .args(["--help"])
+ .current_dir(project_root)
+ .output()?;
+```
+
+`wt_command()`'s default `current_dir` is a process-scoped empty tempdir
+(outside any git repo, no project config) — so a bare `wt_command()` won't
+pick up the test process's inherited CWD. Tests that need a specific CWD
+(e.g., the worktrunk repo root for `readme_sync` help-text capture) must
+call `.current_dir(...)` explicitly.
+
+### Method reference
+
+| Method | Returns | Use when |
+|--------|---------|----------|
+| `repo.wt_command()` | `Command` | Running wt commands with a TestRepo |
+| `wt_command()` | `Command` | Running wt without a TestRepo (free function) |
+| `repo.git_command()` | `Cmd` | Running git commands (use `.run()` not `.output()`) |
+
+### Where a new environment variable goes
+
+A test child's environment is four layers, each with one home in
+`src/testing/mod.rs`: `STATIC_TEST_ENV_VARS` for a determinism knob every child
+needs, `git_test_env` for git isolation (config, timestamps, the transport
+deny), `PTY_TEST_ENV_VARS` for a knob only a terminal triggers, and
+`pty_env_vars` for a path that varies per fixture. `configure_cli_command` and
+`configure_pty_command` apply them by transport, so a variable added to the
+right layer reaches every test that spawns `wt`. A per-builder copy reaches only
+the tests that happen to use that builder, and the ones it misses fail later,
+somewhere else.
+
+**Name it `WORKTRUNK_TEST_*`.** `isolate_subprocess_env` scrubs the parent
+environment by prefix — `GIT_*` and `WORKTRUNK_*` — so the prefix is what makes
+a variable hermetic; an unprefixed name inherits from whatever shell ran the
+suite. The rule covers the test-only protocol between the harness and the mock
+playback, not just knobs that change wt's own behavior:
+`WORKTRUNK_TEST_MOCK_CONFIG_DIR` is read only by the playback dispatch
+(`testing::mock_stub`). A variable `wt` reads in production drops `TEST` and
+keeps `WORKTRUNK_`.
+
+## Git Config Isolation
+
+**No `git` the suite runs reads the developer's `~/.gitconfig`**, whatever the test drives it through and wherever the fixture lives. The guarantee is one environment set, `shell_exec::HERMETIC_TEST_GIT_ENV` — the deny pair pointing `GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` at a path that does not exist, plus the settings the suite needs in the denied config's place — applied to every child at its spawn site. There is no git-config file anywhere in the repo.
+
+**Production spawn sites get the floor from a latch, not from the test.** Most test variables are set on a *child*: `git_test_env` on a git command, `configure_cli_command` on a `wt` subprocess. In-process git is not a child the test configures. `TestRepo` exposes a `repo` field of the production `Repository` type, and `Repository::run_command` builds a plain `Cmd::new("git")` — the test never holds the command, so there is no place to set env on it, and a test cannot set its own process environment instead (under `cargo test` the tests sharing the process run in parallel threads, and `std::env::set_var` beside a thread that spawns a process is the race that makes it `unsafe`). What a test *can* do safely is flip an atomic: the harness latches `shell_exec::enable_hermetic_test_env` in the fixture constructors and `configure_git_*`, and `Cmd` applies the floor to every child it spawns while the latch is set. Production code never latches it, so a user's `wt` inherits their real config; the latch is a test-serving switch in `shell_exec` accepted deliberately — see the `TODO(hermetic-env)` there for the structural alternative (threading an explicit env value through `Repository`).
+
+The harness applies the same floor at the spawn sites it does own:
+
+- `git_test_env` — reaching git through `configure_git_env` / `configure_git_cmd` (`TestRepo::git_command()`, `run_git()`, `run_git_in()`, `git_output()`, `commit_in()`) and a PTY child through `pty_env_vars` — adds the test identity, pinned dates, and locale; `configure_git_cmd` also applies the floor, since a plain `Command` child bypasses the `Cmd` latch.
+- `isolate_subprocess_env` scrubs every inherited `GIT_*` from `wt` children — a host-exported `GIT_CONFIG_*` included — then re-applies the floor explicitly, so a subprocess denies host config just as this process does.
+- a PTY child is `env_clear`ed and inherits nothing, so the floor is carried by hand at the PTY choke point every spawn routes through — `configure_pty_command` in `tests/common/mod.rs` — and again by `pty_env_vars`, whose vector declares a PTY `wt` child's complete environment. Each copy is pinned by its own test (`configure_pty_command_carries_the_git_config_floor`, `pty_env_vars_carry_the_git_config_floor`), because `useConfigOnly` fires only where an identity is missing — no PTY assertion would notice the floor going missing.
+
+**The floor carries two settings.** `user.useConfigOnly` is a backstop: denial alone leaves git *guessing* an identity from the OS username and hostname rather than failing, which is the one way a hermetic suite could still author a commit as the developer. Nothing exercises it, because every path sets an identity, and that is the reason to keep it — without it a future gap goes silent. `rerere.enabled = false` is *set* rather than left unset because git enables rerere on its own whenever `$GIT_DIR/rr-cache` exists, so leaving it unset makes the suite's rerere state depend on what a fixture happens to carry. `commit.gpgsign` is gone, since denial already leaves git on its own default, and so are `advice.mergeConflict` / `advice.resolveConflict` — the snapshot layer strips gutter-prefixed `hint:` lines because they vary across git versions (the filter in `tests/common/mod.rs`), so nothing depends on quieting them at the source.
+
+**A local run can measure a stale fixture.** The standard fixture is built once into `target/debug/wt-test-fixtures/standard-v<N>/` and copied per test, so whatever a git-config change alters *during fixture construction* survives in that copy until the cache is rebuilt. A floor change can therefore pass locally and fail on CI, which always builds fresh. Removing `rerere.enabled` did exactly that: the cached fixture already held an `rr-cache` directory from when the floor enabled rerere, git turns rerere on whenever that directory exists, and so every local test kept the behavior the change had just removed. Before trusting a local measurement of a git-config change, delete `target/debug/wt-test-fixtures/` or bump `STANDARD_FIXTURE_VERSION`.
+
+Three things follow that are easy to get wrong:
+
+- **`GIT_CONFIG_COUNT` is `-c`, so it outranks a repository's own config**, where a global *file* would yield to it. A key belongs in the floor only when no test needs to override it locally. `init.defaultBranch` is the one that doesn't qualify — `default_branch.rs` sets it in a repo to prove `wt` reads it — so every `git init` in the harness names its branch instead.
+- **Identity is not in the floor.** A harness-built git gets it from `git_test_env`; an in-process git gets it from the fixture repo's local config, which every `TestRepo` constructor writes. The floor carries only the denial and the two `-c` settings; identity has those per-command homes already, and a copy in the floor could only drift from them, with `useConfigOnly` failing loudly if a path misses both.
+- **Where fixtures live carries no isolation weight.** A conditional `includeIf "gitdir:<home>"` can't reach them wherever they sit, so `test_temp_root()`'s location is a question of ancestor-walk cost alone.
+
+What the hole cost before this: any key in the developer's config applied to fixture repos, so `commit.gpgsign` failed their commits, `core.hooksPath` ran their hooks, and `core.fsmonitor` / `credential.helper` / `filter.*` ran programs of their choosing. A conditional `includeIf` made which of those happened depend on where `$TMPDIR` sat — the suite passed by accident of the temp dir being outside `$HOME`.
+
+`cargo run -- <cmd>` is untouched: nothing in production latches the floor, so a developer's own invocations keep their aliases, credential helper, and identity.
+
+`GIT_AUTHOR_DATE` / `GIT_COMMITTER_DATE` are **not** part of this floor: `git_test_env` pins them per command, so a commit made through `Repository::run_command` still gets the wall clock. Snapshot the author, not the date.
+
+## Config Isolation for In-Process Unit Tests
+
+`repo.wt_command()` / `wt_command()` isolate *subprocess* tests (above). An
+in-process unit test that calls library functions directly gets no such
+isolation: it runs in the test process, which inherits the real environment.
+
+`Approvals::approve_commands` and the `UserConfig` mutation methods take an
+explicit `&Path`, so a unit test passes a tempdir-backed path and the write stays
+isolated. The global resolvers do not isolate: `Approvals::load()`,
+`approvals_path()`, `config_path()`, and `system_config_path()` all fall back to
+the real `~/.config/worktrunk/`.
+
+<example>
+<bad reason="Approvals::load() reads the real ~/.config/worktrunk/approvals.toml">
+
+Bad:
+
+```rust
+let mut approvals = Approvals::load().unwrap();
+approvals.approve_commands(project, vec![command], &approvals_path).unwrap();
+```
+
+</bad>
+<good reason="Default state plus a tempdir path touches no real config">
+
+Good:
+
+```rust
+let temp_dir = tempfile::tempdir().unwrap();
+let approvals_path = temp_dir.path().join("approvals.toml");
+let mut approvals = Approvals::default();
+approvals.approve_commands(project, vec![command], &approvals_path).unwrap();
+```
+
+</good>
+</example>
+
+Git needs the same care, for a narrower reason. An in-process
+`Repository::run_command()` spawns git with the test process's environment, so
+none of `configure_git_env`'s per-command variables apply — no
+`GIT_ALLOW_PROTOCOL`, no per-test `GIT_CONFIG_GLOBAL`. Host *config* is not
+among the gaps: the latched floor above already denies it. The
+repo's own config is the one layer such a command still reads, so every
+`TestRepo` constructor appends `LOCAL_TEST_CONFIG` (identity
+and the `protocol.allow` transport deny) to it. The identity is required rather
+than convenient — the floor sets `user.useConfigOnly` and carries no name, so a
+repo without one fails its commit instead of authoring from the host's username.
+`TestRepo::assemble` is the single call site; a new constructor routes through it
+and inherits the settings, and the bare fixtures (`BareRepoTest`,
+`NestedBareRepoTest`) get them by composing over `TestRepo`.
+
+`approvals_path()` and `config_path()` refuse the developer's real
+`~/.config/worktrunk/` rather than resolving it. `config_path()` is the one that
+matters most: `set_skip_shell_integration_prompt` and
+`set_skip_commit_generation_prompt` reach it to **write**, so an unguarded
+fall-through edits the config the developer is using. `approvals_path()` panics;
+`config_path()` returns `None`, because its absent state is already meaningful —
+`require_config_path()` turns it into an error, so a write still fails loudly
+while a best-effort read like `prewarm_user_config` simply preloads nothing.
+
+`#[cfg(test)]` makes both guards fire for `worktrunk` lib-crate tests only. A
+bin-crate test (anything compiled into the `wt` binary — `src/commands/`,
+`src/output/`, and the other `main.rs` modules) links the lib in non-test mode,
+so the guard is compiled out there and a global read hits the real config
+silently: it passes wherever `$HOME` is writable and fails only in a sandbox
+that forbids it. Nothing exercises that today — no bin-crate test creates a
+config under a scratch `$HOME` — so it's a live requirement on new tests, not a
+known leak.
+
+`system_config_path()` is deliberately unguarded because it resolves a
+machine-wide file rather than the developer's own.
+
+## Timing Tests: Polling and Absence Windows
+
+**The assertion's polarity picks the tool.** A *presence* assertion waits for something that will happen (a file appears, a counter ticks): poll it, so the test returns the instant the event lands. An *absence* assertion proves something did NOT happen (a hook stays silent, a marker never appears): there's no event to wait for, so hold a fixed window with `SLEEP_FOR_ABSENCE_CHECK`, then assert. The most common timing flake is pairing a fixed sleep with a presence assertion: it guesses how long the work takes and fails when load overruns the guess.
+
+### Presence: long timeouts, fast polling
+
+Use long timeouts (5+ seconds) for reliability on slow CI, but poll frequently (10-50ms) so tests complete quickly when things work:
+- **No flaky failures** on slow machines - generous timeout accommodates worst-case
+- **Fast tests** on normal machines - frequent polling means no unnecessary waiting
+
+```rust
+// ✅ GOOD: Long timeout, fast polling
+let timeout = Duration::from_secs(5);
+let poll_interval = Duration::from_millis(10);
+let start = Instant::now();
+while start.elapsed() < timeout {
+ if condition_met() { break; }
+ thread::sleep(poll_interval);
+}
+
+// ❌ BAD: fixed sleep before a presence assertion (always slow, races under load)
+thread::sleep(Duration::from_millis(500));
+assert!(condition_met());
+
+// ❌ BAD: Short timeout (flaky on slow CI)
+let timeout = Duration::from_millis(100);
+```
+
+Use the helpers in `tests/common/mod.rs`:
+
+```rust
+use crate::common::{wait_for_file, wait_for_file_count, wait_for_file_content};
+
+// ✅ Poll for file existence (60-second default timeout)
+wait_for_file(&log_file);
+
+// ✅ Poll for multiple files
+wait_for_file_count(&log_dir, "log", 3);
+
+// ✅ Poll for file with non-empty content
+wait_for_file_content(&marker_file);
+```
+
+These use exponential backoff (10ms → 500ms cap) for fast initial checks that back off on slow CI. The 60-second default timeout is generous enough to avoid flakiness under CI load.
+
+### Event-driven code: drive the scenario from the callback
+
+When the system under test exposes a callback, channel, or event hook, drive the scenario **causally** through that hook instead of racing wall-clock timers. The callback gives you a happens-before edge into the loop — use it to inject inputs and terminate the run, so the test's timing depends on the event ordering, not on CPU scheduling.
+
+```rust
+// ✅ GOOD: causally driven — first Stall event injects a result; a Stall
+// observed after the result drops tx to end the drain via Disconnected.
+// Runs at threshold speed on any hardware; the 5s deadline is only a
+// safety net.
+let mut sender = Some(tx);
+let mut saw_result = false;
+let outcome = drain_results_with_timings(
+ rx, /* ... */,
+ Instant::now() + Duration::from_secs(5),
+ StallTimings { threshold: ms(20), tick: ms(10) },
+ |event| match event {
+ DrainEvent::Stall { .. } if !saw_result => {
+ sender.as_ref().unwrap().send(result).unwrap();
+ }
+ DrainEvent::Stall { .. } => { sender.take(); } // end drain
+ DrainEvent::Result { .. } => { saw_result = true; }
+ _ => {}
+ },
+);
+
+// ❌ BAD: producer sleeps to land a result "partway through" a window
+// whose size is itself a wall-clock deadline. Every extension of the
+// deadline just makes the race wider, not correct.
+std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(80));
+ tx.send(result).unwrap();
+ std::thread::sleep(Duration::from_millis(2000));
+ drop(tx);
+});
+let outcome = drain_results_with_timings(
+ rx, /* ... */,
+ Instant::now() + Duration::from_millis(1000),
+ /* ... */,
+);
+```
+
+**Rule of thumb:** if your producer thread needs `thread::sleep` to line up with a deadline in the code under test, you're racing the scheduler. Reach for the callback, a channel, or a condvar instead. Fixed deadlines belong only in the safety-net role — "stop if something has truly hung" — not in the assertion path.
+
+### Absence: hold a fixed window
+
+When the assertion proves a negative (`assert!(!marker.exists())`), polling can't help, because there's no event to wait for. Hold a window long enough that the thing would have happened if it were going to, then assert it didn't. Use the shared constant (defined in `src/testing/mod.rs`, re-exported via `tests/common`) so absence sleeps stay greppable and self-documenting:
+
+```rust
+use crate::common::SLEEP_FOR_ABSENCE_CHECK;
+
+thread::sleep(SLEEP_FOR_ABSENCE_CHECK); // 500ms, the floor for an absence window
+assert!(!marker_file.exists(), "Command should NOT have run");
+```
+
+Two traps:
+
+- **Give each half its own wait.** Sleeping once and then asserting both "X happened" and "Y didn't" makes the presence half flaky. Poll for X, then hold the window for Y.
+- **Structural absence needs no window at all.** When the event is gated on a condition the test never sets up, it can't fire regardless of timing. Drop the sleep: poll the positive precondition and the absence holds by construction. A watchdog whose escalation is gated on `command.is_some()` can't escalate with no command, so the test polls for the first render and asserts `!escalated` with no window.
+
+### Time-thresholded output: suppress it at the source
+
+Output that appears only once an operation runs past a threshold is a function of machine load, not of behavior: the `Progress` and `Watchdog` spinners (`src/progress.rs`), `Cmd::delayed_stream`'s progress line, the picker's placeholder reveal. A PTY test captures the raw byte stream, so it keeps every in-place redraw frame a terminal would have erased, elapsed-second counter and all — frames that show up when the whole suite runs together and not when the test runs alone.
+
+Each threshold has an env override pinning it, so the output is present or absent by construction rather than by timing. A new one goes in the baseline that matches its scope — `PTY_TEST_ENV_VARS` when only a terminal triggers it (`WORKTRUNK_TEST_SPINNERS=0`), `STATIC_TEST_ENV_VARS` when a pipe does too (`WORKTRUNK_TEST_DELAYED_STREAM_MS=-1`) — and reaches every PTY child from there, rather than being added per builder. Filtering the frames out of the capture afterwards is the weaker fix: the filter has to model cursor movement, and a block that redraws with a cursor-up spans lines a line-scoped filter can't follow.
+
+## No Retries
+
+Tests run once. Worktrunk configures no nextest `retries`, and no test re-runs its own failed body: a test that passes only on a second attempt is a bug report, and retrying it discards the report while leaving the bug. A green suite has to mean the code is green, not that the run's flakes stayed under a retry budget. Fix the flake at its root:
+
+- A racy assertion is a timing bug. Make it deterministic, per Timing Tests above: poll for the event, or drive it causally through a callback.
+- Resource pressure is a concurrency bug. Windows process creation intermittently fails with STATUS_DLL_INIT_FAILED (exit `-1073741502`) when many tests spawn git/wt children at once. Bound how many heavy tests run together; that removes the pressure instead of retrying past it.
+- A kill at the 180s slow-timeout is a duration symptom with two causes, told apart by the durations around it: many stretched durations alongside high machine load is CPU starvation, usually a sibling worktree's concurrent build; one test pinned at the timeout in an otherwise-normal run is a blocked call inside it, usually network. Starvation's only lever here would be nextest `threads-required` bounds on the heavy PTY tests, deliberately unset while these stay rare one-offs: the bound taxes every healthy run, and can't see the sibling build that caused the starvation.
+- A shared channel with more than one producer is an attribution bug. Counting events drained from a channel between steps only measures the step that produced them if nothing *else* can produce them: a background task's event landing after its step's drain is charged to the next step, so the assertion that fails names the wrong step and the wrong cause. The events are usually indistinguishable (skim's `Event::RunPreview` carries no payload), so identity assertions aren't available — quiesce the other producers instead, before the step sequence arms whatever they'd match. `on_update_pokes_run_preview_only_when_the_visible_pane_changes` is the worked example: `PreviewOrchestrator::wait_for_idle()` before each `note_awaiting`, so the skeleton precompute lands while no key matches it.
+- A spawn that fails `NotFound` is a concurrent-build bug. Cargo uplifts `target/debug/wt` by removing the path and recreating it, so a second `cargo` against the same target directory leaves the binary absent for a fraction of a millisecond per rebuild, failing whatever spawn is in flight with `Os { code: 2, kind: NotFound }` — anywhere: an `insta_cmd` snapshot, a PTY wrapper's `wt config shell init`, a hook whose marker file then never appears — and passing on re-run, which is the signature. `wt_bin()` closes the window by spawning a hardlink pinned under `target/debug/wt-test-bin/` instead of the uplifted path (`testing::pin_test_binary`), so route every `wt` spawn through it or a helper that does; `test_wt_spawns_are_pinned` makes a direct `CARGO_BIN_EXE_wt` spawn fail the suite.
+- A shared namespace is a collision bug. **Never `NamedTempFile::new()`** for a file a test needs by name: `tempfile` retries a name collision only when it surfaces as `AlreadyExists`, and on Windows `create_new` against a name already held by a *directory* — or by a file in delete-pending state — comes back `PermissionDenied`, which it hands straight back to the caller. A full suite run leaves the temp directory full of `.tmpXXXXXX` entries (every `TestRepo` makes one), and under that load the call fails ~1% of the time with `Access is denied.` — a panic that has nothing to do with what the test asserts. Take a `TempDir` and give the files fixed names inside it (`worktrunk::testing::directive_file` is the pattern); a directory collision surfaces as `AlreadyExists`, which tempfile retries.
+
+A bounded poll that rides out one identified `ErrorKind` whose window is understood is itself a root fix, and the doctrine leaves it alone: `pin_test_binary` polls `NotFound` across cargo's uplift window, and `forward_with_etxtbsy_retry` (`src/completion.rs`) polls `ExecutableFileBusy` while a concurrently-forked child holds the just-written script's write fd open. Both fail immediately on any other error, which is what keeps a poll from drifting into a retry.
+
+**Reproducing a Windows-only flake** means reproducing its *neighbours*, not starving it: run the suspect tests in a loop on a Windows runner with a full `cargo nextest run` going alongside. Pinning the CPU instead models the wrong thing whenever the failing run's own timing was normal (compare its duration against the same test passing — nextest prints it, and the `test` job uploads `junit.xml` with every test's time). Measured both ways on the same five tests: 80 iterations under a concurrent full suite reproduced a 1-in-100 Windows failure that no local run had ever shown, while pinning all four cores with busy loops instead just pushed nearly every iteration past the 30s waits — artificial failures that say nothing about the flake.
+
+## Testing with --execute Commands
+
+Use `--yes` to skip interactive prompts in tests. Don't pipe input to stdin.
+
+## Feature Flags, Not Runtime Skipping
+
+**Never skip tests based on runtime availability checks.** Use Cargo feature flags instead.
+
+```rust
+// ❌ BAD: Runtime skip - test silently passes when tool unavailable
+#[test]
+fn test_fish_integration() {
+ if !shell_available("fish") {
+ eprintln!("Skipping: fish not available");
+ return;
+ }
+ // test code...
+}
+
+// ✅ GOOD: Feature flag - test excluded from compilation
+#[cfg(feature = "shell-integration-tests")]
+#[test]
+fn test_fish_integration() {
+ // test code...
+}
+```
+
+**Why:**
+- Runtime skips hide missing test coverage in CI logs
+- Feature flags make dependencies explicit in `Cargo.toml`
+- `cargo test` output clearly shows which tests ran vs were compiled out
+- CI can enable features when dependencies are installed
+
+**Existing feature flags:**
+- `shell-integration-tests` — Tests that drive real shells over a PTY: bash,
+ zsh, fish, nushell, and pwsh, plus the `jq` the Claude hook commands in
+ `plugins/worktrunk/hooks/` pipe their payload through
+
+## PTY Tests and README Examples
+
+Use `insta_cmd` by default. It is faster and lets a test assert stdout, stderr,
+and exit status separately. Use a PTY only when the contract actually depends
+on a terminal: interactive prompts, shell functions and directives, pager
+selection, or the temporal interleaving of stdout and stderr. A README label by
+itself is not a reason to use a PTY.
+
+For README output where interleaving matters, use `build_pty_command` with
+`exec_cmd_in_pty` (or `exec_cmd_in_pty_prompted` for prompt-driven input) from
+`tests/common/pty.rs`. These return the combined stream in terminal order. The
+shell-wrapper-specific equivalent is `exec_in_pty_interactive` in
+`shell_wrapper.rs`.
+
+PTY tests are conformance tests for the shell boundary, not another place to
+retest every command. Keep one representative workflow per distinct shell
+implementation, then test command semantics through ordinary integration
+tests. Add a command × shell case only when that interaction is itself the
+contract.
+
+## Coverage in PTY Tests
+
+`configure_pty_command` clears the child's environment, so an instrumented
+binary would lose the LLVM vars that tell it where to write coverage data. It
+passes them back through, which is one more reason every PTY test starts there:
+
+```rust
+crate::common::configure_pty_command(&mut cmd);
+// ... test-specific env (USER, SHELL, ZDOTDIR, the fixture's paths) ...
+```
+
+## No Global State Mutations in Tests
+
+**Never mutate process-global state in tests.** Rust's test runner executes tests in parallel within the same process, so global mutations leak across tests and cause non-deterministic behavior.
+
+Forbidden patterns:
+- `log::set_max_level()` — affects all concurrent and subsequent tests
+- `std::env::set_var()` — process-wide, races with other tests
+- Setting global `static` variables without synchronization
+
+If coverage tools flag uncovered `log::debug!()` format args, accept the gap — it's not meaningful coverage and not worth global side effects.
+
+```rust
+// ❌ BAD: Global mutation leaks across parallel tests
+#[test]
+fn test_something() {
+ log::set_max_level(log::LevelFilter::Debug);
+ // ...
+}
+
+// ❌ BAD: Environment variable race condition
+#[test]
+fn test_config_loading() {
+ std::env::set_var("MY_CONFIG", "test_value");
+ // ...
+}
+```
+
+For environment-dependent tests, use `Command::new()` with `.env()` to set variables in a subprocess, or use the test isolation helpers (`repo.wt_command()`, `wt_command()`).
+
+## Snapshot Filters
+
+### Bold codes around redacted paths
+
+Source code may wrap a path in `<bold>` for terminal styling (e.g., `cformat!("{label} @ <bold>{path}</> failed")`). Setup-side path filters in `tests/common/mod.rs` substitute the path to a placeholder like `[TEST_CONFIG]` or `[PROJECT_ID]`, and a follow-up filter strips ANSI codes immediately wrapping those placeholders so the snapshot reads as a clean `[PLACEHOLDER]`.
+
+The strip filter only fires on placeholders established **before** it. It runs at the end of `setup_snapshot_settings*`, so any path-redaction filter the test adds *after* setup escapes it.
+
+If a test introduces its own placeholder for a path (e.g., `_REPO_/system-config.toml` → `[TEST_SYSTEM_CONFIG_FILE]`), use `add_path_placeholder_filter` so the filter consumes any styling wrappers around the path:
+
+```rust
+// ✅ GOOD: helper wraps the pattern with optional ANSI consumption
+common::add_path_placeholder_filter(
+ &mut settings,
+ r"_REPO_/system-config\.toml",
+ "[TEST_SYSTEM_CONFIG_FILE]",
+);
+
+// ❌ BAD: bare add_filter substitutes only the path, so a `<bold>{path}</>`
+// source leaves `\x1b[1m[TEST_SYSTEM_CONFIG_FILE]\x1b[22m` in the snapshot.
+settings.add_filter(r"_REPO_/system-config\.toml", "[TEST_SYSTEM_CONFIG_FILE]");
+```
+
+The helper wraps the pattern in `(?:\x1b\[\d+m)*` brackets, which eat only the bold open/close immediately adjacent to the path — surrounding color spans (yellow warning, etc.) are preserved.
+
+Setup-side path-redaction placeholders in the strip list (`add_placeholder_ansi_strip_filter` in `tests/common/mod.rs`): `[TEST_CONFIG]`, `[TEST_CONFIG_NEW]`, `[TEST_APPROVALS]`, `[PROJECT_ID]`, `[TEMP_HOME]`, `[TEMP]`. Placeholders that hold a real value (`[VERSION]`, `[HASH]`, `[BUILD_MODE]`, `[BINARY_PATH]`) keep their bold codes so the snapshot still asserts the user-visible styling. The strip pass is invoked at the end of every `setup_*_snapshot_settings` helper, so the contract holds uniformly across `setup_snapshot_settings*`, `setup_home_snapshot_settings`, and `setup_temp_snapshot_settings`.
+
+## Test Style
+
+### Choose the cheapest boundary
+
+Put a belief at the lowest layer that can prove it:
+
+| Belief | Test boundary |
+|--------|---------------|
+| Parsing, formatting, allocation, state transitions | Direct unit/module test |
+| Git/filesystem/process wiring | Integration test with the smallest fitting fixture |
+| TTY behavior, shell syntax, stream interleaving | PTY or real-shell test |
+
+Exercise boundary values and input matrices exhaustively at the direct layer.
+Keep one representative integration case to prove the pieces are wired
+together. Do not repeat the same matrix end-to-end: a command × shell × width
+cross-product usually measures fixture and process setup, not another product
+behavior.
+
+Equivalent coverage or identical snapshots are useful duplication signals, not
+automatic deletion rules. Before removing a test, identify the belief it owns
+and make sure another test proves that belief at an equal or better boundary.
+
+A test's setup is part of its proof. For topology, absence, and error paths,
+assert the precondition named by the test; fixture names and comments are not
+evidence. If an earlier guard can produce the observed result, the test proves
+that guard rather than the intended condition.
+
+Configuring a subprocess mock is likewise not evidence that production used
+that route. When route selection is the belief, assert the recorded call with
+`mock_calls` and make unexpected calls fail (for example, through `_default`);
+otherwise a fallback or blank response can satisfy the oracle.
+
+Assert semantics through state, structured values, and exit status; snapshot
+the pragmatic user experience when the complete rendering is the contract. A
+custom verifier must fail for every violation it claims to check—diagnostic
+`println!` output is not an oracle.
+
+### Guards that scan source text
+
+Several guards read `src/`, or the snapshot corpus, as text rather than
+compiling it: no stray `println!` outside the allowlist, no `eprintln!` that
+resolves to std's macro instead of anstream's, no bare `env!("VERGEN_…")`, no
+`include_str!` of a path the package won't ship, no host path in a `.snap`, no
+plumbing diff built outside `PlumbingDiff::args`, and nothing but
+`src/testing/mod.rs` spawning `wt` through `CARGO_BIN_EXE_wt`.
+Each one asserts *absence* over what its walk handed it.
+
+That polarity is what makes the failure mode silent. A file that drops out of
+the walk is indistinguishable from a file with nothing wrong in it: the
+violation it carried is never looked for, `violations` stays empty, and the
+test passes green over less than it claims.
+
+So that walk lives once, in `tests/common/source_scan.rs`, and panics on every
+read rather than skipping; its module docstring carries the rest. Other tests
+recurse through directories for their own reasons, and this is about the ones
+whose assertion is absence. A read that returns early is the shape to look
+for. `Err(_) => return` and `let Ok(..) else { return }` are the obvious two,
+and `entries.flatten()` is the one that hides, because it drops a per-entry
+`io::Error` without looking like a `return` at all.
+
+Each guard also proves its walk reached something, since a walk that reads
+cleanly and yields nothing passes just as green. `visit_files` returns the
+number of files it visited and is `#[must_use]`, so forgetting to answer for
+coverage is a compile error rather than a rule someone has to remember — which
+is what the swallowed reads it replaced had going for them. A guard that
+already asserts something an empty walk cannot satisfy discards the count with
+`let _ =`, and that discard is the claim: its proof is the assertion below it,
+and a count beside it would be a second mechanism for one guarantee.
+
+A guard walking several roots counts per root. A layout change moves one root
+and leaves the others, and an aggregate count survives that.
+
+### Snapshot env drift: cosmetic vs. a leak
+
+`insta_cmd` snapshots record the test's environment variables in an `env:`
+block. New or reordered env lines split into two cases — check the *value*
+before dismissing:
+
+- **Cosmetic (accept silently):** value is identical on every machine — a
+ deterministic literal (`"0"`, `C`) or an already-redacted placeholder
+ (`[TEST_HOME]`).
+- **A leak (must fix):** value is host/platform/run-specific — a temp path
+ (`/var/folders/…`, `/tmp/…`), `$HOME`/`$USER`, a PID, a timestamp. It will
+ diff spuriously when the snapshot is regenerated elsewhere. Redact it with
+ `add_redaction(".env.VAR_NAME", "[VAR_NAME]")` in
+ `add_standard_env_redactions` (bound by the `repo` rstest fixture). Note
+ `add_filter` does **not** work on the `env:` block — it only substitutes on
+ captured snapshot content; use a redaction.
+
+Removed vars never appear: insta-cmd (≥0.7, hence the `insta-cmd = "0.7"` dep
+floor) drops every `Command::env_remove` from the recorded block. `get_envs()`
+yields `None` for a removal and `Some("")` for a deliberate set-to-empty, and
+insta-cmd keeps only the latter — so a removed var leaves no trace, while a var
+a test sets to `""` is recorded faithfully as `KEY: ""`. This matters because
+`isolate_subprocess_env` removes whichever `GIT_*` / `WORKTRUNK_*` keys exist
+in the *parent* environment (plus `NO_COLOR` / `SHELL` / `PSModulePath`), so
+which removals happen depends on the host (CI has `GIT_EDITOR`; a contributor's
+box might have `GIT_PAGER`, neither, or both). Dropping removals at the source
+means regenerating on any machine produces the same block — you don't have to
+match CI's `GIT_*` environment.
+
+A var a test affirmatively sets to `""` as its subject does show up:
+`test_list_config_env_override_validation_failure` sets
+`WORKTRUNK_WORKTREE_PATH=""` to trigger the validation warning, and the block
+records it as `WORKTRUNK_WORKTREE_PATH: ""`.
+
+The `args:` block has the same property: a repo path passed as a CLI argument
+(`wt -C <root>`) is covered by the `.args[]` redaction in
+`add_repo_and_worktree_path_filters`, which rewrites it to `_REPO_…` like the
+body filters; any other run-specific argument needs its own redaction.
+
+Path leaks fail `test_no_host_specific_paths_in_snapshots`
+(`snapshot_formatting_guard.rs`), which scans every committed `.snap` for
+host-specific path markers (other run-specific values — PIDs, timestamps —
+still need review-time vigilance). The test exists because insta never *compares* the
+`info:` block — a missing redaction passes on the machine that generated the
+snapshot and only churns when regenerated elsewhere.
+
+A runner caveat: the `repo` fixture leaks its settings binding (rstest has no
+teardown), so under libtest's reused threads a test that binds no settings of
+its own — or clones them via `Settings::clone_current()` without
+`add_standard_env_redactions` — can still appear redacted. nextest (process
+per test) is authoritative — regenerate snapshots with
+`cargo insta test --test-runner nextest` when in doubt.
+
+### Inline snapshots over multi-assert
+
+When a test checks formatted output, use `insta::assert_snapshot!` with an
+inline snapshot instead of multiple `assert!(x.contains(...))` calls. Snapshots
+capture the complete output, so a single snapshot replaces many contains checks
+and catches regressions that spot-checks miss.
+
+```rust
+use insta::assert_snapshot;
+
+// ✅ GOOD: One snapshot captures all formatting
+assert_snapshot!(format_message("hello"), @" │ hello");
+
+// ❌ BAD: Spot-checks that miss structural regressions
+assert!(result.contains("│"));
+assert!(result.contains("hello"));
+assert!(!result.contains("error"));
+```
+
+Import `assert_snapshot` directly (`use insta::assert_snapshot;`) rather than
+using the qualified `insta::assert_snapshot!` form.
+
+For first-time snapshot creation, leave the inline value empty (`@""`), then
+run `cargo insta test --accept` to fill it.
+
+To update existing file-based snapshots (e.g., after editing CLI help text),
+use `cargo insta test --accept`:
+
+```bash
+cargo insta test --accept --test integration -- test_help
+```
+
+Do not manually edit `.snap` files — they contain ANSI escape sequences that
+are difficult to reproduce by hand.
+
+### One test per belief
+
+Group related inputs into a single test when they verify the same belief about
+the code. A test named `test_wrap_text_at_width` that exercises short text, long
+text, single words, and edge cases is better than five separate test functions
+testing each input individually.
+
+Use the minimum sufficient contrasts: one anchor case, then one case that
+changes only the factor needed for each additional claim. A new test earns a
+separate function when it has a distinct setup, oracle, or failure diagnosis—
+not merely another input label or production branch.
+
+```rust
+// ✅ GOOD: One test for the belief "wrapping respects word boundaries"
+#[test]
+fn test_wrap_text_at_width() {
+ assert_eq!(wrap_text_at_width("short text", 20), vec!["short text"]);
+ assert_eq!(wrap_text_at_width("hello world foo bar", 10), vec!["hello", "world foo", "bar"]);
+ assert_eq!(wrap_text_at_width("superlongword", 5), vec!["superlongword"]);
+ assert_eq!(wrap_text_at_width("", 20), vec![""]);
+}
+```
+
+Table-driven tests work well for functions that map inputs to expected outputs:
+
+```rust
+#[test]
+fn test_bash_token_styles() {
+ let cases = [
+ ("function", AnsiColor::Blue),
+ ("keyword", AnsiColor::Magenta),
+ ("string", AnsiColor::Green),
+ ];
+ for (name, expected) in cases {
+ let style = bash_token_style(name).expect(name);
+ assert_eq!(style.get_fg_color(), Some(Color::Ansi(expected)), "{name}");
+ }
+}
+```
+
+### Don't test constructors or dependencies
+
+Tests that verify `Style::new().bold()` produces a bold style, or that
+`StyledString::raw("x")` stores `"x"`, are testing the dependency — not our
+code. Delete these. Test the behavior that uses these types instead.
+
+## Deterministic Time in Tests
+
+Tests use `TEST_EPOCH` (2025-01-02) for reproducible timestamps. The constant is defined in `src/testing/mod.rs`, re-exported via `tests/common/mod.rs`, and automatically set as `WORKTRUNK_TEST_EPOCH` in the test environment.
+
+**For test data with timestamps** (cache entries, etc.), use the constant:
+
+```rust
+use crate::common::TEST_EPOCH;
+
+repo.run_git(&[
+ "config", "worktrunk.state.feature.ci-status",
+ &format!(r#"{{"checked_at":{TEST_EPOCH},"head":"abc123"}}"#),
+]);
+```
+
+**For production code** that needs timestamps, use `worktrunk::utils::epoch_now()` which respects `WORKTRUNK_TEST_EPOCH`. Using `SystemTime::now()` directly causes flaky tests.
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index 6dbd68428..43c994c2d 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -1,747 +1 @@
-# Testing Guidelines
-
-## Running the Suite
-
-```bash
-cargo run -- hook pre-merge --yes # all tests + lints
-pre-commit run --all-files # lints only
-cargo nextest run --all-features # full suite, fastest runner
-cargo nextest run --all-features -E 'test(/^integration_tests::list_layout::/)' # one module
-cargo test --lib --bins # unit tests
-cargo test --test integration # integration (no shell tests)
-cargo test --test integration --features shell-integration-tests # + shell tests
-```
-
-Every binary the suite spawns is `wt` itself — the mock commands are the same binary linked under other names, dispatching on argv[0] (`testing::mock_stub`) — so no run can spawn missing or stale code: cargo rebuilds a package's own binaries whenever its integration tests build, under every runner and filter, and `wt_bin()` resolves `CARGO_BIN_EXE_wt` — naming that just-built binary — into a hardlink pinned under `target/debug/wt-test-bin/`, which a concurrent `cargo build`'s uplift can't unlink mid-run (see No Retries); outside a cargo runner the suite panics ("CARGO_BIN_EXE_wt not set") rather than guessing a path. `cargo build --bin wt` recompiling right after a test run is the bin-only build being a separate cached unit (a different feature graph), not evidence the tests ran stale code.
-
-**Claude Code web:** `task setup-web` installs zsh, fish, Nushell, PowerShell, `jq`, `lsof`, `gh`, pre-commit, and the Cargo dev tools. Install `task` first if needed: `sh -c "$(curl --location https://taskfile.dev/install.sh)" -- -d -b ~/bin` then `export PATH="$HOME/bin:$PATH"`. Tests that need an unprivileged uid skip automatically when running as root, which both this environment and Codex Cloud do; that covers the permission tests and the `wt remove` stuck-directory pair, the only automated coverage of that path.
-
-**Shell/PTY tests** (`shell-integration-tests` feature): approval prompts, picker, progressive rendering, shell wrappers.
-
-**The gate runs one platform, so `#[cfg(unix)]` hides dead code from it.** A helper, const, or import whose every use sits behind `#[cfg(unix)]` is live locally and dead on Windows, where `-D warnings` fails `test (windows)` with "never used". Gate the item with the same predicate as its uses. Cross-compiling to check locally doesn't work: the C build scripts (tree-sitter, libmimalloc-sys) fail before the Rust lint runs.
-
-## One Result Per Test, Whatever Runs It
-
-Five runners execute this suite — `cargo test`, `cargo nextest run`, `cargo llvm-cov nextest`, `cargo bench`, and the Nix `worktrunk-tests` derivation — and CI uses several of them on the same commit. **A test's result must not depend on which one started it.**
-
-So `.config/nextest.toml` carries no setting that changes what a test observes: no `[env]`, no setup scripts. Anything load-bearing goes where every runner sees it — the harness-latched floor in `shell_exec` for git environment (see Git Config Isolation), `.cargo/config.toml` for `COLUMNS`, the fixture for behavior.
-
-A nextest-only knob doesn't fail loudly when another runner misses it. It yields a *different result*, and the runner that disagrees is typically `cargo llvm-cov` — whose numbers gate a merge, and whose disagreement therefore reads as a coverage regression rather than as missing configuration.
-
-## Profiling the Suite
-
-```bash
-task profile-tests # CPU accounting plus per-test timings
-```
-
-The integration binary dominates: ~2,200 tests averaging ~1s, each spawning `wt` and `git` against a fresh fixture copy. Two thirds of the suite's CPU is kernel time, so the cost is process creation and filesystem churn rather than computation, and it sits in a broad middle rather than in a few outliers. Track `user`/`sys` from the `time` line; wall time is unreliable whenever a sibling worktree is building or testing, which on this project is most of the time. Per-test durations land in `target/nextest/default/junit.xml`.
-
-The fixtures put their temp directories under `test_temp_root()` (`$TMPDIR/wt`) rather than directly in the system temp dir, and `test_tempdir()` is the fixture-side replacement for `TempDir::new()`. Entries in the shared temp root are cheap to ignore but expensive to enumerate, and `git::recover::recover_from_path` reads every ancestor directory of a deleted CWD — its own unit test ran 14.2s against a temp root holding 454k leaked entries, 0.06s once the leak stopped. That root's short name is load-bearing: a unix socket path can't exceed 104 bytes on macOS, and `test_copy_ignored_skips_non_regular_files` binds one 89 bytes in.
-
-Process-scoped scratch space belongs in a fixed directory, not a `TempDir` in a `static`: statics don't run destructors at process exit, so under nextest's process-per-test model that leaks one directory per test into a temp root nothing reliably sweeps (macOS clears it only at boot). To check for a recurrence, run the suite with `TMPDIR` pointed at a fresh directory and see what survives.
-
-## Coverage Investigation
-
-`task coverage` runs the suite through nextest and writes an HTML report to `target/llvm-cov/html/index.html`. Coverage uses the same process isolation as the regular suite: PTY tests must not share one crowded test process. Both CI (the `coverage` workflow) and local `task coverage` pass `--features shell-integration-tests`, so code behind that flag is compiled and measured.
-
-When `codecov/patch` fails, investigate before declaring ready (the merge gate itself is in the root `CLAUDE.md` → Coverage):
-
-```bash
-task coverage
-cargo llvm-cov report --show-missing-lines | grep <file> # authoritative miss list; same lines codecov counts
-```
-
-Since cargo-llvm-cov 0.9.0 that column collapses consecutive misses into ranges (`12-18`, not `12, 13, …`), so expand a range before comparing it against a codecov line list.
-
-For each uncovered function, either write a test (integration tests via `assert_cmd_snapshot!` do capture subprocess coverage) or document why it's intentionally untested.
-
-**Querying codecov directly** serves two cases the local report can't: disputing a posted check, and running in CI, where `task coverage` isn't installed. Prefer measuring everywhere else.
-
-```bash
-API=https://api.codecov.io/api/v2/github/max-sixty/repos/worktrunk
-# Full SHAs throughout; an abbreviation 404s. `?pullid=N` compares the PR's
-# *current* head, so name both SHAs to ask about an earlier commit.
-curl -sL "$API/compare/?base=<base-sha>&head=<head-sha>" > "${TMPDIR:-/tmp}/codecov.json"
-
-# Patch coverage per file. `.name` is an object, and the files carrying patch
-# lines are the ones with `has_diff`:
-jq '.files[] | select(.has_diff) | {name: .name.head, patch: .totals.patch}' "${TMPDIR:-/tmp}/codecov.json"
-
-# The missed patch lines in one file. `.coverage.head` is a LineType enum
-# (0=hit, 1=miss, 2=partial), and `.added` keeps context lines inside a hunk
-# from reading as patch misses:
-jq '.files[] | select(.name.head == "<path>") | .lines[]
- | select(.is_diff and .added and .coverage.head == 1) | {line: .number.head, code: .value}' "${TMPDIR:-/tmp}/codecov.json"
-
-# Whole-file line coverage at one commit. No trailing slash after the path —
-# the route swallows it and answers 404 "coverage info not found":
-curl -sL "$API/file_report/<path>?sha=<sha>"
-```
-
-Per-file `.totals.patch` (equivalently `.totals.head.diff`, `[files, lines, hits, misses, …]`) holds that file's patch numbers, and the posted percentage aggregates them over the files in the PR's own diff. The top-level `totals.base.diff` is a different quantity: the base's coverage of those lines. Commit messages arrive with raw newlines in them, so the JSON is strictly invalid — `jq` copes, Python needs `json.loads(…, strict=False)`.
-
-**A compare listing files the PR never touched** means the merge-base has no report, so codecov walked back to the newest ancestor that does and diffed from there. The posted patch check still scopes to the PR's own diff; it's the API object that widens. Every main commit uploads from the `coverage` workflow, so this points at a failed or missing run on the base commit.
-
-**`skim` fails with E0554 (`#![feature]` on stable):** the local `cargo-llvm-cov` predates 0.7.0, which stopped putting the coverage flags in global `RUSTFLAGS` and started instrumenting only workspace crates. Older versions leak `--cfg=coverage` into every dependency, and `skim` gates a nightly feature on it. Install the version the `code-coverage` job pins rather than working around it (`--no-cfg-coverage` also avoids it; `--no-rustc-wrapper` reinstates it).
-
-**Moved and re-indented lines:** codecov counts every line the diff touches as part of the patch, including one the change only relocated — a `git mv`, or a body re-indented because it moved inside a new wrapper. Pre-existing uncovered lines then count against a patch that changed no behavior. Verify against `main` (under the old path, for a rename): if the lines are identical there, the misses predate the change, and the fix is to say so to the user rather than undo the move.
-
-**"N functions have mismatched data" warning:** `cargo llvm-cov` merges profiles from multiple compilation targets with minor codegen differences (typically 5–20 functions). Expected, harmless, no suppression flag exists ([LLVM #97574](https://github.com/llvm/llvm-project/issues/97574)).
-
-PTY tests need extra setup to be measured at all — they `env_clear()` the subprocess, so LLVM env vars must be passed through explicitly. See "Coverage in PTY Tests" below.
-
-## Running `wt` Commands in Tests
-
-**Use the correct helper to ensure test isolation.** Tests that spawn `wt` must
-be isolated from the host environment to prevent:
-
-- **Directive leakage**: Test commands writing to the user's shell directive file
-- **Config pollution**: Tests reading/writing the user's real config
-- **Git interference**: Host GIT_* environment variables affecting test behavior (the developer's *config* is denied a layer lower — see Git Config Isolation below)
-- **Network access**: a fixture's `https://` remote URL becoming a real connect, with no timeout bounding it (`GIT_ALLOWED_PROTOCOLS` in `src/testing/mod.rs`)
-
-### With a TestRepo fixture (most tests)
-
-Use `repo.wt_command()` which returns a pre-configured Command:
-
-```rust
-// ✅ GOOD: Simple case
-let output = repo.wt_command()
- .args(["switch", "--create", "feature"])
- .output()?;
-
-// ✅ GOOD: With additional configuration (piped stdin, etc.)
-let mut cmd = repo.wt_command();
-cmd.args(["switch", "--create", "feature"])
- .stdin(Stdio::piped());
-```
-
-```rust
-// ❌ BAD: Missing isolation - inherits host environment
-let output = Command::new(wt_bin())
- .args(["switch", "--create", "feature"])
- .current_dir(repo.root_path())
- .output()?;
-```
-
-### Without a TestRepo (e.g., readme_sync tests)
-
-Use the free function `wt_command()`:
-
-```rust
-use crate::common::wt_command;
-
-// ✅ GOOD: Isolated from host environment
-let output = wt_command()
- .args(["--help"])
- .current_dir(project_root)
- .output()?;
-```
-
-`wt_command()`'s default `current_dir` is a process-scoped empty tempdir
-(outside any git repo, no project config) — so a bare `wt_command()` won't
-pick up the test process's inherited CWD. Tests that need a specific CWD
-(e.g., the worktrunk repo root for `readme_sync` help-text capture) must
-call `.current_dir(...)` explicitly.
-
-### Method reference
-
-| Method | Returns | Use when |
-|--------|---------|----------|
-| `repo.wt_command()` | `Command` | Running wt commands with a TestRepo |
-| `wt_command()` | `Command` | Running wt without a TestRepo (free function) |
-| `repo.git_command()` | `Cmd` | Running git commands (use `.run()` not `.output()`) |
-
-### Where a new environment variable goes
-
-A test child's environment is four layers, each with one home in
-`src/testing/mod.rs`: `STATIC_TEST_ENV_VARS` for a determinism knob every child
-needs, `git_test_env` for git isolation (config, timestamps, the transport
-deny), `PTY_TEST_ENV_VARS` for a knob only a terminal triggers, and
-`pty_env_vars` for a path that varies per fixture. `configure_cli_command` and
-`configure_pty_command` apply them by transport, so a variable added to the
-right layer reaches every test that spawns `wt`. A per-builder copy reaches only
-the tests that happen to use that builder, and the ones it misses fail later,
-somewhere else.
-
-**Name it `WORKTRUNK_TEST_*`.** `isolate_subprocess_env` scrubs the parent
-environment by prefix — `GIT_*` and `WORKTRUNK_*` — so the prefix is what makes
-a variable hermetic; an unprefixed name inherits from whatever shell ran the
-suite. The rule covers the test-only protocol between the harness and the mock
-playback, not just knobs that change wt's own behavior:
-`WORKTRUNK_TEST_MOCK_CONFIG_DIR` is read only by the playback dispatch
-(`testing::mock_stub`). A variable `wt` reads in production drops `TEST` and
-keeps `WORKTRUNK_`.
-
-## Git Config Isolation
-
-**No `git` the suite runs reads the developer's `~/.gitconfig`**, whatever the test drives it through and wherever the fixture lives. The guarantee is one environment set, `shell_exec::HERMETIC_TEST_GIT_ENV` — the deny pair pointing `GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` at a path that does not exist, plus the settings the suite needs in the denied config's place — applied to every child at its spawn site. There is no git-config file anywhere in the repo.
-
-**Production spawn sites get the floor from a latch, not from the test.** Most test variables are set on a *child*: `git_test_env` on a git command, `configure_cli_command` on a `wt` subprocess. In-process git is not a child the test configures. `TestRepo` exposes a `repo` field of the production `Repository` type, and `Repository::run_command` builds a plain `Cmd::new("git")` — the test never holds the command, so there is no place to set env on it, and a test cannot set its own process environment instead (under `cargo test` the tests sharing the process run in parallel threads, and `std::env::set_var` beside a thread that spawns a process is the race that makes it `unsafe`). What a test *can* do safely is flip an atomic: the harness latches `shell_exec::enable_hermetic_test_env` in the fixture constructors and `configure_git_*`, and `Cmd` applies the floor to every child it spawns while the latch is set. Production code never latches it, so a user's `wt` inherits their real config; the latch is a test-serving switch in `shell_exec` accepted deliberately — see the `TODO(hermetic-env)` there for the structural alternative (threading an explicit env value through `Repository`).
-
-The harness applies the same floor at the spawn sites it does own:
-
-- `git_test_env` — reaching git through `configure_git_env` / `configure_git_cmd` (`TestRepo::git_command()`, `run_git()`, `run_git_in()`, `git_output()`, `commit_in()`) and a PTY child through `pty_env_vars` — adds the test identity, pinned dates, and locale; `configure_git_cmd` also applies the floor, since a plain `Command` child bypasses the `Cmd` latch.
-- `isolate_subprocess_env` scrubs every inherited `GIT_*` from `wt` children — a host-exported `GIT_CONFIG_*` included — then re-applies the floor explicitly, so a subprocess denies host config just as this process does.
-- a PTY child is `env_clear`ed and inherits nothing, so the floor is carried by hand at the PTY choke point every spawn routes through — `configure_pty_command` in `tests/common/mod.rs` — and again by `pty_env_vars`, whose vector declares a PTY `wt` child's complete environment. Each copy is pinned by its own test (`configure_pty_command_carries_the_git_config_floor`, `pty_env_vars_carry_the_git_config_floor`), because `useConfigOnly` fires only where an identity is missing — no PTY assertion would notice the floor going missing.
-
-**The floor carries two settings.** `user.useConfigOnly` is a backstop: denial alone leaves git *guessing* an identity from the OS username and hostname rather than failing, which is the one way a hermetic suite could still author a commit as the developer. Nothing exercises it, because every path sets an identity, and that is the reason to keep it — without it a future gap goes silent. `rerere.enabled = false` is *set* rather than left unset because git enables rerere on its own whenever `$GIT_DIR/rr-cache` exists, so leaving it unset makes the suite's rerere state depend on what a fixture happens to carry. `commit.gpgsign` is gone, since denial already leaves git on its own default, and so are `advice.mergeConflict` / `advice.resolveConflict` — the snapshot layer strips gutter-prefixed `hint:` lines because they vary across git versions (the filter in `tests/common/mod.rs`), so nothing depends on quieting them at the source.
-
-**A local run can measure a stale fixture.** The standard fixture is built once into `target/debug/wt-test-fixtures/standard-v<N>/` and copied per test, so whatever a git-config change alters *during fixture construction* survives in that copy until the cache is rebuilt. A floor change can therefore pass locally and fail on CI, which always builds fresh. Removing `rerere.enabled` did exactly that: the cached fixture already held an `rr-cache` directory from when the floor enabled rerere, git turns rerere on whenever that directory exists, and so every local test kept the behavior the change had just removed. Before trusting a local measurement of a git-config change, delete `target/debug/wt-test-fixtures/` or bump `STANDARD_FIXTURE_VERSION`.
-
-Three things follow that are easy to get wrong:
-
-- **`GIT_CONFIG_COUNT` is `-c`, so it outranks a repository's own config**, where a global *file* would yield to it. A key belongs in the floor only when no test needs to override it locally. `init.defaultBranch` is the one that doesn't qualify — `default_branch.rs` sets it in a repo to prove `wt` reads it — so every `git init` in the harness names its branch instead.
-- **Identity is not in the floor.** A harness-built git gets it from `git_test_env`; an in-process git gets it from the fixture repo's local config, which every `TestRepo` constructor writes. The floor carries only the denial and the two `-c` settings; identity has those per-command homes already, and a copy in the floor could only drift from them, with `useConfigOnly` failing loudly if a path misses both.
-- **Where fixtures live carries no isolation weight.** A conditional `includeIf "gitdir:<home>"` can't reach them wherever they sit, so `test_temp_root()`'s location is a question of ancestor-walk cost alone.
-
-What the hole cost before this: any key in the developer's config applied to fixture repos, so `commit.gpgsign` failed their commits, `core.hooksPath` ran their hooks, and `core.fsmonitor` / `credential.helper` / `filter.*` ran programs of their choosing. A conditional `includeIf` made which of those happened depend on where `$TMPDIR` sat — the suite passed by accident of the temp dir being outside `$HOME`.
-
-`cargo run -- <cmd>` is untouched: nothing in production latches the floor, so a developer's own invocations keep their aliases, credential helper, and identity.
-
-`GIT_AUTHOR_DATE` / `GIT_COMMITTER_DATE` are **not** part of this floor: `git_test_env` pins them per command, so a commit made through `Repository::run_command` still gets the wall clock. Snapshot the author, not the date.
-
-## Config Isolation for In-Process Unit Tests
-
-`repo.wt_command()` / `wt_command()` isolate *subprocess* tests (above). An
-in-process unit test that calls library functions directly gets no such
-isolation: it runs in the test process, which inherits the real environment.
-
-`Approvals::approve_commands` and the `UserConfig` mutation methods take an
-explicit `&Path`, so a unit test passes a tempdir-backed path and the write stays
-isolated. The global resolvers do not isolate: `Approvals::load()`,
-`approvals_path()`, `config_path()`, and `system_config_path()` all fall back to
-the real `~/.config/worktrunk/`.
-
-<example>
-<bad reason="Approvals::load() reads the real ~/.config/worktrunk/approvals.toml">
-
-Bad:
-
-```rust
-let mut approvals = Approvals::load().unwrap();
-approvals.approve_commands(project, vec![command], &approvals_path).unwrap();
-```
-
-</bad>
-<good reason="Default state plus a tempdir path touches no real config">
-
-Good:
-
-```rust
-let temp_dir = tempfile::tempdir().unwrap();
-let approvals_path = temp_dir.path().join("approvals.toml");
-let mut approvals = Approvals::default();
-approvals.approve_commands(project, vec![command], &approvals_path).unwrap();
-```
-
-</good>
-</example>
-
-Git needs the same care, for a narrower reason. An in-process
-`Repository::run_command()` spawns git with the test process's environment, so
-none of `configure_git_env`'s per-command variables apply — no
-`GIT_ALLOW_PROTOCOL`, no per-test `GIT_CONFIG_GLOBAL`. Host *config* is not
-among the gaps: the latched floor above already denies it. The
-repo's own config is the one layer such a command still reads, so every
-`TestRepo` constructor appends `LOCAL_TEST_CONFIG` (identity
-and the `protocol.allow` transport deny) to it. The identity is required rather
-than convenient — the floor sets `user.useConfigOnly` and carries no name, so a
-repo without one fails its commit instead of authoring from the host's username.
-`TestRepo::assemble` is the single call site; a new constructor routes through it
-and inherits the settings, and the bare fixtures (`BareRepoTest`,
-`NestedBareRepoTest`) get them by composing over `TestRepo`.
-
-`approvals_path()` and `config_path()` refuse the developer's real
-`~/.config/worktrunk/` rather than resolving it. `config_path()` is the one that
-matters most: `set_skip_shell_integration_prompt` and
-`set_skip_commit_generation_prompt` reach it to **write**, so an unguarded
-fall-through edits the config the developer is using. `approvals_path()` panics;
-`config_path()` returns `None`, because its absent state is already meaningful —
-`require_config_path()` turns it into an error, so a write still fails loudly
-while a best-effort read like `prewarm_user_config` simply preloads nothing.
-
-`#[cfg(test)]` makes both guards fire for `worktrunk` lib-crate tests only. A
-bin-crate test (anything compiled into the `wt` binary — `src/commands/`,
-`src/output/`, and the other `main.rs` modules) links the lib in non-test mode,
-so the guard is compiled out there and a global read hits the real config
-silently: it passes wherever `$HOME` is writable and fails only in a sandbox
-that forbids it. Nothing exercises that today — no bin-crate test creates a
-config under a scratch `$HOME` — so it's a live requirement on new tests, not a
-known leak.
-
-`system_config_path()` is deliberately unguarded because it resolves a
-machine-wide file rather than the developer's own.
-
-## Timing Tests: Polling and Absence Windows
-
-**The assertion's polarity picks the tool.** A *presence* assertion waits for something that will happen (a file appears, a counter ticks): poll it, so the test returns the instant the event lands. An *absence* assertion proves something did NOT happen (a hook stays silent, a marker never appears): there's no event to wait for, so hold a fixed window with `SLEEP_FOR_ABSENCE_CHECK`, then assert. The most common timing flake is pairing a fixed sleep with a presence assertion: it guesses how long the work takes and fails when load overruns the guess.
-
-### Presence: long timeouts, fast polling
-
-Use long timeouts (5+ seconds) for reliability on slow CI, but poll frequently (10-50ms) so tests complete quickly when things work:
-- **No flaky failures** on slow machines - generous timeout accommodates worst-case
-- **Fast tests** on normal machines - frequent polling means no unnecessary waiting
-
-```rust
-// ✅ GOOD: Long timeout, fast polling
-let timeout = Duration::from_secs(5);
-let poll_interval = Duration::from_millis(10);
-let start = Instant::now();
-while start.elapsed() < timeout {
- if condition_met() { break; }
- thread::sleep(poll_interval);
-}
-
-// ❌ BAD: fixed sleep before a presence assertion (always slow, races under load)
-thread::sleep(Duration::from_millis(500));
-assert!(condition_met());
-
-// ❌ BAD: Short timeout (flaky on slow CI)
-let timeout = Duration::from_millis(100);
-```
-
-Use the helpers in `tests/common/mod.rs`:
-
-```rust
-use crate::common::{wait_for_file, wait_for_file_count, wait_for_file_content};
-
-// ✅ Poll for file existence (60-second default timeout)
-wait_for_file(&log_file);
-
-// ✅ Poll for multiple files
-wait_for_file_count(&log_dir, "log", 3);
-
-// ✅ Poll for file with non-empty content
-wait_for_file_content(&marker_file);
-```
-
-These use exponential backoff (10ms → 500ms cap) for fast initial checks that back off on slow CI. The 60-second default timeout is generous enough to avoid flakiness under CI load.
-
-### Event-driven code: drive the scenario from the callback
-
-When the system under test exposes a callback, channel, or event hook, drive the scenario **causally** through that hook instead of racing wall-clock timers. The callback gives you a happens-before edge into the loop — use it to inject inputs and terminate the run, so the test's timing depends on the event ordering, not on CPU scheduling.
-
-```rust
-// ✅ GOOD: causally driven — first Stall event injects a result; a Stall
-// observed after the result drops tx to end the drain via Disconnected.
-// Runs at threshold speed on any hardware; the 5s deadline is only a
-// safety net.
-let mut sender = Some(tx);
-let mut saw_result = false;
-let outcome = drain_results_with_timings(
- rx, /* ... */,
- Instant::now() + Duration::from_secs(5),
- StallTimings { threshold: ms(20), tick: ms(10) },
- |event| match event {
- DrainEvent::Stall { .. } if !saw_result => {
- sender.as_ref().unwrap().send(result).unwrap();
- }
- DrainEvent::Stall { .. } => { sender.take(); } // end drain
- DrainEvent::Result { .. } => { saw_result = true; }
- _ => {}
- },
-);
-
-// ❌ BAD: producer sleeps to land a result "partway through" a window
-// whose size is itself a wall-clock deadline. Every extension of the
-// deadline just makes the race wider, not correct.
-std::thread::spawn(move || {
- std::thread::sleep(Duration::from_millis(80));
- tx.send(result).unwrap();
- std::thread::sleep(Duration::from_millis(2000));
- drop(tx);
-});
-let outcome = drain_results_with_timings(
- rx, /* ... */,
- Instant::now() + Duration::from_millis(1000),
- /* ... */,
-);
-```
-
-**Rule of thumb:** if your producer thread needs `thread::sleep` to line up with a deadline in the code under test, you're racing the scheduler. Reach for the callback, a channel, or a condvar instead. Fixed deadlines belong only in the safety-net role — "stop if something has truly hung" — not in the assertion path.
-
-### Absence: hold a fixed window
-
-When the assertion proves a negative (`assert!(!marker.exists())`), polling can't help, because there's no event to wait for. Hold a window long enough that the thing would have happened if it were going to, then assert it didn't. Use the shared constant (defined in `src/testing/mod.rs`, re-exported via `tests/common`) so absence sleeps stay greppable and self-documenting:
-
-```rust
-use crate::common::SLEEP_FOR_ABSENCE_CHECK;
-
-thread::sleep(SLEEP_FOR_ABSENCE_CHECK); // 500ms, the floor for an absence window
-assert!(!marker_file.exists(), "Command should NOT have run");
-```
-
-Two traps:
-
-- **Give each half its own wait.** Sleeping once and then asserting both "X happened" and "Y didn't" makes the presence half flaky. Poll for X, then hold the window for Y.
-- **Structural absence needs no window at all.** When the event is gated on a condition the test never sets up, it can't fire regardless of timing. Drop the sleep: poll the positive precondition and the absence holds by construction. A watchdog whose escalation is gated on `command.is_some()` can't escalate with no command, so the test polls for the first render and asserts `!escalated` with no window.
-
-### Time-thresholded output: suppress it at the source
-
-Output that appears only once an operation runs past a threshold is a function of machine load, not of behavior: the `Progress` and `Watchdog` spinners (`src/progress.rs`), `Cmd::delayed_stream`'s progress line, the picker's placeholder reveal. A PTY test captures the raw byte stream, so it keeps every in-place redraw frame a terminal would have erased, elapsed-second counter and all — frames that show up when the whole suite runs together and not when the test runs alone.
-
-Each threshold has an env override pinning it, so the output is present or absent by construction rather than by timing. A new one goes in the baseline that matches its scope — `PTY_TEST_ENV_VARS` when only a terminal triggers it (`WORKTRUNK_TEST_SPINNERS=0`), `STATIC_TEST_ENV_VARS` when a pipe does too (`WORKTRUNK_TEST_DELAYED_STREAM_MS=-1`) — and reaches every PTY child from there, rather than being added per builder. Filtering the frames out of the capture afterwards is the weaker fix: the filter has to model cursor movement, and a block that redraws with a cursor-up spans lines a line-scoped filter can't follow.
-
-## No Retries
-
-Tests run once. Worktrunk configures no nextest `retries`, and no test re-runs its own failed body: a test that passes only on a second attempt is a bug report, and retrying it discards the report while leaving the bug. A green suite has to mean the code is green, not that the run's flakes stayed under a retry budget. Fix the flake at its root:
-
-- A racy assertion is a timing bug. Make it deterministic, per Timing Tests above: poll for the event, or drive it causally through a callback.
-- Resource pressure is a concurrency bug. Windows process creation intermittently fails with STATUS_DLL_INIT_FAILED (exit `-1073741502`) when many tests spawn git/wt children at once. Bound how many heavy tests run together; that removes the pressure instead of retrying past it.
-- A kill at the 180s slow-timeout is a duration symptom with two causes, told apart by the durations around it: many stretched durations alongside high machine load is CPU starvation, usually a sibling worktree's concurrent build; one test pinned at the timeout in an otherwise-normal run is a blocked call inside it, usually network. Starvation's only lever here would be nextest `threads-required` bounds on the heavy PTY tests, deliberately unset while these stay rare one-offs: the bound taxes every healthy run, and can't see the sibling build that caused the starvation.
-- A shared channel with more than one producer is an attribution bug. Counting events drained from a channel between steps only measures the step that produced them if nothing *else* can produce them: a background task's event landing after its step's drain is charged to the next step, so the assertion that fails names the wrong step and the wrong cause. The events are usually indistinguishable (skim's `Event::RunPreview` carries no payload), so identity assertions aren't available — quiesce the other producers instead, before the step sequence arms whatever they'd match. `on_update_pokes_run_preview_only_when_the_visible_pane_changes` is the worked example: `PreviewOrchestrator::wait_for_idle()` before each `note_awaiting`, so the skeleton precompute lands while no key matches it.
-- A spawn that fails `NotFound` is a concurrent-build bug. Cargo uplifts `target/debug/wt` by removing the path and recreating it, so a second `cargo` against the same target directory leaves the binary absent for a fraction of a millisecond per rebuild, failing whatever spawn is in flight with `Os { code: 2, kind: NotFound }` — anywhere: an `insta_cmd` snapshot, a PTY wrapper's `wt config shell init`, a hook whose marker file then never appears — and passing on re-run, which is the signature. `wt_bin()` closes the window by spawning a hardlink pinned under `target/debug/wt-test-bin/` instead of the uplifted path (`testing::pin_test_binary`), so route every `wt` spawn through it or a helper that does; `test_wt_spawns_are_pinned` makes a direct `CARGO_BIN_EXE_wt` spawn fail the suite.
-- A shared namespace is a collision bug. **Never `NamedTempFile::new()`** for a file a test needs by name: `tempfile` retries a name collision only when it surfaces as `AlreadyExists`, and on Windows `create_new` against a name already held by a *directory* — or by a file in delete-pending state — comes back `PermissionDenied`, which it hands straight back to the caller. A full suite run leaves the temp directory full of `.tmpXXXXXX` entries (every `TestRepo` makes one), and under that load the call fails ~1% of the time with `Access is denied.` — a panic that has nothing to do with what the test asserts. Take a `TempDir` and give the files fixed names inside it (`worktrunk::testing::directive_file` is the pattern); a directory collision surfaces as `AlreadyExists`, which tempfile retries.
-
-A bounded poll that rides out one identified `ErrorKind` whose window is understood is itself a root fix, and the doctrine leaves it alone: `pin_test_binary` polls `NotFound` across cargo's uplift window, and `forward_with_etxtbsy_retry` (`src/completion.rs`) polls `ExecutableFileBusy` while a concurrently-forked child holds the just-written script's write fd open. Both fail immediately on any other error, which is what keeps a poll from drifting into a retry.
-
-**Reproducing a Windows-only flake** means reproducing its *neighbours*, not starving it: run the suspect tests in a loop on a Windows runner with a full `cargo nextest run` going alongside. Pinning the CPU instead models the wrong thing whenever the failing run's own timing was normal (compare its duration against the same test passing — nextest prints it, and the `test` job uploads `junit.xml` with every test's time). Measured both ways on the same five tests: 80 iterations under a concurrent full suite reproduced a 1-in-100 Windows failure that no local run had ever shown, while pinning all four cores with busy loops instead just pushed nearly every iteration past the 30s waits — artificial failures that say nothing about the flake.
-
-## Testing with --execute Commands
-
-Use `--yes` to skip interactive prompts in tests. Don't pipe input to stdin.
-
-## Feature Flags, Not Runtime Skipping
-
-**Never skip tests based on runtime availability checks.** Use Cargo feature flags instead.
-
-```rust
-// ❌ BAD: Runtime skip - test silently passes when tool unavailable
-#[test]
-fn test_fish_integration() {
- if !shell_available("fish") {
- eprintln!("Skipping: fish not available");
- return;
- }
- // test code...
-}
-
-// ✅ GOOD: Feature flag - test excluded from compilation
-#[cfg(feature = "shell-integration-tests")]
-#[test]
-fn test_fish_integration() {
- // test code...
-}
-```
-
-**Why:**
-- Runtime skips hide missing test coverage in CI logs
-- Feature flags make dependencies explicit in `Cargo.toml`
-- `cargo test` output clearly shows which tests ran vs were compiled out
-- CI can enable features when dependencies are installed
-
-**Existing feature flags:**
-- `shell-integration-tests` — Tests that drive real shells over a PTY: bash,
- zsh, fish, nushell, and pwsh, plus the `jq` the Claude hook commands in
- `plugins/worktrunk/hooks/` pipe their payload through
-
-## PTY Tests and README Examples
-
-Use `insta_cmd` by default. It is faster and lets a test assert stdout, stderr,
-and exit status separately. Use a PTY only when the contract actually depends
-on a terminal: interactive prompts, shell functions and directives, pager
-selection, or the temporal interleaving of stdout and stderr. A README label by
-itself is not a reason to use a PTY.
-
-For README output where interleaving matters, use `build_pty_command` with
-`exec_cmd_in_pty` (or `exec_cmd_in_pty_prompted` for prompt-driven input) from
-`tests/common/pty.rs`. These return the combined stream in terminal order. The
-shell-wrapper-specific equivalent is `exec_in_pty_interactive` in
-`shell_wrapper.rs`.
-
-PTY tests are conformance tests for the shell boundary, not another place to
-retest every command. Keep one representative workflow per distinct shell
-implementation, then test command semantics through ordinary integration
-tests. Add a command × shell case only when that interaction is itself the
-contract.
-
-## Coverage in PTY Tests
-
-`configure_pty_command` clears the child's environment, so an instrumented
-binary would lose the LLVM vars that tell it where to write coverage data. It
-passes them back through, which is one more reason every PTY test starts there:
-
-```rust
-crate::common::configure_pty_command(&mut cmd);
-// ... test-specific env (USER, SHELL, ZDOTDIR, the fixture's paths) ...
-```
-
-## No Global State Mutations in Tests
-
-**Never mutate process-global state in tests.** Rust's test runner executes tests in parallel within the same process, so global mutations leak across tests and cause non-deterministic behavior.
-
-Forbidden patterns:
-- `log::set_max_level()` — affects all concurrent and subsequent tests
-- `std::env::set_var()` — process-wide, races with other tests
-- Setting global `static` variables without synchronization
-
-If coverage tools flag uncovered `log::debug!()` format args, accept the gap — it's not meaningful coverage and not worth global side effects.
-
-```rust
-// ❌ BAD: Global mutation leaks across parallel tests
-#[test]
-fn test_something() {
- log::set_max_level(log::LevelFilter::Debug);
- // ...
-}
-
-// ❌ BAD: Environment variable race condition
-#[test]
-fn test_config_loading() {
- std::env::set_var("MY_CONFIG", "test_value");
- // ...
-}
-```
-
-For environment-dependent tests, use `Command::new()` with `.env()` to set variables in a subprocess, or use the test isolation helpers (`repo.wt_command()`, `wt_command()`).
-
-## Snapshot Filters
-
-### Bold codes around redacted paths
-
-Source code may wrap a path in `<bold>` for terminal styling (e.g., `cformat!("{label} @ <bold>{path}</> failed")`). Setup-side path filters in `tests/common/mod.rs` substitute the path to a placeholder like `[TEST_CONFIG]` or `[PROJECT_ID]`, and a follow-up filter strips ANSI codes immediately wrapping those placeholders so the snapshot reads as a clean `[PLACEHOLDER]`.
-
-The strip filter only fires on placeholders established **before** it. It runs at the end of `setup_snapshot_settings*`, so any path-redaction filter the test adds *after* setup escapes it.
-
-If a test introduces its own placeholder for a path (e.g., `_REPO_/system-config.toml` → `[TEST_SYSTEM_CONFIG_FILE]`), use `add_path_placeholder_filter` so the filter consumes any styling wrappers around the path:
-
-```rust
-// ✅ GOOD: helper wraps the pattern with optional ANSI consumption
-common::add_path_placeholder_filter(
- &mut settings,
- r"_REPO_/system-config\.toml",
- "[TEST_SYSTEM_CONFIG_FILE]",
-);
-
-// ❌ BAD: bare add_filter substitutes only the path, so a `<bold>{path}</>`
-// source leaves `\x1b[1m[TEST_SYSTEM_CONFIG_FILE]\x1b[22m` in the snapshot.
-settings.add_filter(r"_REPO_/system-config\.toml", "[TEST_SYSTEM_CONFIG_FILE]");
-```
-
-The helper wraps the pattern in `(?:\x1b\[\d+m)*` brackets, which eat only the bold open/close immediately adjacent to the path — surrounding color spans (yellow warning, etc.) are preserved.
-
-Setup-side path-redaction placeholders in the strip list (`add_placeholder_ansi_strip_filter` in `tests/common/mod.rs`): `[TEST_CONFIG]`, `[TEST_CONFIG_NEW]`, `[TEST_APPROVALS]`, `[PROJECT_ID]`, `[TEMP_HOME]`, `[TEMP]`. Placeholders that hold a real value (`[VERSION]`, `[HASH]`, `[BUILD_MODE]`, `[BINARY_PATH]`) keep their bold codes so the snapshot still asserts the user-visible styling. The strip pass is invoked at the end of every `setup_*_snapshot_settings` helper, so the contract holds uniformly across `setup_snapshot_settings*`, `setup_home_snapshot_settings`, and `setup_temp_snapshot_settings`.
-
-## Test Style
-
-### Choose the cheapest boundary
-
-Put a belief at the lowest layer that can prove it:
-
-| Belief | Test boundary |
-|--------|---------------|
-| Parsing, formatting, allocation, state transitions | Direct unit/module test |
-| Git/filesystem/process wiring | Integration test with the smallest fitting fixture |
-| TTY behavior, shell syntax, stream interleaving | PTY or real-shell test |
-
-Exercise boundary values and input matrices exhaustively at the direct layer.
-Keep one representative integration case to prove the pieces are wired
-together. Do not repeat the same matrix end-to-end: a command × shell × width
-cross-product usually measures fixture and process setup, not another product
-behavior.
-
-Equivalent coverage or identical snapshots are useful duplication signals, not
-automatic deletion rules. Before removing a test, identify the belief it owns
-and make sure another test proves that belief at an equal or better boundary.
-
-A test's setup is part of its proof. For topology, absence, and error paths,
-assert the precondition named by the test; fixture names and comments are not
-evidence. If an earlier guard can produce the observed result, the test proves
-that guard rather than the intended condition.
-
-Configuring a subprocess mock is likewise not evidence that production used
-that route. When route selection is the belief, assert the recorded call with
-`mock_calls` and make unexpected calls fail (for example, through `_default`);
-otherwise a fallback or blank response can satisfy the oracle.
-
-Assert semantics through state, structured values, and exit status; snapshot
-the pragmatic user experience when the complete rendering is the contract. A
-custom verifier must fail for every violation it claims to check—diagnostic
-`println!` output is not an oracle.
-
-### Guards that scan source text
-
-Several guards read `src/`, or the snapshot corpus, as text rather than
-compiling it: no stray `println!` outside the allowlist, no `eprintln!` that
-resolves to std's macro instead of anstream's, no bare `env!("VERGEN_…")`, no
-`include_str!` of a path the package won't ship, no host path in a `.snap`, no
-plumbing diff built outside `PlumbingDiff::args`, and nothing but
-`src/testing/mod.rs` spawning `wt` through `CARGO_BIN_EXE_wt`.
-Each one asserts *absence* over what its walk handed it.
-
-That polarity is what makes the failure mode silent. A file that drops out of
-the walk is indistinguishable from a file with nothing wrong in it: the
-violation it carried is never looked for, `violations` stays empty, and the
-test passes green over less than it claims.
-
-So that walk lives once, in `tests/common/source_scan.rs`, and panics on every
-read rather than skipping; its module docstring carries the rest. Other tests
-recurse through directories for their own reasons, and this is about the ones
-whose assertion is absence. A read that returns early is the shape to look
-for. `Err(_) => return` and `let Ok(..) else { return }` are the obvious two,
-and `entries.flatten()` is the one that hides, because it drops a per-entry
-`io::Error` without looking like a `return` at all.
-
-Each guard also proves its walk reached something, since a walk that reads
-cleanly and yields nothing passes just as green. `visit_files` returns the
-number of files it visited and is `#[must_use]`, so forgetting to answer for
-coverage is a compile error rather than a rule someone has to remember — which
-is what the swallowed reads it replaced had going for them. A guard that
-already asserts something an empty walk cannot satisfy discards the count with
-`let _ =`, and that discard is the claim: its proof is the assertion below it,
-and a count beside it would be a second mechanism for one guarantee.
-
-A guard walking several roots counts per root. A layout change moves one root
-and leaves the others, and an aggregate count survives that.
-
-### Snapshot env drift: cosmetic vs. a leak
-
-`insta_cmd` snapshots record the test's environment variables in an `env:`
-block. New or reordered env lines split into two cases — check the *value*
-before dismissing:
-
-- **Cosmetic (accept silently):** value is identical on every machine — a
- deterministic literal (`"0"`, `C`) or an already-redacted placeholder
- (`[TEST_HOME]`).
-- **A leak (must fix):** value is host/platform/run-specific — a temp path
- (`/var/folders/…`, `/tmp/…`), `$HOME`/`$USER`, a PID, a timestamp. It will
- diff spuriously when the snapshot is regenerated elsewhere. Redact it with
- `add_redaction(".env.VAR_NAME", "[VAR_NAME]")` in
- `add_standard_env_redactions` (bound by the `repo` rstest fixture). Note
- `add_filter` does **not** work on the `env:` block — it only substitutes on
- captured snapshot content; use a redaction.
-
-Removed vars never appear: insta-cmd (≥0.7, hence the `insta-cmd = "0.7"` dep
-floor) drops every `Command::env_remove` from the recorded block. `get_envs()`
-yields `None` for a removal and `Some("")` for a deliberate set-to-empty, and
-insta-cmd keeps only the latter — so a removed var leaves no trace, while a var
-a test sets to `""` is recorded faithfully as `KEY: ""`. This matters because
-`isolate_subprocess_env` removes whichever `GIT_*` / `WORKTRUNK_*` keys exist
-in the *parent* environment (plus `NO_COLOR` / `SHELL` / `PSModulePath`), so
-which removals happen depends on the host (CI has `GIT_EDITOR`; a contributor's
-box might have `GIT_PAGER`, neither, or both). Dropping removals at the source
-means regenerating on any machine produces the same block — you don't have to
-match CI's `GIT_*` environment.
-
-A var a test affirmatively sets to `""` as its subject does show up:
-`test_list_config_env_override_validation_failure` sets
-`WORKTRUNK_WORKTREE_PATH=""` to trigger the validation warning, and the block
-records it as `WORKTRUNK_WORKTREE_PATH: ""`.
-
-The `args:` block has the same property: a repo path passed as a CLI argument
-(`wt -C <root>`) is covered by the `.args[]` redaction in
-`add_repo_and_worktree_path_filters`, which rewrites it to `_REPO_…` like the
-body filters; any other run-specific argument needs its own redaction.
-
-Path leaks fail `test_no_host_specific_paths_in_snapshots`
-(`snapshot_formatting_guard.rs`), which scans every committed `.snap` for
-host-specific path markers (other run-specific values — PIDs, timestamps —
-still need review-time vigilance). The test exists because insta never *compares* the
-`info:` block — a missing redaction passes on the machine that generated the
-snapshot and only churns when regenerated elsewhere.
-
-A runner caveat: the `repo` fixture leaks its settings binding (rstest has no
-teardown), so under libtest's reused threads a test that binds no settings of
-its own — or clones them via `Settings::clone_current()` without
-`add_standard_env_redactions` — can still appear redacted. nextest (process
-per test) is authoritative — regenerate snapshots with
-`cargo insta test --test-runner nextest` when in doubt.
-
-### Inline snapshots over multi-assert
-
-When a test checks formatted output, use `insta::assert_snapshot!` with an
-inline snapshot instead of multiple `assert!(x.contains(...))` calls. Snapshots
-capture the complete output, so a single snapshot replaces many contains checks
-and catches regressions that spot-checks miss.
-
-```rust
-use insta::assert_snapshot;
-
-// ✅ GOOD: One snapshot captures all formatting
-assert_snapshot!(format_message("hello"), @" │ hello");
-
-// ❌ BAD: Spot-checks that miss structural regressions
-assert!(result.contains("│"));
-assert!(result.contains("hello"));
-assert!(!result.contains("error"));
-```
-
-Import `assert_snapshot` directly (`use insta::assert_snapshot;`) rather than
-using the qualified `insta::assert_snapshot!` form.
-
-For first-time snapshot creation, leave the inline value empty (`@""`), then
-run `cargo insta test --accept` to fill it.
-
-To update existing file-based snapshots (e.g., after editing CLI help text),
-use `cargo insta test --accept`:
-
-```bash
-cargo insta test --accept --test integration -- test_help
-```
-
-Do not manually edit `.snap` files — they contain ANSI escape sequences that
-are difficult to reproduce by hand.
-
-### One test per belief
-
-Group related inputs into a single test when they verify the same belief about
-the code. A test named `test_wrap_text_at_width` that exercises short text, long
-text, single words, and edge cases is better than five separate test functions
-testing each input individually.
-
-Use the minimum sufficient contrasts: one anchor case, then one case that
-changes only the factor needed for each additional claim. A new test earns a
-separate function when it has a distinct setup, oracle, or failure diagnosis—
-not merely another input label or production branch.
-
-```rust
-// ✅ GOOD: One test for the belief "wrapping respects word boundaries"
-#[test]
-fn test_wrap_text_at_width() {
- assert_eq!(wrap_text_at_width("short text", 20), vec!["short text"]);
- assert_eq!(wrap_text_at_width("hello world foo bar", 10), vec!["hello", "world foo", "bar"]);
- assert_eq!(wrap_text_at_width("superlongword", 5), vec!["superlongword"]);
- assert_eq!(wrap_text_at_width("", 20), vec![""]);
-}
-```
-
-Table-driven tests work well for functions that map inputs to expected outputs:
-
-```rust
-#[test]
-fn test_bash_token_styles() {
- let cases = [
- ("function", AnsiColor::Blue),
- ("keyword", AnsiColor::Magenta),
- ("string", AnsiColor::Green),
- ];
- for (name, expected) in cases {
- let style = bash_token_style(name).expect(name);
- assert_eq!(style.get_fg_color(), Some(Color::Ansi(expected)), "{name}");
- }
-}
-```
-
-### Don't test constructors or dependencies
-
-Tests that verify `Style::new().bold()` produces a bold style, or that
-`StyledString::raw("x")` stores `"x"`, are testing the dependency — not our
-code. Delete these. Test the behavior that uses these types instead.
-
-## Deterministic Time in Tests
-
-Tests use `TEST_EPOCH` (2025-01-02) for reproducible timestamps. The constant is defined in `src/testing/mod.rs`, re-exported via `tests/common/mod.rs`, and automatically set as `WORKTRUNK_TEST_EPOCH` in the test environment.
-
-**For test data with timestamps** (cache entries, etc.), use the constant:
-
-```rust
-use crate::common::TEST_EPOCH;
-
-repo.run_git(&[
- "config", "worktrunk.state.feature.ci-status",
- &format!(r#"{{"checked_at":{TEST_EPOCH},"head":"abc123"}}"#),
-]);
-```
-
-**For production code** that needs timestamps, use `worktrunk::utils::epoch_now()` which respects `WORKTRUNK_TEST_EPOCH`. Using `SystemTime::now()` directly causes flaky tests.
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index f7a7ce631..d9a18d33f 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -1490,7 +1490,7 @@ mod tests {
// and would pass unchanged if `tests` or `benches` stopped yielding
// `.rs` files — the absence claim silently narrowing to one third of
// what it names. See "Guards that scan source text" in
- // `tests/CLAUDE.md`.
+ // `tests/AGENTS.md`.
for dir in ["src", "tests", "benches"] {
let seen = scan_for_needle(&root.join(dir), &needle, root, &mut offenders);
assert!(
diff --git a/tests/common/source_scan.rs b/tests/common/source_scan.rs
index 3efc74829..25b2af99f 100644
--- a/tests/common/source_scan.rs
+++ b/tests/common/source_scan.rs
@@ -2,7 +2,7 @@
//!
//! Those guards assert *absence*, which is what makes a swallowed read
//! dangerous here in a way it isn't for code that acts on what it finds — see
-//! "Guards that scan source text" in `tests/CLAUDE.md` for the shape of that
+//! "Guards that scan source text" in `tests/AGENTS.md` for the shape of that
//! failure and the rules it sets.
//!
//! Every read below panics rather than skipping, so the walk either covers the
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 7165aaf15..4887df954 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -5141,7 +5141,7 @@ fn test_codex_plugin_metadata_is_valid_json() {
// directory (verified against codex-cli 0.144.1). The scanned tree is the
// real-file mirror of repo-root skills/ — `codex plugin add` copies the
// plugin into its cache with a copier that drops symlink entries, which
- // is why the mirror exists. See CLAUDE.md → "Plugin skills are a
+ // is why the mirror exists. See AGENTS.md → "Plugin skills are a
// generated mirror".
assert!(
plugin.get("skills").is_none(),
@@ -5181,7 +5181,7 @@ fn test_codex_plugin_metadata_is_valid_json() {
// inline Codex override means Codex never loads it, so the #3362 collision
// (Codex surfacing the *Claude* file's events) stays closed. `Stop`
// returns 🤖 to 💬 at turn end, and `SessionEnd` clears the marker when
- // the main thread ends. See CLAUDE.md → "Plugin Layout".
+ // the main thread ends. See AGENTS.md → "Plugin Layout".
let codex_hooks = plugin
.get("hooks")
.and_then(|h| h.get("hooks"))
@@ -5260,7 +5260,7 @@ fn test_codex_plugin_metadata_is_valid_json() {
/// also scans `skills/` by convention when the manifest omits the key, but
/// its installer's cache copy drops symlink entries — which is why the
/// plugin's `skills/` is a real-file mirror of the repo-root `skills/`,
-/// generated by `test_docs_are_in_sync` (see plugins/worktrunk/CLAUDE.md
+/// generated by `test_docs_are_in_sync` (see plugins/worktrunk/AGENTS.md
/// → "Plugin skills are a generated mirror"). Gemini
/// (gemini-cli 0.42) resolves the extension at the repo root, so
/// `${extensionPath}/skills/` is the real single-sourced repo-root `skills/`
@@ -5282,7 +5282,7 @@ fn test_plugin_layout_is_consolidated() {
// Repo-local maintainer skills are authored once for Claude and exposed to
// Codex through its conventional .agents/skills discovery path. Windows
// checkouts with core.symlinks=false materialize the link as a plain file;
- // that accepted limitation is documented in plugins/worktrunk/CLAUDE.md.
+ // that accepted limitation is documented in plugins/worktrunk/AGENTS.md.
#[cfg(unix)]
{
let codex_skills = root.join(".agents/skills");
@@ -5436,7 +5436,7 @@ fn test_plugin_layout_is_consolidated() {
}
}
// The assertion above is absence, so an empty mirror satisfies it over
- // nothing — see "Guards that scan source text" in `tests/CLAUDE.md`.
+ // nothing — see "Guards that scan source text" in `tests/AGENTS.md`.
assert!(
mirrored > 0,
"plugins/worktrunk/skills is empty — the mirror never generated, so the \
diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rs
index 9ece8a0c3..353a897a8 100644
--- a/tests/integration_tests/shell_wrapper.rs
+++ b/tests/integration_tests/shell_wrapper.rs
@@ -2423,7 +2423,7 @@ approved-commands = ["echo 'bash background'"]
// These tests generate snapshots for README.md examples. They use PTY execution
// to capture stdout/stderr interleaved in the order users see them.
//
- // See tests/CLAUDE.md for background on why PTY-based tests are needed for README examples.
+ // See tests/AGENTS.md for background on why PTY-based tests are needed for README examples.
/// README example: Pre-merge hooks with squash and LLM commit message
///
diff --git a/tests/integration_tests/snapshot_formatting_guard.rs b/tests/integration_tests/snapshot_formatting_guard.rs
index 68a0db447..821cdcbe9 100644
--- a/tests/integration_tests/snapshot_formatting_guard.rs
+++ b/tests/integration_tests/snapshot_formatting_guard.rs
@@ -27,7 +27,7 @@
//! When the host-path rule fails: add a redaction — env values go in
//! `add_standard_env_redactions`, path arguments are covered by the
//! `.args[]` redaction in `add_repo_and_worktree_path_filters` (both in
-//! `tests/common/mod.rs`); see tests/CLAUDE.md "Snapshot env drift".
+//! `tests/common/mod.rs`); see tests/AGENTS.md "Snapshot env drift".
use crate::common::source_scan::visit_files;
use ansi_str::AnsiStr;
@@ -167,7 +167,7 @@ fn test_no_host_specific_paths_in_snapshots() {
These churn whenever the snapshot is regenerated on another machine.\n\
Add a redaction: env values in `add_standard_env_redactions`, path\n\
arguments via the `.args[]` redaction in `add_repo_and_worktree_path_filters`\n\
- (tests/common/mod.rs); see tests/CLAUDE.md \"Snapshot env drift\".\n\
+ (tests/common/mod.rs); see tests/AGENTS.md \"Snapshot env drift\".\n\
Deliberate example paths use the fake users in FAKE_USERS.",
violations.len(),
violations.join("\n"),
diff --git a/tests/integration_tests/step_tether.rs b/tests/integration_tests/step_tether.rs
index a2e697ab8..5e2c95f85 100644
--- a/tests/integration_tests/step_tether.rs
+++ b/tests/integration_tests/step_tether.rs
@@ -24,7 +24,7 @@ fn group_alive(pgid: i32) -> bool {
!matches!(kill(Pid::from_raw(-pgid), None), Err(Errno::ESRCH))
}
-/// Poll `cond` with a generous cap and fast interval (per tests/CLAUDE.md:
+/// Poll `cond` with a generous cap and fast interval (per tests/AGENTS.md:
/// long timeout for slow CI, fast polling so it returns immediately when the
/// event has happened).
fn wait_until(mut cond: impl FnMut() -> bool) -> bool {
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index d27e88f1c..49aaddc8a 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1492,7 +1492,7 @@ approved-commands = ["{}"]
// post-start runs in the background; with --no-hooks it is never spawned,
// but sleep briefly so a regression that incorrectly spawns it has time to
- // create the marker (per tests/CLAUDE.md "Testing absence").
+ // create the marker (per tests/AGENTS.md "Testing absence").
std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
let worktree = repo
@@ -1550,7 +1550,7 @@ fn test_switch_no_config_commands_with_yes(repo: TestRepo) {
// post-start runs in the background; with --no-hooks it is never spawned,
// but sleep briefly so a regression that incorrectly spawns it has time to
- // create the marker (per tests/CLAUDE.md "Testing absence").
+ // create the marker (per tests/AGENTS.md "Testing absence").
std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
let repo_name = repo.root_path().file_name().unwrap().to_str().unwrap();
let worktree = repo