Add machine-readable error codes to JSON commands
Motivation
Callers using --format=json can parse successful results, but failures such as approval-required, hook failure, and Git failure still require compatibility matching against human-readable stderr.
Request
For JSON-mode commands, return a stable structured error envelope or another documented machine-readable error channel with codes for at least:
- approval required;
- hook failure;
- Git failure;
- invalid input or unsupported operation.
Human diagnostics can remain on stderr, but callers should not need regexes to classify failures.
Thanks for the suggestion — this is a real gap. There's no machine-readable error channel today: --format=json shapes only the success payload, and every failure path renders the same way regardless of format.
Concretely, on failure a command routes through print_command_error → format_command_error, which emits human-readable, styled text to stderr with no JSON variant. The exit code then comes from error.exit_code().unwrap_or(1) — so it isn't a category channel either. Walking WorktrunkError::exit_code and its enum, of your four categories only hook failure carries a distinct code (it passes through the hook's own exit code); approval-required (CommandNotApproved) and most git/invalid-input failures are plain anyhow errors with no typed code, so they all collapse to 1. So regex-against-stderr is indeed the only classifier right now.
Where a change would slot in, and one existing precedent worth pointing at: wt step for-each --format=json already emits a per-item structured failure — {branch, path, exit_code, success: false, error} — from for_each.rs. That's the shape you're describing, just scoped to one command's per-worktree results rather than offered as a top-level command-failure envelope. Generalizing it would mean (a) giving the failure categories a stable discriminant — the ~40-variant GitError enum plus the WorktrunkError variants are a good foundation (an error_code() mapping alongside the existing exit_code() walk), with a fallback code for the untyped anyhow/bail! context that can't be classified today; and (b) deciding the transport. One concrete plumbing cost either way: --format is declared per-subcommand and consumed inside each handler, so it isn't currently visible at the top-level error handler (handle_command_failure) — a JSON error envelope would need the effective format threaded up there, or emitted inside each handler.
Two tradeoffs a maintainer would weigh on (b):
- A JSON error envelope on stdout (mirroring
for_each) is richest, but it changes the "JSON is the only stdout payload, diagnostics stay on stderr" invariant that the related #3501 thread leaned on — errors would now also print structured JSON to stdout. - A documented stable exit-code scheme (one code per category) keeps stdout pure and is a smaller surface, but it's coarser than an envelope with a code + message.
This is closely tied to #3501 (stable automation contract), where "structured error category" was flagged as the open item before that issue was closed by a different requester who opted to pin versions and build against the existing CLI. Per the project's CLAUDE.md, output formatting is explicitly on the flexible, uncommitted side of the interface line — so both the envelope and the stability commitment behind it are a maintainer policy call rather than a mechanical fix. I'll leave it for a maintainer to evaluate and prioritize.
I'd like to work on this — planning to map failure categories to stable codes, thread JSON-mode through the top-level error path, add tests, and open a PR.
Before locking the transport: the earlier triage called out two options — (1) a JSON error envelope on stdout (closest to wt step for-each --format=json's per-item {success:false, error, exit_code} shape), or (2) a documented stable exit-code scheme that keeps stdout success-only. #3501 is closed and #3710 already added some machine-readable approval/removal outcomes, so I'd like to align with whatever contract you want going forward.
Please let me know if anyone is already on it or which transport you prefer. I'll start on the independently progressable piece — an error_code() (or equivalent) mapping over WorktrunkError / typed git failures for at least approval-required, hook failure, Git failure, and invalid input — unless you'd rather I wait.
Nobody's on it as far as I can see — no open or closed PR references this issue. When @max-sixty landed #3710, its description listed #3697 as "a real gap and the one policy call in the set; not started", so the transport choice (stdout envelope or exit-code scheme) is still theirs to make. I'll leave that decision to them rather than pick one.
The error_code() mapping you describe works with either transport, so starting there doesn't commit the project to one. One correction to my earlier triage that affects that piece: approval-required is already typed, not plain anyhow. A non-interactive run that needs approval returns GitError::NotInteractive, and a declined prompt returns WorktrunkError::CommandNotApproved. Both lack an exit code (exit_code()), so they fall back to 1. The invalid-input category is the one that mostly lives in untyped bail! sites (about 80 under src/), so classifying it means converting the relevant sites into typed errors, not just mapping the existing enums.
@worktrunk-bot what are some cases where this would be useful?
It's useful for a program that has to choose its next step after a nonzero exit. That mostly means non-LLM orchestrators like the one behind this set of issues (#3696–#3700) and the multi-repo orchestrator in #3501. Both drive wt -C "$repo" switch --create --format=json <branch> with no human at the terminal. Today, almost every failure exits 1. Each category calls for a different response:
- Approval required. The orchestrator shows the commands to a human, or runs
wt config approvals add, then retries. It must not pass--yesblindly, because that approves whatever is in the project config. - Invalid input (for example, the branch already exists or the name isn't valid). The orchestrator reports it to the user and doesn't retry, since retrying won't help.
- Git failure (for example, a leftover
index.lockfrom a concurrent git process, which is common when one orchestrator drives several worktrees at once). The orchestrator retries with backoff. - Hook failure. The worktree now exists. The orchestrator keeps it and offers to re-run setup, or cleans it up. A hook's exit code is passed through, so a hook that exits
1, the usual case, gives the same code as every other failure.
A GUI or editor front-end has the same needs, mapping each category to a UI action: an "Approve hooks" button, an error toast, or a "Retry setup" action.
Where this is weak:
- An LLM agent reads the stderr prose fine, so agent harnesses gain little.
- Approval-required, the most valuable case, can already be checked before running:
wt config approvals list --format=json(#3710) returnsstate: "approval_required". - A hook failure during
wt switch --createcan already be told apart. The switch still prints its JSON result, path included, to stdout before exiting nonzero (switch.rs). So "nonzero exit with a JSON result on stdout" means the worktree was created and setup failed.
The gap no workaround covers is telling a retryable Git failure apart from an input error. That is also the costliest part to build, because most input errors are untyped bail! sites. If you want a smaller step than a full envelope, a few reserved exit codes (approval required, invalid input) would cover the cases that are already typed and keep stdout as it is. @NathanaelRea could say which branch their caller actually takes. That would show whether the remaining Git-versus-input split is worth the conversion work.
@worktrunk-bot what are some cases where this would be useful?
FYI this would also be useful here: https://github.com/max-sixty/worktrunk/pull/4502 Having scripts that assume failure means the single expected error is undesirable in general
The #4502 case is one of the cheap ones. When the worktree at a branch's expected path holds another branch, wt switch already fails with a typed error, GitError::WorktreePathOccupied { branch, path, occupant }, raised in switch.rs. It has no exit_code() of its own, so today it exits 1 like everything else. Classifying it needs no bail! conversion; it only needs a mapping. Its fields are the data @BenJurewicz's wrapper currently recomputes with expected_worktree_path_of_branch: the expected path and the branch that occupies it.
So this adds to the typed set that the smaller reserved-exit-code step would cover, next to approval-required. A JSON envelope could also carry path and occupant. That would let the wrapper switch to the path without calling wt step eval again, and without falling back on unrelated failures.