Skip to content

fix(switch): classify forge-CLI failures by structure, not tool prose - #3595

Merged
max-sixty merged 1 commit into
mainfrom
fix-uninstall-exec-context-adjacency
Jul 25, 2026
Merged

max-sixty merged 1 commit into
mainfrom
fix-uninstall-exec-context-adjacency

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Follow-ups from #3589's audit of brittle string matching, plus one live bug the audit turned up.

Gitea: the error path was unreachable

From tea's own cmd/api.go: runApi never inspects resp.StatusCode — it copies the response body to stdout and returns nil. So tea api exits 0 for 404, 401, and 403, which put the whole 404/401/403 classification behind an if !output.status.success() that those responses never reach. A missing PR surfaced as Failed to parse Gitea API response for PR #N. This may indicate a Gitea API change. The fabricated {"message":"403 Forbidden"} fixtures hid this by mocking an exit code tea does not produce.

The response shape now discriminates — the PR object, or Gitea's APIError body whose message is surfaced verbatim. A non-zero exit means tea itself failed (no login configured, transport error) and keeps the existing cli_api_error path, which shows tea's own stderr.

Azure: the install command, from JSON

#3589 dropped the appended az extension add --name azure-devops because detecting the case needed prose matching. az extension list --output json answers it structurally instead, and the whole az repos command group ships in that extension — so it's a precondition of the call, not one guess among many. The check runs only after a failure, so the happy path pays nothing, and an az that can't answer counts as installed: an unanswered check never becomes an accusation the user would act on.

Statusline detection

is_statusline_configured matched the substring "wt ", which newt status also satisfies. That is not only a wrong diagnostic line — install-statusline early-returns on it, so a foreign statusline made install refuse. It now asks for the adjacent token pair list statusline, which is the actual question and stays agnostic to wt / git-wt / an absolute path.

Worktree removal: comment only

The remaining error.contains("not empty") stays. There is no structured form to recover: the text is git worktree remove's own stderr, so the failure never passes through a Rust io::Error, and remaining_entries can't substitute because permission-denied also leaves entries behind. The comment claiming an io::ErrorKind was lost upstream is corrected.

Testing

Every changed path is covered by an integration test with realistic mocks: the four Gitea tests now mock exit 0 with APIError bodies (gitea_server_error became gitea_request_failed, since a 5xx no longer exits non-zero), the Azure tests mock az extension list on both sides — present, and failing so the check comes back unanswered — and a new install_statusline_foreign_command test asserts a foreign statusline gets replaced rather than mistaken for worktrunk's.

This was written by Claude Code on behalf of max

`tea api` never inspects the HTTP status — it copies the response body to stdout and exits 0 — so gitea.rs's 404/401/403 classification sat behind `if !status.success()` and could never run. A missing PR reached the user as "Failed to parse Gitea API response … may indicate a Gitea API change". The response shape now discriminates: the PR object, or Gitea's APIError body, whose message is surfaced verbatim. A non-zero exit means `tea` itself failed and keeps the existing `cli_api_error` path.

Azure regains the install command for a missing azure-devops extension, from `az extension list --output json` rather than from az's English. The whole `az repos` group ships in that extension, so it's a precondition of the call rather than one guess among many; the check runs only after a failure, and an az that can't answer counts as installed, so an unanswered check never becomes an accusation.

Claude Code statusline detection asks for the `list statusline` token pair instead of the substring "wt ", which `newt status` also satisfies — enough to make `install-statusline` refuse to install over a foreign statusline.

Also corrects the `WorktreeRemovalFailed` comment: the "not empty" match reads `git worktree remove`'s own stderr, so no `io::ErrorKind` was ever lost upstream.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit c136cbc into main Jul 25, 2026
38 checks passed
@max-sixty
max-sixty deleted the fix-uninstall-exec-context-adjacency branch July 25, 2026 10:44
max-sixty added a commit that referenced this pull request Jul 25, 2026
…xtension (#3597)

Two follow-ups from #3595, both in code that talks to a forge CLI.

## Gitea CI status had the same exit-0 blind spot as the switch path

`tea api` never reads the HTTP status — it copies the response body to
stdout and exits 0 — so the `!output.status.success()` gate in
`src/commands/list/ci_status/gitea.rs` never fired for a 4xx/5xx. #3595
fixed this for `wt switch pr:<n>`; the CI-status backend is the second
instance of the same bug.

The commit-status path was the quieter one: every field of
`GiteaCombinedStatus` carries `#[serde(default)]`, so Gitea's `APIError`
body deserialized as `{state: "", total_count: 0}` — an error
indistinguishable from "this commit has no statuses". The PR-list path
was noisier but less harmful: the error body failed to parse and logged
`Failed to parse tea api pulls JSON`, blaming an API change for what was
an API error.

`tea_api_error` now reads the response shape — the `APIError` body,
whose message feeds the existing retriable sniff — and a non-zero exit
keeps meaning what it always meant, `tea` itself failing (transport
error, no login). A proxy's HTML error page stays unclassified, as
before: sniffing arbitrary bodies is the string-heuristic pile this
removes.

## `wt config show --full` reports the azure-devops extension

The whole `az repos` command group ships in that extension, so without
it CI status stays blank however well `az` is authenticated — a
persistent, user-fixable condition, which is what this surface is for.
`azure_devops_extension_installed` (added in #3595) answers it in JSON:

```console
✓ az installed & authenticated
▲ azure-devops extension not installed; run az extension add --name azure-devops
```

An `az` that can't answer counts as installed, so an unanswered check
never becomes an accusation. The `wt switch pr:<n>` bail now uses the
same sentence — one wording for one condition, which is the one-line
change to `switch_pr_azure_extension_not_installed.snap`.

## Testing

The two new Gitea tests were checked against the unfixed source:
reverting `gitea.rs` alone fails both, so they pin the fix rather than
describe it. The two pre-existing retriable tests kept their exit-1
shape but lost their fabricated payload — `exit 1` alongside `429 Too
Many Requests` is the combination `tea` can't produce — and now carry a
real transport error, which is the case that does exit non-zero. `config
show --full` gets a case per extension state.

> _This was written by Claude Code on behalf of max_

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Jul 25, 2026
Follow-up to #3600, independent of it (no shared files).

GitHub and GitLab rewrote forge API failures into messages of our own,
discarding what the CLI said. GitLab picked its three by prose —
`error_text.starts_with("404")` — the pattern #3595/#3597 removed
elsewhere.

## Before / after

A GitLab MR that doesn't exist:

```
- ✗ MR !9999 not found
+ ✗ glab api failed for MR !9999
+ ▎ glab: 404 Not found (HTTP 404)
```

A GitHub PR that doesn't exist — the one message kept, now with gh's
verdict under it rather than instead of it:

```
  ✗ PR #999999 not found on max-sixty/worktrunk (gh default). Check that `gh repo set-default` points to the correct repository.
+ ▎ gh: Not Found (HTTP 404)
```

## The rule, now written down

`src/git/remote_ref/mod.rs` gets an **Error Messages** section: forward
the CLI's own line, and write our own only where the CLI *structurally
cannot* report the condition. Two cases qualify — GitHub's 404 (it
answers about an owner/repo *we* chose, from `gh repo set-default` or a
remote; gh can't know that) and Azure's missing `azure-devops` extension
(a precondition `az extension list` answers, which `az` never names).
Reading more nicely than the CLI doesn't qualify.

`cli_api_error` and `cli_api_error_details` gained docstrings for the
mechanism: our context as the headline, the CLI's words in the gutter,
so a provider with something to add passes it as `message` rather than
bailing.

## Evidence

Measured, not assumed — both CLIs render an API failure the same way:

| | stdout | stderr |
|---|---|---|
| `gh api …/pulls/999999` | `{"message":"Not Found",…,"status":"404"}` |
`gh: Not Found (HTTP 404)` |
| `glab api …/merge_requests/…` | `{"message":"401 Unauthorized"}` |
`glab: 401 Unauthorized (HTTP 401)` |

`cli_api_error_details` prefers stderr, so the gutter gets the human
line, not the JSON. That also surfaced a test bug: **the glab mocks
never set stderr**, so they'd have enshrined output real glab doesn't
produce. Fixed to match the probe.

`gh` puts the status in a structured field, so its 404 arm keys on
`status`. `glab` puts it only inside the message text — nothing to key
on, which is why prose-matching was the only way to keep those arms.

## What this gives up

A bad or expired token no longer gets "run gh auth login" / "run glab
auth login"; it gets `gh: Bad credentials (HTTP 401)`. The far more
common case — no auth configured at all — is unaffected: gh prints its
own "please run: gh auth login" and always did fall through to
forwarding. Happy to restore the GitHub 401 arm (it's structurally
keyable); GitLab's can't come back without prose-matching.

## Testing

`cargo run -- hook pre-merge --yes` → 4572 passed. Six snapshots
reviewed individually before accepting (five updated, one new). Both
paths also driven through the **real** `gh` binary (a live 404 and a
live 401), not only mocks. Clippy clean with `--features
shell-integration-tests`.

Coverage: the GitHub 404 arm and the forwarding fallthrough each have a
test, on both forges. `codecov/patch` also flagged one line —
re-indenting the 404 block pulled a pre-existing gap into the patch, and
it turned out to be real: the `gh repo set-default` half of the hint,
the fork workflow the message exists for, had never been tested.
`test_switch_pr_not_found_gh_default` closes it.

> _This was written by Claude Code on behalf of Maximilian Roos_
@max-sixty max-sixty mentioned this pull request Jul 29, 2026
max-sixty added a commit that referenced this pull request Jul 29, 2026
Cuts 0.70.0 — version bump plus the changelog for the 45 commits since
v0.69.2.

**Minor bump, not patch.** `cargo semver-checks` reports 6 breaking
library changes (`set_command_timeout` and `ListConfig::task_timeout_ms`
removed, `WorkingTree::stage` arity changed, three enum variants added
to exhaustive enums). Worktrunk ships breaking library changes freely,
but semver still puts a break at minor while pre-1.0.

## Release validation

- Local gate green on the release commit: 4631 tests, lints, doctests.
- `nightly` dispatched on the cut-from tip (`a27cbd42`) for the full
cross-platform suite — `full-tests` green on linux, macOS, and Windows,
plus minimal-versions, nix-flake, crate-build, and the release targets.

## Data-loss surface review

The cumulative diff was audited against the deletion surface. One
deliberate widening, signed off for this release with follow-ups to
file:

- **#3602** removes the content check from `wt config shell install`'s
legacy cleanup, so `conf.d/{cmd}.fish` and the stranded nushell
`{cmd}.nu` are now deleted by path, unread. Only that exact filename is
touched and each removal is reported, but the deletion is absent from
both `--dry-run` and the confirmation prompt, and the already-configured
path skips the prompt entirely.

Also noted, none blocking:

- The `!path.exists()` check precedes the lock guard on the
`Path`/`Current` removal arm, so a locked worktree whose directory is
absent loses its branch. This already governed the branch-targeted route
in v0.69.2; #3533 unified the other arms onto it. The FAQ's "Neither
`git worktree remove` nor `wt remove` (even with `--force`) will delete
them" is absolute where the behavior isn't.
- On the default background removal path, `ensure_clean` and
`stop_fsmonitor_daemon` swapped order, so the safety gate is now
answered by the live fsmonitor daemon rather than a full re-stat.
Bounded by trash staging with 24-hour retention, and the foreground and
picker paths were already daemon-served.

Net *improvements* to the same surface: shared-branch retention across
remove/prune/merge (#3533), outcome-accurate removal reporting (#3633,
#3637), and the removal of the thread-local command timeout that could
kill in-flight git commands on worker threads (#3615).

## Changelog accuracy

Entries were verified against the actual diffs rather than commit
messages, which corrected several drafts: the prune figures were one PR
stale (~2.9 s → the real ~0.6 s), `wt merge` takes no worktree argument
so it only gained the retention half of #3533, the Azure DevOps report
is behind `--full`, #3608 never touched `nightly.yaml`, and #3601
inverted what the FAQ change actually said. Two omissions were added —
the `install-statusline` foreign-statusline fix (#3595) and the shipped
`/wt-switch-create` skill change (#3636).

> _This was written by Claude Code on behalf of Maximilian_
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.70.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre>## Release Notes

### Improved

- **`wt step prune` removes worktrees far faster**: Each removal ran a serial chain of ~17 git subprocesses under the scan write lock, re-preparing a plan the scan had already computed and re-stating the worktree right after the fsmonitor daemon stop. The chain is now one check per guarantee, reusing the scan-time plan, and removals run concurrently on the scan lock's read side — the write side is kept for the candidates that need it (hook-bearing, `--foreground`, metadata-pruning, and the current worktree). The documented rust-scale live prune of 24 candidates goes from ~12 s to ~0.6 s wall, and the `prune_e2e/live` benchmark from ~620 ms to ~400 ms. ([#3617](max-sixty/worktrunk#3617), [#3631](max-sixty/worktrunk#3631))

- **`wt step prune --format=json` is ordered, and a failed removal aborts the rest**: Live JSON output is now sorted by scan index, matching `--dry-run`, with the current worktree last. The first failing removal drains the remaining queue unexecuted, matching the serial loop it replaced; in-flight removals complete. ([#3631](max-sixty/worktrunk#3631))

- **A worktree can be named by its path wherever a branch is accepted**: Every argument that takes a branch now also accepts the worktree's own path, resolved after the branch so a directory never shadows a branch sharing its name. A path names what a branch cannot — a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against `-C` and a leading `~` against the home directory, so a path worktrunk printed can be pasted back. [Docs](https://worktrunk.dev/switch/#naming-a-worktree) ([#3607](max-sixty/worktrunk#3607))

- **`wt list` flags a branch checked out in more than one worktree**: Such a branch resolves to whichever worktree git lists first, so every worktree on it now carries `⚑` — `worktree.state` `"duplicate_branch"` in schema 1, a `worktree.duplicate_branch` boolean in schema 2. The flag makes the ambiguity visible in the listing; resolving such a branch from any command warns separately and names a duplicate to drop. ([#3480](max-sixty/worktrunk#3480), [#3606](max-sixty/worktrunk#3606))

- **`wt switch --execute` computes only the template variables its command names**: The switch path built every variable the template context could hold before rendering; it now resolves just the ones the command references. On a clone with no `origin/HEAD` and no cached default branch, that removes a `git ls-remote` the command never asked for — 13 subprocesses and one remote query down to 8 and none. ([#3628](max-sixty/worktrunk#3628))

### Fixed

- **A branch checked out in a second worktree is retained on removal, `-D` included**: `wt remove` and `wt step prune` now act on the worktree named rather than the branch's first checkout, and all three of `wt remove`, `wt step prune`, and `wt merge` keep the branch while another worktree still has it out — deleting the ref would leave that worktree unable to resolve `HEAD`, which is why `git branch -d` refuses the same delete. The retention is reported and names the surviving checkout rather than passing silently. ([#3533](max-sixty/worktrunk#3533))

- **Removal reports what it took, not what it selected**: A removal's summary and JSON described the plan, so a worktree candidate whose branch was retained still counted as `✓ Pruned 1 branch`, and `wt remove --format=json` reported `"branch_deleted": true` beside a stderr line saying the branch was kept. Execution now returns the branch's fate; `wt step prune` counts executed outcomes (`--dry-run` included), both JSON payloads gained `branch_deleted`, and a declined orphan deletion drops out of the removed list rather than being reported as removed. ([#3633](max-sixty/worktrunk#3633), [#3637](max-sixty/worktrunk#3637))

- **Hook previews expand every variable except `vars.*`**: One `vars.` token disabled expansion for the whole command, so `wt hook show --expanded` and `wt hook <type> --dry-run` printed `{{ branch }}` and `{{ repo }}` raw in a listing whose job is to show the expansion. A preview now substitutes a stand-in that renders each `vars.*` reference back as itself, nested access included, while every other variable expands — and no longer spawns the git read that resolving `vars` required. The listing is also derived from the execution path itself, so a context key added there reaches the preview with no second edit. `wt config alias dry-run` shares the renderer, so its help text — which still described the all-or-nothing behavior — was corrected to match. ([#3635](max-sixty/worktrunk#3635), [#3638](max-sixty/worktrunk#3638), [#3639](max-sixty/worktrunk#3639))

- **`wt hook show` no longer prints a bare heading for an empty command list**: A hook type declared as `post-switch = []` has a config entry but no commands, and the section decided it had printed something from the entry rather than from the rows — so it emitted its heading and stopped, and the `(none configured)` line never appeared. Both the user and project sections carried the bug, since the loop and the fallback were duplicated; they now share one renderer that reports whether it wrote any rows. The execution path was already correct: an empty list announces nothing and is omitted from JSON. ([#3641](max-sixty/worktrunk#3641))

- **`wt config shell install` reclaims its own legacy wrapper paths**: Fish sources `conf.d` at startup, so a stale `conf.d/{cmd}.fish` was already loaded by the time fish would autoload the `functions/{cmd}.fish` the install had just written — the old definition won and the new wrapper never loaded. Install decided ownership by reading the file, and left anything unrecognized in place. Ownership now comes from the path: `conf.d/{cmd}.fish` and the stranded nushell `{cmd}.nu` candidates are paths worktrunk computes for the command being installed, so it takes them back whole, unread. Only that exact filename is touched — a neighbour under another name is not worktrunk's — and each removal is reported. `wt config shell uninstall` still reads the header, because it takes no `--cmd` and so cannot know the name; it prompts and previews every file first. (Breaking: install now removes a file at those exact paths regardless of its contents.) ([#3602](max-sixty/worktrunk#3602))

- **Command timeouts actually bound wall-clock, and a default branch guessed while the remote was unreachable isn't cached**: A timeout killed only the direct child, so a surviving grandchild held the output pipe open and the call ran on regardless — a 3 s bound measured at 120 s. A timed command now runs in its own process group and the whole tree is torn down on expiry, which fixes every existing bound including the fsmonitor and reap probes. On top of that, nothing in git bounds `git ls-remote` (an unreachable host costs ~127 s per address on Linux), so default-branch detection abandons the query after 10 s and falls back to local inference — without caching the result, so an outage can't make an inferred default branch permanent. (Breaking: because a timed command gets its own process group, Ctrl-C no longer reaches it; the command waits out the remaining bound.) ([#3603](max-sixty/worktrunk#3603))

- **`wt step relocate` no longer strands a worktree in its staging directory**: When worktree A's target was held by worktree B, and B was itself blocked by a non-worktree path without `--clobber`, the dependency loop read the stall as a cycle, temp-moved A into `.git/wt/staging/relocate/`, then failed moving it into the still-occupied target — leaving A at neither its original nor its expected path. A worktree blocked by an immovable occupant is now skipped. ([#3530](max-sixty/worktrunk#3530))

- **Forge CLI failures are classified by response shape, not by the tool's prose**: `tea api` copies the response body to stdout and exits 0, so an HTTP error never tripped the exit-code gate — a Gitea `APIError` body deserialized into `{state: "", total_count: 0}`, indistinguishable from a commit with no CI statuses, while the PR-list path blamed an API change for what was an API error. Failures from `gh`, `glab`, and `tea` are now keyed on the response envelope, and a non-zero exit keeps meaning the tool itself failed; the CLI's own error text is forwarded rather than reworded, so a bad token surfaces as `gh: Bad credentials (HTTP 401)` instead of a suggestion to re-authenticate. `wt config show --full` reports the Azure DevOps CLI extension alongside the other forge tools. ([#3595](max-sixty/worktrunk#3595), [#3597](max-sixty/worktrunk#3597), [#3605](max-sixty/worktrunk#3605))

- **`wt config plugins claude install-statusline` no longer mistakes another tool's statusline for its own**: The check for an existing worktrunk statusline matched the bare substring `wt `, which an unrelated command like `newt status` satisfies — so `wt config show` reported a foreign statusline as worktrunk's, and the installer early-returned "already configured" and refused to install. It now matches the adjacent `list statusline` token pair, so it works whether the binary is `wt`, `git-wt`, or an absolute path. ([#3595](max-sixty/worktrunk#3595))

- **`[list] task-timeout-ms` is removed**: The per-command bound is gone; `[list] timeout-ms` bounds the whole collect phase. A config that still sets it warns, and `wt config update` strips the key — i

See merge request: Harmonybrew/homebrew-core!15439
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants