Files
worktrunk/AGENTS.md
Maximilian RoosandClaude Opus 5.5 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>
2026-10-20 12:31:58 -07:00

10 KiB
Raw Permalink Blame History

Worktrunk development guidelines

Quick start

Run cargo run -- hook pre-merge --yes for the project test and lint gate. Claude Code web first runs task setup-web; Codex Cloud uses .codex/cloud.sh. Test and coverage recipes live in tests/AGENTS.md.

Project Status

Worktrunk is a CLI with a growing user base. New commands, flags, and config keys are product decisions. Config formats and CLI arguments are protected interfaces; internal APIs and output formatting are flexible. MSRV is latest stable minus one.

Terminology

  • main worktree: the original Git directory; bare repos have none
  • linked worktree: one created by git worktree add
  • primary worktree: the home worktree, or the default-branch worktree in a bare repo
  • default branch: the branch named main, master, or equivalent
  • target: a merge, rebase, or push destination, never a worktree

Skills

Load writing-user-outputs before changing visible CLI text, running-tend for Tend CI, and release for a release. Project-local skills live in .claude/skills/, linked for Codex from .agents/skills/.

Worktree Model

Each worktree maps to one branch. Worktree arguments resolve branch first through Repository::resolve_worktree; a path aliases its checkout, including detached or duplicate-branch checkouts. Never retarget an existing worktree to a different branch; create, switch, or remove instead. The experimental wt step promote is the sole branch-exchange operation.

Documentation

Public docs help users choose and use Worktrunk. Keep them concise, in the reader’s terms, with detail proportional to how many readers need it. Document new capabilities and changed usage; correct false claims in place with the smallest sufficient edit. Implementation rationale belongs in code. A correctness fix that preserves usage needs no new guide prose; keep regression conditions in tests and commit messages.

src/cli/mod.rs is primary for command help and generated command pages; docs/AGENTS.md explains sync. Check that --help matches behavior. Run cargo test --test integration test_docs_are_in_sync, then refresh help snapshots when help text changes.

Plugin Layout

The loader paths, generated skills mirror, and cross-tool hook requirements are in plugins/worktrunk/AGENTS.md.

Data Safety

Prefer a clear failure over losing untracked files, uncommitted changes, or user data. Make cleanup a separate action, never a destructive side effect of an unrelated command. Force removal requires explicit consent. Git operations should use their failing variant on races: reset --keep and checkout --merge instead of destructive alternatives.

Be conservative across the gap between a safety check and the operation. If files appear before cleanup, fail rather than force-remove them.

Full-file rewrites of user-owned or externally owned files use utils::write_atomically; creation of an observed-missing file uses write_new_atomically. Shell rc additions append under the installer lock; removal rewrites atomically. A user-named --output path is an intentional replacement. Regenerable caches and diagnostic reports may use ordinary writes. See the write helper contracts for symlink and mode behavior.

Git itself may overwrite an ignored destination file when a tracked file arrives, and core.fsmonitor controls Git's final dirty-worktree gate. The inventory is in the FAQ sections “What files does Worktrunk create?” and “What can Worktrunk delete?”

Command Execution Principles

All Commands Through shell_exec::Cmd

External commands use shell_exec::Cmd for logging and timing; Git generally uses Repository::run_command or WorkingTree::run_command. Use run for capture, stream for live output, delayed_stream for slow setup, and pipe_into for pipelines. In-process spawns outside Cmd use a CommandTrace guard; its contract is in src/trace/emit.rs. Detached background children and interactive helpers are deliberately untraced.

Git-Discovery Env Vars Follow Who Chose the Cwd

A child whose cwd is a Worktrunk-chosen worktree must scrub inherited Git discovery variables before running, including hooks and worktree-local plumbing. Repo-level commands and commands in the user's own context keep inherited values. The site classification is in scrub_git_discovery_env_vars in src/shell_exec.rs.

Real-time Output Streaming

Show the first local result promptly. Stream later output line by line. Network detail may arrive after the first frame, but must not block it.

Structured Output Over Error-Message Parsing

Use exit codes and machine-readable output. For example, distinguish git merge-base results by status code and parse git status --porcelain=v2 -z, rather than matching localized prose.

Plumbing for Output Worktrunk Consumes

Git output that Worktrunk parses, caches, renders, or prompts with uses plumbing, with submodule behavior pinned through PlumbingDiff::args and rendered diffs through PreparedDiff::capture. Output displayed as Git's own view, such as wt step diff, may stay porcelain.

Immutable Ids Over List Positions

Do not carry stash@{n} or another position through a mutation window. Capture an object id or derive the position from a stable id immediately before use.

Network Access

Worktrunk touches the network only when the user asks for it. The first Repository::default_branch() is the bounded detection exception: it may use git ls-remote and cache the result; timeout falls back to local inference without caching. No other detection helper adds a wire fallback. A synchronous shell-prompt hot path never touches the network; wt list statusline may fetch CI status because its host consumes it asynchronously. The picker can stream forge results into visible rows and cancel them when the user leaves; a run-to-completion command waits for its last request even after first paint.

Signal Handling: Ctrl-C Cancels the Current Command

Foreground commands share the caller's native job group. A child terminated by SIGINT or SIGTERM stops every foreground loop before its next step, including Warn hook pipelines and worktree loops. A terminal Ctrl-C that wt itself receives while a child runs cancels the command, as in make or cargo: the child handles the key its own way, then wt starts nothing more and exits interrupted, whatever status the child chose. wt's receipt is the evidence; never infer cancellation from numeric exit codes such as 130. A final interactive child (a pager, an --execute program, a custom subcommand, an alias's last serial step) owns the key as input instead, and its exit status stands. SIGTERM addressed to wt cancels its owned work even if the child catches it. Use err.interrupt_signal() from ErrorExt and propagate WorktrunkError::Interrupted through loops. Capture mode also classifies native SIGINT/SIGTERM exits; other child signals remain visible failures. See src/shell_exec.rs and src/signal_forwarder.rs for the contracts.

Project Commands Run Only After Approval

Project hooks, aliases, and --execute commands are arbitrary code. Gate them through Approvals before running. For an operation that mutates state between approval and execution, select once into ApprovedHookPlan and execute only that plan; do not reread config to choose new commands. A noninteractive context runs only an already approved subset. The contract is in src/commands/hook_plan.rs.

Background Hook Pipelines Run Concurrently, Per Source

A post-hook batch spawns one detached pipeline per source. A source can run indefinitely, so do not serialize independent sources. HookAnnouncer marks an anchor worktree removed before flush, preventing a hook from running in a path that no longer resolves to that worktree. See src/commands/process.rs.

Coverage

codecov/patch is a merge gate even if GitHub marks it optional. Fix real gaps; do not bend the design to a predicted percentage. A failing patch check requires explicit approval before merge. Check runs appear after the coverage job, not in commit statuses. Investigation commands are in tests/AGENTS.md.

Code Quality

Use Existing Dependencies

Check Cargo.toml and installed APIs before writing a utility. Prefer path_slash for path normalization, shell_escape for shell quoting, color_print for ANSI styling, and MiniJinja's undeclared_variables for template variables.

Name pure accessors as bare nouns, erroring preconditions require_, network calls fetch_, and file loads load_; avoid get_.

Other Tools Own Their Conventions

Where another tool owns a convention, such as its config location, file format, URL syntax, or error reporting, ask that tool or a library that implements its rules instead of encoding them in Worktrunk: nu reports its own directories, and gh auth token --hostname reports whether a host is authenticated. Worktrunk's role is the standard uses of those conventions. Where neither the tool nor a library answers, support the standard case and remove rather than refine: an input that only misbehaves outside standard use is a reason to stop reading it, and a tool that isn't installed has nothing to integrate with, so needs no fallback table.

System Docstrings

Complex state machines and cross-module coordination need a module-level spec describing purpose, decisions, and invariants. Keep it current as the system changes.

Keep test helpers out of library code. Use plain multiline string literals, without continuation escapes. Do not hide unused code with allow(dead_code).

Error Handling

Use anyhow context for I/O and child command failures, and bail! for business-rule failures. Functions returning Result use ? or explicit errors, not expect or unwrap.

Config Deprecation

Migrate deprecated TOML before deserialization in src/config/deprecation.rs; never silently drop a key. Each DEPRECATION_RULES row uses one idempotent migrate-and-report function for detection and rewrite. Warning rules fire exactly when wt config update changes the file, and what an update writes must load without deprecation or unknown-field warnings. The module spec and test_warning_fires_iff_update_changes own the details.

Releases

Use the release skill. Release changelog entries come from commits since the last tag; feature PRs leave CHANGELOG.md untouched.