mirror of
https://github.com/max-sixty/worktrunk.git
synced 2026-11-26 13:37:01 +08:00
965db4080779bbdcf44e8a2dc4e1aff32bc4fac3
674
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
736606bac2 |
fix(copy-ignored): reach .worktreeinclude paths inside a wholly ignored directory (#4751)
`.worktreeinclude` now selects by git's own gitignore rules, including paths inside a wholly ignored directory that an include line names, as Claude Code does. `git ls-files --directory` lists such a directory as one entry, so `.cache/claude-code-types/` under an ignored `.cache/` matched nothing, and `copy-ignored` and `promote` skipped it. Claude Code's own `.worktreeinclude` copy reaches it, and a team trialling the Claude Code plugin lost that cache in every new worktree (Rikmorn/sidekick#287). Git now does all the matching. Discovery runs `git ls-files -o -i --directory` once with the standard exclude sources and, when `.worktreeinclude` exists, again with that file as the only source. An entry is selected where the two listings overlap, taking the deeper path of each pair where one holds the other. Inside a directory git lists whole, only lines that name a path (a slash before the end, past any leading `/` or `**/`) select, as found by a third listing of those lines plus the negations. A name matched at any depth (`.env`, `types/`) selects only outside such directories. Claude Code, which defines the file, agrees on path-naming lines; it differs in opening a directory from a line's text and then applying every line inside, so for `packages/*/.cache/types/` plus `.env` it also copies `packages/foo/node_modules/pkg/.env`. The `.worktreeinclude` parse error goes away, since git takes any line as a pattern. So: - A pattern naming a path inside an ignored directory (`.cache/types/`) selects it, and its siblings stay behind. - A pattern that matches at any depth (`.env`) selects the root `.env` and any `.env` git lists on its own, but never a package's `.env` from `node_modules/`. - A negation can't re-include a path inside a selected directory. - An include line naming a partly ignored directory (`build/` with only `build/*.o` ignored) selects only its ignored files. The cost is that each include listing walks every untracked directory: 0.33 s over 124k ignored files with a warm cache, against 0.03 s for the standard listing. Without `.worktreeinclude`, discovery runs one listing as before. Reaching inside ignored directories needed boundaries that whole-directory entries had made unnecessary: - Built-in VCS and tool-state directories now exclude everything inside them too, so `promote` no longer moves `.jj/repo`. - `promote` refuses a destination that resolves outside its worktree through a symlinked directory, and `copy-ignored` checks before creating parent directories. The containment error now says "write" rather than "copy". The Claude Code page now says that hook-made worktrees ignore `worktree.baseRef`, since the hook input carries the worktree's name and no base. Left alone, and older than this change: copying or promoting into a destination where another worktree is checked out inside an ignored directory writes into that worktree, with or without `.worktreeinclude`. > _This was written by Claude Code on behalf of max-sixty_ |
||
|
|
11f8b5b71c |
fix(forge): read Azure DevOps collection, legacy SSH, and default-repo remotes (#4764)
`GitRemoteUrl::azure_organization` / `azure_project` read the org and project from fixed positions in the remote path. Three valid Azure DevOps remote forms broke that, so `wt list --format json` reported a wrong `repo.forge.project` and `url`, and the `az` CI lookup got the same wrong project (or, for the legacy SSH host, the org `vs-ssh`): | Remote | Before | After | |---|---|---| | `https://myorg.visualstudio.com/DefaultCollection/My%20Project/_git/my-repo` | project `DefaultCollection` | project `My%20Project` | | `myorg@vs-ssh.visualstudio.com:v3/myorg/My%20Project/my-repo` | host `vs-ssh.visualstudio.com`, owner `vs-ssh`, project `v3` | host `myorg.visualstudio.com`, owner `myorg`, project `My%20Project` | | `https://dev.azure.com/myorg/_git/my-repo` | project `_git`, url `…/myorg/_git/_git/my-repo` | project `my-repo`, url `…/myorg/my-repo/_git/my-repo` | A new private `azure_coordinates` resolves `(web host, org, project)` for every shape. It strips a leading `DefaultCollection` on `*.visualstudio.com`, reads `v3/{org}/{project}` on both SSH hosts, and falls back to the repo name when the project segment is omitted (the project's default repo shares its name). The two accessors, `web_url`, `repo_info`, the PR-checkout org detection, and the CI-status context all go through it. The CI-status path and the PR path now take the host from the new `azure_web_host` rather than the raw remote host, so the legacy SSH host maps to `{org}.visualstudio.com`. `repo_info_from_remote_azure_devops_collection_legacy_ssh_and_default_repo` covers the reporter's three remotes plus the `visualstudio.com` short forms. Before the change, the issue's repro gave the wrong values in the table; after it, a local build gives the expected ones. Existing Azure unit and integration tests pass. `project` and `name` still keep the URL's percent-encoding (`My%20Project`), as the issue notes. This PR leaves that unchanged. Closes #4763 — automated triage --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
b96ad3b6cc |
Remove the unused Repository::default_branch_sha accessor (#4744)
Removes `Repository::default_branch_sha`, which has no production caller left. The picker's branch-diff preview now keys its cache through `Repository::branch_diff_spec` (the upstream-aware comparison base), and the log preview's comment at [`items.rs`](https://github.com/max-sixty/worktrunk/blob/2085f470917f60c36911dd587c0aa10bc2244de0/src/commands/picker/items.rs#L1790-L1800) explains why it must not use an inventory snapshot. The only remaining uses were the accessor's own three unit tests and three picker cache tests. AGENTS.md keeps test helpers out of library code, and the compiler doesn't flag the accessor because it is `pub` in the lib crate. The three picker tests (`branch_diff_cache_*`) now take the cache key from `branch_diff_spec(...).cache_sha`, the same value `compute_branch_diff_preview` reads and writes. That ties them to the real key rather than to "local `main`'s SHA", which only coincides with it when the default branch has no upstream. The comment that named the accessor now points at the `local_branches` snapshot contract it was restating. No behavior change, so there is no regression test. `cargo test branch_diff_cache` (3 passed), `cargo test --lib branches`, `cargo clippy --all-targets`, and `cargo fmt --check` all pass locally. Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
64515b0eb3 |
Label wt list diff columns with @ and ^ instead of HEAD and main (#4732)
`wt list` labelled its ahead/behind and branch-diff columns `main↕` and `main…±` in every repository, so a repo whose default branch is `master` or `develop` saw a header naming a branch it doesn't have (#4727). Following the discussion there, the headers now use the symbols worktrunk already gives these refs: | Column | Before | After | |--------|--------|-------| | `working-diff` | `HEAD±` | `@±` | | `ahead-behind` | `main↕` | `^↕` | | `branch-diff` | `main…±` | `^…±` | `^` is the default-branch shortcut `wt switch ^` accepts, and `@` is both Git's and `wt switch`'s name for the current HEAD. The `## Columns` section of the list docs now explains this in place of the sentence that defended the fixed `main` label. No column changes width. Each one is sized by its pre-allocated values (`+999 -999`, `↑99 ↓99`), which were already wider than the old headers, so the only layout change is where the shorter header is centred. Config keys (`[list] columns`) and JSON output don't change. The change itself is the three strings in `ColumnKind::header`. The rest is regenerated snapshots and doc mirrors, plus comments and test fixtures that quoted the old labels. One picker test, `test_arrow_toward_row_ignores_the_column_header`, relied on the header containing `main`; it now checks the same header exclusion with `Remote`, which appears only in the header row. The demo GIF snapshots under `docs/demos/snapshots/` still show the old headers. They come from the demo build (`docs/demos/build`), which needs VHS and isn't run here. Locally, the list, picker, help and docs-sync tests pass, along with clippy and fmt. Some `config_show`/`configure_shell` tests and a few socket and signing tests fail in this sandbox, and they fail the same way on `main`. Refs #4727. The issue's other points are still open: how `C`/`K`/`∞` overflow values are shown and documented. Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
f35966e86a |
Stop the fsmonitor orphan sweep killing submodule daemons (#4729)
The orphan fsmonitor sweep that runs after `wt remove` and `wt merge` (`run_internal_sweep` → `reap_orphan_fsmonitor_daemons` → `classify_orphans`) treated any daemon as a class-2 orphan when its git-dir sat under the repo's git-common-dir but wasn't a live worktree's git-dir. Submodule git-dirs also live under the common dir, at `.git/modules/<name>`, and `git worktree list` never reports them. So with `core.fsmonitor=true` set globally, every sweep sent SIGTERM and then SIGKILL to the daemons serving live submodules. That breaks the module's own rule that a daemon serving a live checkout is never reaped. Git respawns the daemon on the next command, so the damage is a lost cache, not lost data. This PR limits class 2 to the git-dirs this repo's own worktrees use: the common dir itself, and `<common-dir>/worktrees/<name>`. Everything else nested in the common dir is spared, the same way daemons for other repositories already are. `classifies_each_orphan_class_and_spares_others` now also has a submodule daemon and a daemon for a submodule's linked worktree. Under the old `starts_with` check, both would have been selected. Locally, the fsmonitor unit tests and clippy pass. The one other failure, `start_fsmonitor_daemon_skips_fork_when_daemon_answers`, also fails on `main` here, because this sandbox blocks `AF_UNIX` sockets. Found during the nightly survey by reading the code, not from a user report. Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
c45a2f636e |
fix(switch): use a GitHub PR URL's host for gh api (#4722)
`wt switch https://host/owner/repo/pull/N` asked `gh api` with no `--hostname`, so the lookup went to gh's default host. An Enterprise URL then 404'd when the git remote was github.com, even though gh was logged in on the URL's host. When `forge.hostname` is unset, the `/pull/N` URL's host is now passed as `--hostname` if `gh auth token` succeeds for it. `pr:N` still follows the remote, and the 404 hint is unchanged. Checked with the new switch cases (logged in and not), the existing enterprise-remote regression, the URL-host unit test, `cargo test --doc`, and `cargo clippy --all-targets --all-features -- -D warnings`. Refs #4709 |
||
|
|
79f19f6407 |
fix(switch): pass a GitHub Enterprise remote's host to gh api when gh is logged in to it (#4710)
`gh api` doesn't take its host from the repository. Without `--hostname` it uses gh's default host, which is github.com once more than one host is logged in. `fetch_pr_info` passed `--hostname` only when `forge.hostname` was set, so on a GitHub Enterprise remote `wt switch pr:N` and `wt switch <PR URL>` asked github.com for the PR and got a 404. With no `forge.hostname`, the lookup now passes the GitHub remote's host as `--hostname` if `gh auth token --hostname <host>` succeeds (a local check, no network; `choose_pr_forge` already uses the same check). An SSH alias such as `github-personal` has no gh login, so it still goes to gh's default host. That keeps the #1790 fix in place, the one #1826 made by removing host detection. A configured `forge.hostname` still takes priority. github.com remotes skip the check, so they behave as before. `test_switch_pr_enterprise_remote_passes_hostname` uses an `https://github.example.com/...` remote and a mock `gh`. When `gh` is logged in to that host, the test expects `--hostname github.example.com` on the `api` call; it failed before this change and passes now. When `gh` isn't logged in to it, the test expects no `--hostname` flag. The existing `pr` integration tests pass. Not changed here: the issue's second suggestion, a 404 hint that names `forge.hostname`. That case still applies when `gh` has no login for the Enterprise host. Whether to add that output is up to a maintainer. A PR URL's own host is also not used yet. In the reported setup the remote's host matches the URL's, so this change fixes that case. Refs #4709 — automated triage Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
78e1357583 |
feat(remove): back up uncommitted changes before --force discards them (#4545)
`wt remove --force` now saves a worktree's uncommitted changes before discarding them, using the same `refs/wt-backup/<branch>` ref and reflog that the squash backup in `wt merge` / `wt step squash` already uses. The output then prints the backup and a recovery command: ``` ▲ Discarding uncommitted changes (--force): ?? devbox.lock ↳ Backup created @ refs/wt-backup/feature-untracked (690353c) ↳ To recover in a new worktree, run wt switch --create --base 690353c… --no-hooks recovery/690353c ``` Closes #4544. ## What gets saved - Staged, unstaged, and untracked files go into the snapshot, which is what `git add -A` would stage. The snapshot is built through a `TempIndex`, so the real index and the stash list are left alone. - Ignored files, such as build output, are not saved. For submodules, only the checked-out commit is recorded; uncommitted changes inside a submodule are not saved. - The backup commit's parent is the worktree's `HEAD`, so the branch tip also stays reachable after `-D` deletes the branch. On an unborn branch the commit has no parent. - The backup is taken only when `--force` actually discards something. A clean `--force` removal creates no ref. ## Decisions for review - **Always on, no flag.** This follows the issue thread: a flag would grow the CLI, and always saving means `-f` loses nothing you can't get back. - **A failed backup refuses the removal.** The error is `Failed to back up uncommitted changes; worktree not removed`, followed by git's own error, and the "Discarding uncommitted changes" warning is printed only after the backup succeeds. That follows the data-safety guidance in AGENTS.md. It means `wt remove -f` now refuses a worktree that `git add -A` can't snapshot, such as one holding an unreadable non-ignored file or an untracked nested repo with no commits. A worktree whose `git status` fails (for example, a corrupt index) still has no backup and is removed as before (#4347). The alternative is to warn and continue. - **Cost.** Untracked files that aren't ignored are written as blobs. A large unignored artifact makes the removal slower and grows the object store until the reflog entry expires. Nothing prunes `refs/wt-backup/` today, and this PR doesn't change that. ## Code `create_safety_backup` and the new `create_removal_backup` (`src/git/repository/working_tree.rs`) share a `record_backup` helper for the `commit-tree` / `update-ref` step. The helper looks up the branch name without the cache, and falls back to `symbolic-ref` so an unborn branch is still named. The removal side lives in `stage_worktree_removal` (`src/git/remove.rs`). That function runs right before the worktree is renamed into trash, so it covers `wt remove`, `wt merge --remove`, and the foreground path. ## Tests - `test_remove_force_with_untracked_files` now checks that the backup ref holds the untracked file's content, that its parent is the removed branch tip, and that an ignored file is excluded. - A new unit test covers the unborn-branch case. - `test_remove_force_refuses_when_backup_fails` checks that an untracked nested repo with no commits leaves the worktree in place, and that no discard warning is printed. - The four `remove_force_with_*` snapshots and the `wt remove --help` snapshot gain the new lines. The docs (`wt remove` help, FAQ) mention the backup. --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
0081536a2b |
fix(switch): handle fork branch conflicts on GitLab and Azure DevOps (#4542)
`wt switch` now handles a fork PR or MR whose branch name is already used locally on GitLab and Azure DevOps, matching the existing GitHub and Gitea behavior. GitLab uses the source project's namespace as a prefix, including nested groups; Azure DevOps uses the fork repository name. The prefixed branch tracks the PR or MR ref and remains fetch-only, so it cannot push to the fork. The change also updates the `wt switch` help and its generated documentation to describe the shared behavior. Integration tests cover GitLab conflicts with and without existing tracking, Azure DevOps conflicts, and the no-conflict Azure path. The prefixed-name unit tests, docs sync test, and help snapshots pass locally. --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
ea0dbee6ce |
fix(switch): clear a stale marker when --create makes the branch (#4704)
A branch deleted outside `wt` (for example with `git branch -D`) leaves its `worktrunk.state.<branch>.marker` key in git config. A later `wt switch --create` with the same name then showed the old 🤖/💬. Now `wt switch --create` clears that branch's marker once `git worktree add -b` succeeds. #4684 already clears the marker on every `wt` deletion path. This is the follow-up the maintainer asked for when closing #4685. - The deletion helper from #4684 moves to `Repository::clear_branch_marker`, and both call sites use it. It is still best effort: a failed unset is logged at debug level, and only marker JSON is removed, so a `vars` entry named `marker` that shares the key is left alone. - Only `--create` clears the marker. Switching to an existing branch keeps its marker, and so does a DWIM checkout from a remote branch or a PR/MR ref. - A branch deleted and recreated with plain `git` still keeps its marker until `wt config state marker clear`. The marker help, its generated docs, and the help snapshot now say so. `test_switch_create_clears_stale_marker` sets a marker on a branch name that has no branch and on an existing branch. It then runs `wt switch --create` for the first and plain `wt switch` for the second. It fails without the change, because the stale marker survives, and passes with it. The existing `deletion_*` unit tests pass on the moved helper. Refs #4683 Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
bac7f7e137 | fix(tests): seed tempfile's name generator per process (#4693) | ||
|
|
5bdb832fe8 | fix(remove): clear a branch's marker when wt deletes the branch (#4684) | ||
|
|
365539a266 |
test: format fork remote URLs without spawning gh or glab (#4679)
`git::remote_ref::github::tests::test_fork_remote_url_formats` ran the real `gh config get git_protocol --host …` from the test runner's PATH, and on Windows CI that subprocess has twice hung past nextest's 180s limit (#4577, #4672) while every other test passed. The test only checked the URL shape, accepting either protocol, so it never needed `gh`. URL formatting now lives in a pure `host_remote_url(host, owner, repo, ssh)` helper in `src/git/remote_ref/mod.rs`. Its unit test pins both the SSH and HTTPS forms and spawns nothing. The GitLab test had the same structure with `glab`, so it moves to the shared helper too. `fork_remote_url` behaves the same for both forges. The protocol query is still exercised end to end by the mock-CLI integration tests in `tests/integration_tests/switch.rs`, which answer `config get git_protocol` with `ssh` and assert the `--host` argument for GitHub and GitLab. This change does not explain why `gh` stalled on the Windows runner; neither timeout log shows anything from inside the subprocess. It removes the test's dependency on the runner's `gh`, which was the only thing exposing the stall. Closes #4672 — automated triage Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
d5a9e4f48d |
fix(list): deduplicate concurrent ahead/behind counts (#4663)
Two statusline tasks can request the same ahead/behind SHA pair concurrently when local `main` trails `origin/main`. Each previously missed the persistent cache and launched its own `git rev-list --count`. A per-repository, per-pair in-memory cache now holds the first computation while the other caller waits; the persistent cache still serves later processes. The new statusline regression test reproduced two matching `rev-list` calls before the change and passes with at most one after it. `cargo test --lib test_ahead_behind_reads_cache`, the focused integration test, and `cargo fmt --check` pass. Closes #4662 — automated triage --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
4907d2dd40 | fix(remove): find Linux reap candidates through procfs (#4631) | ||
|
|
16d52e58b0 |
Report removal failures with the surviving checkout and branch state (#4457)
A branch-deletion failure can be lost after its checkout has already been removed. Return a contextual error through foreground and silent callers after arranging teardown, while preserving partial JSON results, including `retained_failed`, and the underlying cancellation signal. Later failures in an already detached cleanup child continue to go to its log. The destructive Git command owns checkout-removal errors and surviving-entry details. Preflight and staging refusals keep their own diagnostic, so they do not imply that deletion partly succeeded; actual partial failures still list survivors. Validation: 160 removal integration tests, 83 prune integration tests, and the cancellation and silent-picker unit regressions pass. The full project gate passes: 5,447 tests plus Clippy, formatting, docs, doctests, and lockfile checks. Independent source review found no remaining defects. > _This was written by Codex on behalf of max-sixty_ |
||
|
|
899b6c6aa6 |
Redact sensitive auth probe output and restrict log permissions (#4604)
Authentication probes print their credentials, which captured-output logging previously copied into debug logs, diagnostics, and stderr under `RUST_LOG=debug`. Add `Cmd::sensitive_output()` and apply it to GitHub and GitLab token probes so callers retain the original output while both subprocess logging targets emit `[redacted]`. Status and timing remain available, including for failed probes; pipelines propagate sensitivity to both commands. Use one permission-preparation helper for debug, diagnostic, command-history, and background-hook logs. On Unix it applies `0600` to regular files and `0700` to log directories, including existing paths and command-log rotation. Initialization also secures existing active and rotated audit logs when the current command writes no audit entry. Permission repair handles read-only files without opening audit streams, so FIFOs cannot block initialization. Preserve native file-opening behavior for FIFO log destinations and keep `RUST_LOG` filtering consistent across full and bounded output. Validation: the full project pre-merge gate passed with 5,446 tests passing and one skipped, plus formatting, Clippy, doctests, and rustdoc. Regression coverage checks fake credentials across all logging destinations, returned output, failures, concurrent commands, pipelines, and new/existing log permissions. Disabling redaction made all three auth-probe regression cases fail on leaked fake credentials. > _This was written by Codex on behalf of max-sixty_ |
||
|
|
89e6040848 |
Keep legacy project approvals within SSH port boundaries (#4606)
A saved approval for `host.example/o/r` previously authorized project commands from `ssh://git@host.example:2222/o/r.git` through the legacy identifier fallback. Exclude legacy identifiers that lost the SSH port, including malformed SSH URLs, so approval lookup, project settings, and approval removal use the same server boundary. Safe hostname-case and raw `git+ssh` compatibility remain. Non-default-port repositories must reapprove commands under their port-qualified ID and use that ID for project overrides. Regression coverage exercises refused exact and wildcard port-less approvals and successful port-qualified approval through a project alias. Validation: regression failed before the fix and passes afterward; independent review found no issues; formatting, lint, documentation, and doctests passed. Full local suite: 5,440 passed, one detached-removal timeout; that case passed separately. > _This was written by Codex on behalf of max-sixty_ |
||
|
|
94338ed210 |
fix: support slash-named remotes in branch inventory (#4271)
Git permits remote names such as `team/fork`. Splitting `team/fork/feature` at its first slash prevented `wt switch feature` from finding the remote branch and misidentified remote names in list and CI consumers. Resolve remote-tracking refs against the longest configured remote prefix once per inventory scan, and retain that boundary through list JSON, CI lookup, and picker deduplication. Read local branches’ upstream remote directly from Git’s tracking metadata. Remote HEAD queries remain supported, and orphaned refs retain the conventional first-segment fallback. Validation: regression reproduction fails with the original parser; 263 focused tests pass, including slash-named and overlapping remotes, remote HEAD queries, and local tracking. Pre-commit/Clippy and documentation checks pass. The full local suite reports 5,316 passes and three PowerShell failures; standalone PowerShell also crashes with “Stack overflow” on this machine. > _This was written by Codex on behalf of max-sixty_ --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> Co-authored-by: Maximilian Roos <m@maxroos.com> |
||
|
|
5acc8da7c5 |
chore: correct stale docs and skill references to the trash drain and picker tabs (#4529)
This PR fixes comments, user docs, and maintainer skills that no longer match the code. There are no behavior changes. #4516 replaced the trash sweep, and several references still describe the old one. A few other docs were wrong before that. - **Troubleshooting, `wt list` timeout example**: the warning prints `TaskKind::display_name()` labels (`working-tree diff, working-tree conflict check`), not the kebab-case names the example showed. The snapshot in `format_drain_timeout_diag`'s tests uses the same labels. - **Troubleshooting, config checklist**: dropped "path must be relative, not absolute". No such validation exists, and `worktree-path` accepts absolute paths. - **`drain_trash` doc** (`src/git/remove.rs`): dropped "Every staged removal starts a drain". That describes the behavior #4516 replaced. Removals now skip spawning when a drain is already running. - **State module doc**: the default-branch override key is `worktrunk.default-branch`, not `worktrunk.default_branch.*`. - **Summary tab number**: `PreviewMode::Summary = 6`, so the `[list] summary` doc comment and a test comment now say tab 6 instead of 5. - **`release` skill**: the safety-scan note named "the trash sweep in `src/commands/process.rs`" as the densest destructive code outside `src/git/`. That sweep now only spawns a drain; the deletion walk is in `src/remove_dir.rs`, so the note points there. `unlinkat`, the walk's primitive, is added to the keyword regex, which would otherwise miss changes to it. - **`writing-user-outputs` skill**: `sweep_stale_trash` is now `run_internal_sweep`. The plugin skills mirror was regenerated, and `test_docs_are_in_sync` and the `switch_picker_dry_run` tests pass. No regression test is needed because no behavior changed. Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
90da2475b0 |
Reclaim stale temporary indexes with age-based cleanup (#4469)
Abruptly terminated commands can leave full temporary Git index copies behind. The contributor reported 52,786 files totaling 127 GB after three days of frequent statusline cancellations. Reclaim index copies and their Git lock siblings older than one hour when a command next creates a temporary index. Keep the existing filename prefix so cleanup also handles files left by older versions. Sweep the system temp directory once per process, without making other probe threads wait, and retain best-effort cleanup in the Git-directory fallback. Normal exits still remove their own temporary indexes. This uses age alone: no PID-tagged filenames, process checks, or platform-specific liveness behavior. Move commit-preview approval before temporary-index creation so an unattended approval prompt cannot age out an index needed afterward. The one-hour limit is a retention policy; a suspended operation or unusually slow Git filter can still exceed it. Statusline computations are unchanged. Validation: regression tests cover stale indexes and locks, recent/future/unrelated files, both storage locations, cleanup failures, real-index preservation, and the actual approval wait. The approval test fails with the old ordering and passes with the fix. Independent review, lint, docs sync, and docs build passed. The local full gate passed 5,412 tests; three PowerShell tests failed because the installed pwsh also crashes with Stack overflow on a standalone arithmetic command outside the repository. > _This was written by Codex on behalf of max-sixty_ --------- Co-authored-by: Jonah Eaton <49370794+jonaheaton@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Maximilian Roos <m@maxroos.com> |
||
|
|
023cb0a82d |
Propagate failed Git predicates instead of treating them as missing refs (#4562)
When a ref query fails, `wt switch --create` can treat the branch as absent and create it from a fallback base. The same predicate helper can cache a failed `merge-base --is-ancestor` (for example, a missing object) as a permanent `false`. Give `run_command_check` Git's predicate contract: status 0 is true, 1 is false, and anything else propagates the command error. `ref_exists` uses quiet `rev-parse --verify`, which follows that contract, and `exists_locally` reuses it. Switch base selection and the pre-add branch check propagate failures instead of defaulting to "absent". `wt list` now reports a failed ancestry query alongside its other failed tasks (one snapshot updated). Tests: a switch regression where a failing `rev-parse` must stop creation, and a unit test that a failed ancestry query is not cached. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
56c1b1534c |
Clear repeated Git config values completely (#4566)
`git config --unset` returns status 5 both when a key is absent and when it has multiple values. Worktrunk treats that status as absence, so clearing repeated state values can report success while leaving the values on disk and removing them only from the in-memory cache. Use `--unset-all` in the shared key-clearing helper. Status 5 then means absence, and a successful clear removes every value for the selected key. Add coverage for cached and fresh reads, repeated clears, and both named-variable and `--all` CLI paths. Validation: all three regressions fail before the fix. All 171 focused state, repository-config, and commit-generation prompt tests pass with the fix. The required `cargo run -- hook pre-merge --yes` gate passed in the combined audit checkout: 5,463 tests passed, one skipped, plus formatting, Clippy, lockfile checks, doctests, and rustdoc. The container runner supplied orphan reaping because its PID 1 does not reap children. |
||
|
|
1c6eb9da85 |
Test same-basename trash staging without depending on drain timing (#4561)
The same-basename prune regression assumes each removal creates a separate background-drain log. The removal path intentionally reuses a running drain, so the assertion depends on scheduling and can fail when both worktrees were correctly staged and removed. Move this invariant to the staging boundary: stage two registered worktrees with the same basename, verify that each keeps its registration-derived destination, and verify that both staged directories survive distinctly. Existing integration tests retain command-level prune coverage. No production removal behavior changes. Validation: the replacement test and 886 focused repository, switch, and prune tests pass. The required `cargo run -- hook pre-merge --yes` gate passed in the combined audit checkout: 5,463 tests passed, one skipped, plus formatting, Clippy, lockfile checks, doctests, and rustdoc. The container runner supplied orphan reaping because its PID 1 does not reap children. |
||
|
|
b3d6fd2700 |
Clarify recovery hints and file-operation diagnostics (#4346)
GitHub PR-not-found errors keep the selected repository and its source in the diagnosis, preserve the CLI error, and render `gh repo set-default` as a separate recovery hint. Relocation warnings identify the blocking path and explain that `--clobber` backs it up; config migration hints name the command that applies the updates. Copy and promote failures use the shared path formatter and retain their underlying I/O errors. Failed copies name both source and destination, including when the source is readable and the destination is invalid. Promote recovery commands use shell-quoted paths. Validation: the required local pre-merge gate passes 5,392 tests (one skipped), Clippy, formatting, locked dependencies, documentation and doctests. Focused error-path tests check quoted paths, destination context and retained I/O causes; command snapshots cover the recovery hints. Independent review found no remaining issues. Remote patch coverage is 90.06% (136/151 lines) against a 98.55% gate. The 15 misses are existing filesystem-failure paths whose diagnostic formatting changed; exercising most would require races, fault injection or special permission/ownership fixtures. The maintainer approved landing with this coverage gap and the independent subagent review after the automated review job completed without posting a verdict. Linux, macOS and Windows CI, including all advisory affected-tests jobs, passed. > _This was written by Codex on behalf of max-sixty_ --------- Co-authored-by: worktrunk-bot <worktrunk-bot@users.noreply.github.com> |
||
|
|
93beb0670d |
fix: return one complete JSON result for switch (#4345)
JSON switches now emit one result after synchronous work, including any --execute command, finishes. Accepted invocations return the existing success fields, or an object with an `error` string when target discovery, configuration, directory directives, or execution fails. Execute output goes to stderr, and child errors retain exit and signal metadata. Typed Git diagnostics retain captured Git details and recovery hints, including commands for a branch left behind after failed worktree creation. Argument errors and picker cancellation produce no JSON; background hooks remain independent. Validation: the full project gate passed (5,028 tests, one skipped), plus focused checks covering early and late failures, child output and signals, picker behavior, and plain output. Generated help, documentation synchronization and build, and independent review passed. The change also removes a synthetic stdin write from an existing noninteractive alias-refusal test that raced with process exit. > _This was written by Codex on behalf of max-sixty_ --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
3ec0bf71a1 |
fix(remove): recheck cleanliness after stopping the fsmonitor daemon (#4456)
Removal's dirty-worktree gate runs before wt stops the fsmonitor daemon, since the daemon answers that `git status` cheaply. A file written while the daemon shuts down therefore reached the rename unchecked. With `core.fsmonitor` configured, removal now runs the gate once more after the stop, with fsmonitor disabled, which rescans without starting a new daemon in the worktree about to go. The first gate stays, so a dirty worktree is still refused off the daemon's answer with its daemon left running. Under fsmonitor the post-stop rescan is what a clean removal passes: one full re-stat per removal there, which also makes `wt` stricter than `git worktree remove` against a stale daemon answer. Without fsmonitor nothing changes. `--force` skips both gates, as before. This narrows the earlier version of this PR, which bypassed fsmonitor for every removal and stacked on #4454; it now targets `main` on its own. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
ab2a1e3a2e |
fix(remove): warn when a submodule holds commits on no remote (#4460)
Removing a worktree deletes its submodules' module stores, and with them any commit no remote-tracking ref reaches, including reflog-only ones. Removal now warns before proceeding: ``` ▲ Submodule submod has commits on no remote; removing the worktree deletes them ``` It still removes, so shallow or SHA-fetched pins (which can look the same) never need `--force`. `--force` skips the check, having already consented to losing what the worktree holds. The picker removes silently, as it does for everything else. This replaces the earlier refuse-unless-`--force` version of this PR, per the decision to warn instead. The test-only commit routing `GIT_EXEC_PATH` to Git's real exec path is kept, since `git submodule` needs Git's helpers when wt runs as `git wt`. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
af3c278fa9 |
fix(remove): stop suggesting -D when refusing to remove the default branch (#4535)
`wt remove main` refuses with `Cannot remove the default branch main`, then hinted `To force-delete, run wt remove -D main`, pointing at the one outcome the guard exists to prevent. The refusal now stands alone; `-D` still bypasses the guard for anyone who means it. This replaces #4455, which would have let `--no-delete-branch` remove the default branch's worktree; the guard stays as it is. > _This was written by Claude Code on behalf of max-sixty_ Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
a4a3063c71 |
test(remove): retry the drain when a forked child still holds the trash lock (#4530)
The nightly `feature-powerset` job [failed](https://github.com/max-sixty/worktrunk/actions/runs/39376521570) in `git::remove::tests::drain_trash_deletes_staged_entries_once_the_lock_is_free` (added in #4516) with `assertion failed: staged_trash_entries(&trash).is_empty()`. This is a race in the test, not a bug in the drain. After the test drops its lock holder, it expects the next `drain_trash` to get the lock. But another test in the same process can fork a child while the holder is open. That child inherits the descriptor, and the flock stays held until it execs. The drain sees `WouldBlock` and exits, leaving the deletion to the holder, as designed. `test_configure_shell_opens_rc_with_exclusive_lock` has the same race on the rc-file lock. Both tests now wait for the release through the shared `testing::wait_for` helper. It polls with a bounded timeout and stops at the first success, so on Windows the test never asks a handle that already holds the lock to take it again. Verification: I reproduced the race with a scratch test that ran the same lock/release/drain sequence 2000 times while four threads spawned `true` in a loop. The first drain left the entry behind in 17–20 of the 2000 iterations. With the retry, no iteration left it. Both tests pass locally, and clippy is clean. The same window exists in production, but it only delays cleanup: a staged entry waits in the trash until the next removal's drain. The doc comment on `trash_drain_running` already accepts a similar window, so this PR doesn't change the drain itself. Refs #4509 --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
0559edce3b |
fix(signals): stop foreground loops when wt itself receives Ctrl-C (#4533)
## What regressed Since v0.80.0, Ctrl-C during `wt remove a b c` no longer stops the batch when the pre-remove hook catches SIGINT and exits normally, as pre-commit does (`trap '...' INT; exit 130`). Reproduced with a hook that traps INT, exits 130 and otherwise sleeps, plus a process-group SIGINT: v0.80.0 stops at `a` and keeps every worktree; current main removes `b` and `c`, branches included, and runs their hooks. `wt step prune` did the same with a hook that exits 0 after catching the key: every candidate was removed and wt exited 0. Two changes combined. #4400 moved foreground children into the caller's native job group and followed the shell's wait-and-cooperative-exit rule, so a child that handles the key keeps its own exit status. #4357 made a multi-target remove continue past a failing target. ## The rule Max chose the batch-runner convention (make, ninja, cargo) over the shell's: Ctrl-C that wt itself receives stops the current command. The terminal delivers SIGINT to the whole foreground job, so wt receives the key alongside the child. A shell waits and exits only if the child died of the signal, because the child might be an interactive program using Ctrl-C as input. A batch runner's steps aren't interactive, and the user pressing Ctrl-C means "stop the batch". For a destructive loop like remove or prune, that rule is also the one the data-safety principle asks for. The child still handles the key its own way, and wt never signals it for INT. Once the child exits, the command starts nothing more and exits interrupted (native SIGINT re-raise / 130), whatever status the child chose. Numeric exit codes such as 130 are still never read as cancellation; wt's own receipt is the evidence. ## What changes - `src/signal_forwarder.rs`: the existing per-operation cancellation (`CommandOperation`) gains a SIGINT flag beside its SIGTERM one. Foreground scopes register it, so the scope reports cancellation when its child exits, and later admissions in the same command are refused. The output drain's fresh flag, which existed to ignore keys the children had already handled, is gone. - Covered loops: hook pipelines (including Warn-strategy post-* hooks), multi-step aliases, `for-each`, multi-target `remove` and `prune`. - A command's final interactive child keeps the key as input and its own exit status: help and `config show` pagers, `--execute` programs and custom `wt-*` subcommands opt in through `Cmd::hand_off_terminal` (`TerminalInterrupt::ChildInput`). So does an alias's last serial step (`ForegroundStdin::HandOff`), since the alias is the whole command; `agent = "claude"` keeps claude's status after the user stops a turn with Ctrl-C. Otherwise pressing Ctrl-C in `less`, a REPL started by `-x` or such an alias, then quitting normally, would turn into exit 130. Earlier alias steps, concurrent groups and every hook step still cancel. - Unchanged: between children, idle SIGINT still kills wt natively. Detached background hooks, timeout-bounded captures in their own process group and the picker hold no foreground scope. A SIGINT sent only to wt is still not forwarded to the child; wt waits for it to finish, then stops. Windows is unchanged: wt installs no console Ctrl-C handler, so the default handler already ends wt and nothing more starts. - AGENTS.md "Signal Handling" and the `signal_forwarder` / `shell_exec` / `concurrent` module docs state the new rule. ## Verification - New unix integration tests, each pressing Ctrl-C (a group SIGINT) after wt has admitted a child that catches it: `remove` with a hook exiting 130 and with one exiting 0 keeps both targets; a post-start pipeline doesn't run its next step after a step exits 130; `for-each` visits one worktree when the child exits 0. All four fail on the old semantics. `test_alias_last_step_keeps_status_after_caught_ctrl_c` covers the alias handoff. The exit-0 remove case also fails if the scope stops reporting the latch and only refuses later admissions, since the current target would still be removed. - Existing tests that asserted the old rule now assert cancellation: the PTY `caught_keyboard_interrupt_cancels_following_step`, `test_alias_pid_signal_policy` (PID-only INT) and `test_alias_group_sigint_does_not_escalate`. The children still handle every key exactly once and wt never dies while they run. `test_alias_caught_sigint_preserves_successful_descendant_output` is deleted because its premise is the old rule. The pager and custom-subcommand cases in `custom_commands_and_help_pagers_preserve_native_signals` pass unchanged. - The alias signal harness moved to `tests/common` as `SignalJob` for reuse. - `cargo nextest run --all-features` (5377 passed), `cargo clippy --all-targets --all-features -- -D warnings`, pre-commit on the changed files. Manual repro of remove and prune before and after. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
a4573593db |
fix: resolve every no-argument default through @, which outside a worktree names HEAD's branch (#4521)
Since v0.80.0, `wt switch @` run outside any worktree treats the directory it runs in as a detached worktree. This happens from a bare repository's directory (or the `proj/` holding `proj/.git` → `.bare`) and from a normal repository's `.git` directory. It prints `Already on worktree for detached worktree @ <dir>`, runs pre-switch hooks with no branch, and cds into the directory. v0.80.0 switched to the worktree of the branch HEAD names. #4496 routed `wt switch` arguments through `Repository::resolve_worktree`. Its `@` arm expected `current_worktree().root()` to fail outside a worktree, but `WorkingTree::root()` falls back to the cwd. `@` now resolves to the registered worktree at the cwd's root and, where none is registered, falls through to the branch HEAD names, as `expand_selector` already reads `@`. The unreachable `GitError::NotInWorktree` is removed. ## One definition of the current worktree The no-argument forms of other commands read `current_worktree().root()` and `.branch()` directly, so "the current worktree" had a second definition, and outside every worktree the two disagreed: `wt remove` and `wt remove @` took different code paths and gave different answers. Every no-argument default is now `selector.unwrap_or("@")`, so each command has one path with or without an argument: - `wt remove` with no argument goes through `validate_remove_targets` with `["@"]`. Its separate single-target path is gone, and so is the `@` guard an earlier commit on this branch added beside it. - `CommandEnv::for_action` and `for_action_loading_config` are deleted. `wt merge`, `wt step commit`, `wt step squash` (including `--show-prompt` / `--dry-run`), `wt hook` and `wt hook show` use `CommandEnv::for_selector("@")`. - `wt step diff` resolves `@` the way it resolves `--branch`. - `wt step copy-ignored` defaults `--to` to `@`. Run from a bare repository's directory, it used to copy ignored files into the bare repository itself (in v0.80.0 too). - `wt config state` and `wt step push --no-ff` use `require_selected_branch("@")`; `Repository::require_current_branch` is deleted. Inside a worktree these commands behave as before. `Repository::rooted_at` keeps the invoking repository when the selected worktree is the one it was discovered in, and `@` matches the worktree by path, so detached worktrees and duplicate checkouts of one branch resolve to themselves. `require_selected_branch` no longer names the detached worktree the user is standing in: `wt config state vars set` there says `Cannot set variable: not on a branch (detached HEAD)` with a plain `git switch <branch>` hint. ## Behavior change outside a worktree From a bare repository's directory or a `.git` directory, `wt remove`, `wt merge`, `wt step commit`, `wt step squash`, `wt step diff` and `wt hook` now act on the worktree of the branch HEAD names, where they used to treat the directory itself as a worktree. `wt config state … --branch @` and `--to @` act on HEAD's branch there too. For `wt remove`, the default-branch refusal is what guards this case: with HEAD on the default branch, `wt remove` and `wt remove @` both refuse with `Cannot remove the default branch main`. It only protects HEAD's branch when the cached default branch matches HEAD. Where HEAD's branch has no worktree, the commands that need a worktree fail with `Branch <name> has no worktree`, and `wt remove` deletes the branch alone if it is integrated. The fall-through applies only outside every work tree. Inside a work tree git doesn't have registered at that path, such as a worktree moved without `git worktree repair`, `@` still names the directory, so `wt remove` there refuses with `No worktree @ <dir>` rather than pruning the branch's stale registration. ## Verification The release review's scripts, rerun against main, v0.80.0 and this branch, show `wt switch @` from `proj/`, `proj/.bare` and `repo/.git` again landing in the HEAD branch's worktree, with pre-switch hooks seeing that branch and path. New or changed integration tests, each of which fails without its fix: - `test_switch_at_outside_a_worktree_names_the_head_branch`: `wt switch @` from a `.git` directory. - `test_bare_repo_at_from_bare_directory_names_head_branch`: `wt switch @` and `wt step copy-ignored` from a bare repository's directory. - `test_bare_repo_remove_from_bare_directory_targets_head_branch`: `wt remove` and `wt remove @` give identical output there and refuse as default branch. - `test_bare_repo_previews_from_bare_directory_use_head_branch`: `wt hook show` and `wt step squash --show-prompt` read HEAD's branch's worktree, not the primary one. - `test_remove_no_argument_in_moved_worktree_refuses`: `wt remove` from a moved worktree refuses and leaves its checkout intact. - `test_vars_set_in_detached_worktree`: the detached-HEAD message for the no-argument form. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
1fe07b3145 |
fix(switch): refuse --path naming the bare repository; drop rm -rf hint for --path (#4532)
Two problems with the new `wt switch --path` flag from #4317, found in release review. **Bare repository moved aside.** `wt switch --create x --path proj.git --clobber` in a bare clone with no worktrees printed `Moved ~/proj.git to ~/proj.git.bak.<ts> (--clobber)` and created a worktree in the repository's place. `reject_path_overlapping_worktrees` skipped a requested path equal to any entry it checks, which is right for a registered worktree (`validate_worktree_creation` reports it by branch) but nothing later checks the git common dir. The guard now refuses that case with `--path <dir> is the repository's git directory`. The template route has the same exposure and is left to #4461; this guard runs only for `--path`. While there, the guard compares paths with `canonicalize_with_parents` rather than `dunce::canonicalize`, so a deep Windows path and the short root containing it get the same prefix spelling for `starts_with` (the #3898 mismatch). **`rm -rf` hint for a user-named directory.** When the `--path` directory exists, the hint suggested `rm -rf <path>`, though `--path` can name any directory, such as a project. For `--path` it now reads `To place the worktree elsewhere, choose a different --path; to overwrite (with backup), run wt switch --create --clobber <branch> --path=<path>`. The template route's hint is unchanged. **Verification:** reproduced both on a build of `main` and confirmed the fix on this branch. `test_bare_repo_switch_path_rejects_the_repository` fails with the old guard (its snapshot shows the `Moved … (--clobber)` line), and the `switch_path_occupied` snapshot shows the new hint. `test_switch_path_naming_another_worktree` pins that `--path` naming another branch's worktree, with `--clobber`, still reports that worktree's branch and leaves it in place. Ran the switch, bare-repository and error-display integration tests, clippy, and pre-commit. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
15b1ed10ce |
fix(config): keep approvals and [projects] entries saved under v0.80.0 identifiers (#4526)
Since v0.80.0, #4421 changed the project identifier for three kinds of remote: a non-default SSH port joins the host (`host:2222/o/r`, was `host/o/r`), hosts are lowercased (`github.com/o/r`, was `GitHub.com/o/r`), and `git+ssh://` / `ssh+git://` URLs parse (`github.com/o/r`, was the raw URL). Approvals and `[projects."…"]` settings saved under the old identifier silently stopped applying. A non-interactive `wt switch --create` then failed with "Cannot prompt for approval" for hooks the user had approved, and ignored the project's `worktree-path`. `Repository::project_identifier` now returns a `ProjectId` that carries the current identifier plus, where it differs, the identifier v0.80.0 computed for the same remote. `legacy_project_identifier` in `src/git/url.rs` is a frozen copy of the pre-#4421 rule. It returns nothing for an `ssh://` IPv6 remote, whose v0.80.0 identifier (`[2001/o/r`) collided across distinct hosts. `matching_keys`, the one matcher behind both approvals and `[projects]` settings, also matches keys against the legacy identifier and ranks them below every key matching the current one. Settings under a current key override legacy ones field by field. Approvals under either key apply, so approving a new command (saved under the current identifier) keeps the earlier approvals in force without any migration. The per-project `wt config approvals` operations (stale approvals in `list`, `clear`, `clear --stale`) treat the legacy exact key like the current one. Writes and the displayed identifier stay on the current identifier. Most of the diff is the read APIs switching from `&str` to `&ProjectId`. For the port case this restores v0.80.0's sharing. The legacy key `host/o/r` is also the live key of the same project on port 22, so a repo on `host:2222` reads approvals and settings saved for the port-22 remote, including ones saved after upgrading, and clearing from it removes them. #4421 had separated those; telling old entries from new ones would need provenance in `approvals.toml`, which this PR doesn't add. Keys written under `host:2222/o/r` apply only to that remote. Verification: I reproduced the regression with the v0.80.0 and main binaries for all three remote forms, using approvals and `worktree-path` keyed under the old identifier. On this branch, `wt switch --create` (stdin closed) runs the approved hook in the legacy `worktree-path` again, as on v0.80.0. New tests: an integration test running `wt switch --create` with a case per remote form, an updated identifier-selection test, and unit tests for the legacy derivation, ranking and clear. The integration tests fail when the legacy identifier is withheld. Lib and bin tests, the approval, config, hook, merge and prune integration tests, clippy, rustdoc and pre-commit pass. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
4874f33c29 |
fix(alias): report an alias child killed by a signal other than INT/TERM (#4523)
Since v0.80.0, an alias whose child dies by a signal other than SIGINT/SIGTERM (for example `crash = "kill -KILL $$"`, or a segfaulting program) exits 128+N with no output. v0.80.0 printed `✗ Killed by signal N`. #4352 and #4400 limited interrupt classification to SIGINT/SIGTERM, so these deaths now reach `alias_error_wrapper`, which turns every child exit code into a silent `AlreadyDisplayed`. wt exits normally rather than dying by the signal, so the shell reports nothing either. `alias_error_wrapper` now maps a child exit with a physical signal to `WorktrunkError::Interrupted`, the variant custom subcommands (`wt-foo`) already use for the same case. It renders `Killed by signal N` and exits 128+N. SIGINT and SIGTERM still short-circuit earlier and are re-raised for the shell to report, as AGENTS.md "Signal Handling" specifies, so `kill -TERM $$` stays silent from wt. Hooks and `wt step for-each` already report the signal in their own failure lines and are unchanged. Verified with the release-review repros: SEGV and KILL aliases print `✗ Killed by signal 11` / `9` and exit 139 / 137, matching v0.80.0, for single, multi-step and concurrent aliases; `exit 2` stays silent. The new unix-only `test_step_alias_killed_by_signal` snapshot fails without the fix. > _This was written by Claude Code on behalf of max-sixty_ Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
25d0c44b0b |
fix(remove): drain the trash with one background process per repository (#4516)
A prune of many worktrees started one `rm -rf` per staged worktree. On a 193-worktree prune those processes competed for the disk: together they deleted about 1,500 files/s on 3 cores, while a single `rm` alone managed 3,000–5,400 files/s on under one core. Read-only directories (`dr-xr-xr-x`, as installers leave them) also made `rm -rf` fail, so those entries stayed in `.git/wt/trash/` and every later sweep retried them. Removal now starts a hidden `wt _drain-trash`, which holds `.git/wt/trash.lock` and deletes every staged entry, including entries staged while it runs. A removal or sweep that finds the lock held starts nothing, so a prune runs about one deleter. The sweep after `wt remove` drains leftovers immediately rather than waiting 24 hours. Priority is unchanged (`taskpolicy -b` on macOS). The drain uses wt's own walker (`src/remove_dir.rs`), which `wt remove --foreground` and `wt config state clear` also use: - On Unix it opens each directory relative to its parent's descriptor with `O_NOFOLLOW` and unlinks relative to the holding directory. The old path-based walker could follow a directory swapped for a symlink mid-walk and delete outside the tree; a swap-race script reproduced that, and the new walker lost nothing in 20 runs. - It grants the owner `rwx` on each directory it enters, so read-only and unreadable trees are deleted, never changing a symlink's target. Linux's `fchmodat` has no `AT_SYMLINK_NOFOLLOW`, so there it opens the directory with `O_PATH | O_NOFOLLOW` and changes the mode through `/proc/self/fd`. - Subdirectories are removed sequentially, so open descriptors stay bounded by depth. On a 199k-entry pnpm `node_modules` it deleted about twice as fast as `rm -rf`. - On Windows it uses `std::fs::remove_dir_all`, which removes junctions without following them. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
55d302dbb2 |
fix(switch): return wt switch - to the worktree it left, not the first checkout of its branch (#4497)
|
||
|
|
0c75655c6c |
fix: resolve worktree arguments once and pass the resolved worktree through (#4496)
Follow-up to the survey on #4493. Several commands resolved a worktree argument, kept only the branch or only the path, and looked the other half up again. Each re-lookup could disagree with the first. This resolves the argument once and passes the resolved worktree through. | Case | Before | After | |---|---|---| | `wt switch origin/feature` (`feature` has a worktree) | pre-switch hook got `branch=origin/feature` and no `target_worktree_path` | hook gets `branch=feature` and the worktree path | | `wt step promote <second copy>` of a branch checked out twice | acted on the first copy, failed partway, left the main worktree and that copy detached | refuses before touching anything, listing both checkouts | | the same with no argument from the second copy, or with the default branch checked out twice | same partial failure | same refusal | | `wt switch @` from a second copy or a detached worktree | landed in the first copy, or errored | `already_at` the current worktree | | bare-repo worktree-path warning for `@` / `-` / `pr:N` | skipped through a hand-kept list of shortcuts | names the branch the shortcut resolves to; the list is gone | ### `wt switch` `SwitchTarget` holds the resolved destination (an existing worktree, or a branch to create one for) plus the forge's answer for `pr:`/`mr:`. The bare-repo warning, the pre-switch hooks, and `plan_switch` all read it, so the hooks no longer run their own copy of resolution. Arguments other than `pr:`/`mr:` and `--create` names go through `Repository::resolve_worktree`, which is what makes `@` resolve by path; the remote-prefix strip applies to a `BranchOnly` result. A pre-switch hook can change what the argument names: the fetch-if-stale hook the docs suggest makes a remote-only branch appear. So when a hook actually ran (`execute_hook` now reports whether one did), the pipeline locates the argument again through the same `SwitchTarget::locate`, on a fresh `Repository`, and plans against that. The forge is not queried twice. `--base` and `--create` validation still run after the hooks. Two behaviour changes follow. Naming errors (`wt switch -` with no history, a path holding no worktree) now fail before the pre-switch hooks run rather than after. And when a hook ran, the rest of the switch reads repository state as the hook left it, `.config/wt.toml` included. ### Promote and the other `--branch` callers `Repository::require_worktree` returns the branch along with the path, so `CommandEnv::for_selector`, `copy-ignored`, and promote use the resolved pair instead of looking one up from the other. Promote resolves every route (argument, `@`, `^`) to a worktree and refuses when either branch is checked out more than once. ### Not covered `wt switch -` still records the previous location as a branch name, so it can't return to the second copy of a duplicated branch or to a detached worktree. Changing what the history records is a separate change. ### Testing New integration tests cover each row above, plus a pre-switch hook that fetches, with both `late` and `origin/late`. The hook-fetch tests also pass on `main`; they pin the behaviour that resolving before the hooks could break. Every other new test fails on `main`. The full pre-merge gate passes locally. Codex and a separate Claude agent reviewed it, the latter twice. > _This was written by Claude Code on behalf of max-sixty_ Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
4416f64e46 |
Honor resolved paths and forge settings (#4495)
Several paths reconstructed default values instead of consuming the configured or server-provided result. This could configure an unusable fork push URL, recommend editing the wrong zsh file, or report misleading worktree information. - Preserve Gitea's API clone URLs for fork pushes and missing-remote suggestions, including HTTP schemes, ports, and deployment paths. - Scope GitHub and GitLab protocol lookups to the selected host. - Name the resolved zsh configuration path and selected command in compinit advice. - Compare prune candidates through project-config resolution, so shared absolute overrides do not falsely imply different hooks. - Deduplicate statusline branches only when a linked checkout still matches its configured path and its displayed directory contains the branch. Main checkouts and checkouts whose branch has drifted from the configured path retain the branch label. The audit followed the default-template assumption fixed in [#4491](https://github.com/max-sixty/worktrunk/pull/4491). Validation: regression coverage for the affected checkout, shell, prune, and statusline behavior; the project pre-merge gate; and independent code review with live CLI checks of custom directory names and ZDOTDIR installation. > _This was written by Codex on behalf of max-sixty_ |
||
|
|
a633331f42 | chore: correct stale help-rendering docs and drop an unused table indent parameter (#4484) | ||
|
|
3e17648ae4 |
Preserve native Git paths and pass removal arguments without shell interpolation (#4453)
Lossy path decoding and shell interpolation can change the filesystem target. Preserve native Git paths, carry native argv through the existing command runner, and pass cleanup paths as positional arguments to fixed scripts. Remove the path-conversion errors and duplicate detachment code. Use the existing Rust branch-deletion logic in the detached fallback, replacing the shell topology parser. Capture the invoking target and expected tip before scheduling; recheck live checkout ownership before deleting. This incorporates and supersedes https://github.com/max-sixty/worktrunk/pull/4462. Validation: 272 focused tests pass under Rust 1.98. Claude reviewed the source; its technical findings are addressed, with the follow-up reviewed independently by Codex. > _This was written by Codex on behalf of max-sixty_ |
||
|
|
f98bd11816 |
fix(list): leave CI blank when the forge CLI isn't logged in (#4449)
Since #4436, any failed forge call shows ⚠. That includes a CLI that is installed but not logged in, which then puts a permanent ⚠ in `wt list --full`, the shell prompt, and the Claude Code statusline. This change leaves the cell blank when the CLI holds no login for the forge's host, and keeps ⚠ for a failure from a CLI that does (offline, rate limit, expired token). Each CLI answers from its own local state, so a lost connection never reads as logged out: - **GitHub**: `gh` exits with its documented code 4 when it has no login for the host it resolved for the request. The backend reads that exit code, so SSH host aliases resolve the way `gh` resolves them. - **GitLab / Gitea / Azure DevOps**: after a failed call, `remote_ref::is_authed_for(forge, host)` asks `glab config get token --host`, `tea logins list --output json`, or `az account show`, for the `forge.hostname` if configured, else the remote's host. The answer is cached per forge and host for the process. `wt config show --full` uses the same check for the repo's host and names that host in its warning. It replaces `CiToolsStatus`, which probed all four CLIs to report one, and asked `gh auth status` / `glab auth status`, which contact the server and accept a login for any host. `tea`'s host-agnostic `has_any_login` is gone with it. Behavior changes: - `wt list --full` / statusline: a CLI with no login for the host leaves the CI cell blank instead of ⚠. The legend now lists that under blank, and ⚠'s examples say "expired login". - `wt config show --full`: a login for another host no longer counts, and the warning says which host it checked (`gh installed but not authenticated for github.com`). Known limits: a GitLab or Gitea remote through an SSH host alias is checked under the alias, so a failure there shows blank unless `forge.hostname` names the real host; Azure DevOps counts only an `az login`, not a PAT from `az devops login`. Tests: the failed-list test now covers logged-in and logged-out cases for `gh` (exit 1 vs 4) and `glab` (token vs none); the `tea` CI mocks hold a login for the test host; the `tea` login-discovery test adds a login for another host. Follows #4436. > _This was written by Claude Code on behalf of max-sixty_ Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
397136ea31 |
refactor: stop refining failed forge calls and missing nu/pwsh (#4436)
Applies `AGENTS.md`'s **Other Tools Own Their Conventions** (#4435) to what #4106 left: where worktrunk refined how it handles a case outside standard use, stop handling the case. **CI status: a failed forge call shows the error indicator.** The classifier that searched `gh`/`glab`/`az`/`tea` output for English phrases ("rate limit", "403", "connection", …) to choose between ⚠ and a blank "no CI" cell is deleted. Any failed call now shows ⚠. Gitea reads only whether the HTTP status is an error, not which one. The two lookups by commit SHA (GitHub check runs, Gitea combined status) now run only when some remote-tracking ref contains the head, since the forge answers a commit it doesn't have with an error and ordinary unpushed work would otherwise show ⚠. GitLab and Azure look pipelines up by branch and are unchanged. **PowerShell on Unix.** When `pwsh` can't be queried there is no PowerShell profile, rather than a guessed `~/.config/powershell` one (left by #4422). **Nushell.** When `nu` can't be queried there are no autoload candidates, rather than a reconstruction of Nushell's data-dir rule. Install can't write into a legacy directory, since the candidate list is empty. Behavior changes: - `gh`/`glab`/`az` installed but not logged in now shows ⚠ under `wt list --full` instead of a blank cell. Detection checks that the tool is installed, and `wt config show` reports that it isn't logged in. The ⚠ legend now names "not logged in". - A Gitea 404 shows ⚠. - `wt config shell install powershell` (or `nu`) without the tool fails with "No shell config files found", and uninstall no longer finds a wrapper left behind after `nu` was removed. **Fish's completion path.** `Shell::completion_path` answered for every shell, but only fish installs a completion file; its other arms, including the Nushell one this change touched, were dead. `shell::fish_completion_path` replaces it. Tests: the retriable-classifier unit tests are gone, and the Gitea test that only distinguished a blanked 500 body. Mocks now answer for branches other than the one under test, since those would otherwise show ⚠. New tests: a failed `gh pr list` / `glab mr list` shows ⚠; an unpushed head skips the GitHub and Gitea lookups by SHA, each with a pushed control. Shell unit tests and the PowerShell integration tests no longer depend on a real `nu` or `pwsh`; they pass with only `/usr/bin:/bin` on `PATH`. Full integration and unit suites pass locally. Ref #4106. > _This was written by Claude Code on behalf of max-sixty_ --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> |
||
|
|
59501986af |
fix: parse remote URLs with gix-url so IPv6 hosts and SSH ports get distinct project identifiers (#4421)
`GitRemoteUrl::parse` split SSH authorities at the first `:`, so `ssh://git@[2001:db8::1]/owner/repo.git` and `ssh://git@[2001:db8::2]/owner/repo.git` both became `[2001/owner/repo`. Because that identifier selects both saved approvals and `[projects]` settings, the two servers shared them. The parser also dropped explicit SSH ports, merging servers on different ports. The parser now delegates transport syntax to `gix-url` 0.40, and the identity keeps the full IPv6 host and any non-default SSH port. What changes: - **Syntax from `gix-url`.** It handles scheme, SCP form, userinfo (split at the final `@` of the authority, which is the host git connects to), IPv6 literals and ports. Worktrunk still owns the namespace/repo split and the forge policy. HTTP(S), git and SSH remotes are accepted, plus SCP when it has a non-empty user (the existing rule). Remote helpers, `file://`, local paths, option-like hosts and out-of-range ports are rejected. - **Escaped paths.** The path comes from `original_path()`, not the decoded `path`, so `evil%2Frepo` stays a single segment in SSH, SCP and git forms, as it already did for HTTPS. - **IPv6 hosts** are always bracketed (`[2001:db8::1]`), since `gix-url` strips the brackets for SSH but keeps them for HTTP(S). - **SSH ports.** A new `ssh_port` field goes into `project_identifier()` (`host:2222/owner/repo`) but not into `host()`, which feeds web and API URLs; an SSH port is not the web port. An explicit `:22` is treated as no port. HTTP(S) and git keep their explicit port in `host()`, as before. - **No new identity API.** `project_identifier()` is still the only identity; there is no separate one. Approvals and settings: the ordinary forms of one project still share an identifier (`git@host:o/r`, `ssh://git@host/o/r`, `ssh://git@host:22/o/r`, `https://host/o/r`). Corrected identities get fresh keys, so old IPv6-truncated or port-merged approvals don't carry over. The same applies to `[projects]` settings: a user on `ssh://…:2222` with a `[projects."host/o/r"]` entry needs to re-key it to `host:2222/o/r`. Nothing warns about this. The config docs now say that a non-default port stays with the host. Smaller identifier changes from delegating normalization: - DNS-style hostnames are lowercased (`GitHub.com` → `github.com`). - `git+ssh://` and `ssh+git://` now parse; before, they fell back to the raw-URL identifier. - Some inputs `gix-url` rejects now fall back to the raw-URL identifier in `Repository::project_identifier`: URLs containing whitespace, and SCP `user@[ipv6]:path`. Each still gets a distinct identifier. Tests: - New unit tests cover the IPv6 collision, port isolation (including a port inside hostile userinfo), escaped paths across transports, and rejected forms. - `tests/integration_tests/repository.rs` checks that `Repository::project_identifier` keeps the two IPv6 remotes apart. It also checks that `Approvals::is_command_approved` and `UserConfig::worktree_path_for_project` pick the right entry for port 2222 versus the shared SSH/HTTPS identifier. - The full lib and integration suites pass locally, except for tests that bind Unix sockets or sign commits. Those fail the same way on `main` in this sandbox. - Binary size was not measured; the issue's ~84 KiB figure is a standalone probe. Closes #4418 — automated triage --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
6b0f8e2bdb |
fix(shell): discover the Unix PowerShell profile from the installed pwsh (#4422)
On Unix, shell installation now asks the installed PowerShell runtime for `$PROFILE.CurrentUserCurrentHost`, so a custom `XDG_CONFIG_HOME` selects the profile PowerShell actually loads. Install, uninstall and configuration detection share the cached result. The local query uses `-NoProfile`, disables telemetry and update checks, and uses the existing five-second probe timeout. Missing, failing or invalid runtime output retains the conventional fallback. Windows continues to use the known Documents folder candidates for both PowerShell editions. Native SIGINT/SIGTERM cancels installation before profile writes, including when descendants keep the probe's output pipes open. The shared timed-command primitive now observes the child's native terminal status without reaping its leader until process-group teardown completes, preserving the existing process-ID safety guarantee. Typed interruption also propagates through diagnostics, switch/remove warnings, and installation offers before another probe or hint mutation starts. Validation covers custom-XDG installation and removal, malformed/unavailable runtime fallback, native interruption versus ordinary exit 130, pipe-holding descendants, bounded timeouts, and real pwsh profile discovery without executing user profiles. Regression tests exercise both the shell-installation flow and the shared timeout primitive. An obsolete profile previously written under `~/.config` while a custom XDG location was active is no longer an install/uninstall candidate; PowerShell did not load it, and treating it as configured would preserve the original bug. Closes #4419. > _This was written by Codex on behalf of max-sixty_ --------- Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
074a925612 |
fix: delegate tea login discovery and preserve settings key order (#4420)
Delegate tea login discovery to its local `logins list --output json` command, replacing Worktrunk's YAML scanner and platform-specific config-path guesses. Forge routing matches both web and SSH hosts; diagnostics share the same probe. Native cancellation stops subsequent probes, while ordinary command failures retain the existing unauthenticated fallback. The local-only command was also checked with real tea v0.12.0. Preserve existing JSON object order when installing the Claude statusline, including nested settings. Generated schemas and documentation retain canonical sorting; command JSON snapshots now follow construction order, with unchanged values. Regression coverage includes login discovery, routing, cancellation, and settings key order. Ref #4106. > _This was written by Codex on behalf of max-sixty_ |
||
|
|
8423f3c67e | fix(config): read a git config key with no value as true (#4314) | ||
|
|
c388ec375e |
fix(test): gate the highlighted hook-template snapshot on syntax-highlighting (#4427)
The nightly `feature-powerset` job ([run 38115848986](https://github.com/max-sixty/worktrunk/actions/runs/38115848986)) fails in `cargo test --no-default-features` on `git::error::tests::snapshot_worktrunk_error_display`. #4352 added a case to that test where an unnamed hook failure renders its template (`echo test`) through `format_bash_with_gutter`. That output is only highlighted when the `syntax-highlighting` feature is on, so without default features the snapshot gets plain `echo test` and doesn't match. This change moves that case into its own test, `snapshot_unnamed_hook_failure_shows_template`, gated on `#[cfg(feature = "syntax-highlighting")]`. `snapshot_worktree_creation_failed` in the same module is already gated this way for the same reason. The other assertions in `snapshot_worktrunk_error_display` still run in every feature configuration. This only changes tests. Verification: `cargo test --lib --no-default-features snapshot_worktrunk_error_display` failed before the change and passes after it. With default features, both tests pass. `cargo fmt --check` and `cargo clippy --lib --tests --no-default-features -D warnings` are clean. Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com> |
||
|
|
689bab3d3e |
Name undefined template variables and suggest corrections (#4350)
A hook containing `{{ brnch }}` names the undefined variable, shows its
source line, and suggests `branch`. MiniJinja's failing expression span
selects the reached output; compound expressions, nested values and
locally bound names retain a general diagnostic when the missing input
is ambiguous. Preflight validation uses MiniJinja's undeclared-variable
analysis and accepts engine globals.
Config migration and diagnostics share the existing AST visitor, and
similarity suggestions have one shared implementation. MiniJinja stays
on 2.x (minimum 2.24); compiled source-span support leaves the
environment's runtime debug defaults unchanged.
Custom filters now reject undefined inputs instead of silently
converting them to empty strings. This includes an absent optional
value, such as `upstream`, passed directly into a custom filter; guard
it or supply a default. Defined non-string values retain their existing
behavior.
The CLI signal matrix also checks that raw SIGTERM from a custom child
reaches the shell as status 143.
Validation: actual Claude full review found no material code downsides.
All 48 defined-input/filter contrasts preserve output, all eight custom
filters reject undefined input, and focused config and CLI regressions
pass. Pinned Rust 1.98 project validation passed: 5,278 tests, Clippy,
formatting, lockfile, doctests and rustdoc (one test skipped). The
hook-error composition snapshot also passes with default features, no
default features, and CLI support without syntax highlighting. The
no-default-features CLI unit suite passes all 1,011 tests; all 11 real
CLI signal cases pass, including raw SIGTERM.
> _This was written by Codex on behalf of max-sixty_
|
||
|
|
5b0930f09b | Add branch-addressed merge with --branch (#4360) |