Skip to content

refactor: unify foreground execution of hooks and aliases - #2128

Merged
max-sixty merged 15 commits into
mainfrom
unify-hook-alias
Apr 12, 2026
Merged

max-sixty merged 15 commits into
mainfrom
unify-hook-alias

Conversation

@max-sixty

@max-sixty max-sixty commented Apr 12, 2026 •

Copy link
Copy Markdown
Owner

Extracts execute_pipeline_foreground() in command_executor.rs as the single foreground execution path for both hooks and aliases. Previously hooks.rs and alias.rs each had their own loop calling execute_shell_command with duplicated logic for serial/concurrent steps, template expansion, and error handling.

The shared executor is parameterized by CommandOrigin (Hook vs Alias) which determines announcement format, error wrapping, and log labels. Hooks pass concurrent: false (serial execution per documented contract), aliases pass concurrent: true (thread::scope for concurrent steps). HookFailureStrategy is renamed to FailureStrategy and moved to command_executor since it's no longer hook-specific.

Key types added to command_executor.rs: CommandOrigin, ForegroundStep, FailureStrategy. Key types removed: AliasExecCtx (alias.rs), HookFailureStrategy / announce_hook_command / execute_one_hook_command (hooks.rs). Background hook execution is unchanged — it uses fundamentally different I/O (log files, not terminal streaming).

Follow-ups

This PR centralizes dispatch but the shared helpers still match on CommandOrigin internally, so net LOC grows rather than shrinks. Real consolidation tracked as inline TODOs on execute_pipeline_foreground:

  1. Unify the error type — one CommandFailed { origin_label, exit_code, message } collapses handle_command_error.
  2. Unify announcement policy so announce_command's origin match disappears.
  3. Push log/expansion labels onto PreparedCommand at prep time.
  4. Longer term: treat hooks as aliases bound to triggers so hooks.rs becomes a thin trigger-dispatcher over the alias machinery.

This was written by Claude Code on behalf of @max-sixty

max-sixty and others added 8 commits April 11, 2026 18:57
Shell integration previously used a single WORKTRUNK_DIRECTIVE_FILE that held
arbitrary shell commands (`cd '...'`, exec payloads). This meant alias and
hook shell bodies could inject arbitrary shell into the user's interactive
session by writing to the file.

Split into two files with different trust levels:

- WORKTRUNK_DIRECTIVE_CD_FILE: raw path, wrapper does `cd -- "$(< file)"`.
  No shell parsing, no injection surface. Safe to pass to alias/hook bodies.

- WORKTRUNK_DIRECTIVE_EXEC_FILE: arbitrary shell (--execute payloads),
  wrapper sources it. Scrubbed from alias/hook child environments so bodies
  cannot inject shell into the parent session.

When a nested `wt` inside an alias body tries to emit --execute, it warns
and drops the payload, linking to #2101 for user feedback on relaxing.

Legacy single-file WORKTRUNK_DIRECTIVE_FILE is honored for one release with
a deprecation warning, bridging users who upgraded wt without restarting
their shell.

Co-Authored-By: Claude <[email protected]>
Resolved import conflict in alias.rs: combined main's new
expand_shell_template/wait_first_error/force_serial_concurrent imports
with our DirectivePassthrough import.

Co-Authored-By: Claude <[email protected]>
Most shells (bash, zsh, fish, PowerShell) re-evaluate from the binary on
restart, so the warning was unavoidable noise until the next terminal
restart. Nushell is the only shell needing manual reinstall. A targeted
nushell-only warning can be added in a future release.

Co-Authored-By: Claude <[email protected]>
…plication

Drop the legacy env var from the help/docs env var table and condense the
identical directive-passthrough rationale in alias.rs and hooks.rs to a
one-liner pointing at the canonical explanation in output::global.

Co-Authored-By: Claude <[email protected]>
Extract `execute_pipeline_foreground()` in `command_executor.rs` as the
single foreground execution path for both hooks and aliases. Previously
each had its own loop calling `execute_shell_command` — now they share
pipeline iteration, concurrent/serial step handling, lazy template
expansion, and origin-aware error handling via `CommandOrigin`.

Co-Authored-By: Claude <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

codecov/patch reports 91.29% (target 96.11%). The base PR #2118 also fails at 95.09%, so part of the gap is inherited from the stacked directive-file split. The remaining delta is likely from moved code paths in the unified execute_pipeline_foreground where branch coverage in the new structure differs slightly from the original split locations. Worth investigating before merge — the maintainer may want to address coverage in #2118 first, then rebase this PR.

Unit tests for handle_command_error covering all origin × strategy
combinations, plus helpers command_log_label and expansion_label.

Co-Authored-By: Claude <[email protected]>
worktrunk-bot
worktrunk-bot previously approved these changes Apr 12, 2026
@worktrunk-bot
worktrunk-bot dismissed their stale review April 12, 2026 17:00

codecov/patch failed — investigating coverage gap

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

codecov/patch is failing. The code looks correct — dismissing the approval only because of the coverage gap. Here's where the uncovered new lines are:

src/output/global.rs — two gaps:

  1. warn_exec_scrubbed_once (lines 280–297) and its caller in execute() (line 421): requires WORKTRUNK_DIRECTIVE_CD_FILE set but WORKTRUNK_DIRECTIVE_EXEC_FILE absent, then a wt switch --execute call. The configure_directive_cd_only test helper exists for exactly this scenario but isn't used in any integration test yet.

  2. escape_legacy_cd PowerShell branch (line 336): requires WORKTRUNK_SHELL=powershell with legacy directive file. Platform-specific — unlikely to be exercised on Linux CI.

src/output/global.rs — pre-existing: execute_command Unix path (lines 447–469) uses exec() which replaces the process, making coverage impossible to capture. Not new to this PR.

The exec-scrubbed scenario (gap 1) is the most actionable — an integration test with configure_directive_cd_only + --execute would cover it. I can push that if you'd like. The PowerShell escaping (gap 2) is hard to cover on Linux CI without mocking WORKTRUNK_SHELL.

# Conflicts:
#	src/commands/alias.rs
#	src/commands/hooks.rs
#	src/commands/picker/pager.rs
#	src/commands/process.rs
#	src/git/repository/mod.rs
#	src/help_pager.rs
#	src/shell/snapshots/worktrunk__shell__tests__init_bash.snap
#	src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
#	src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap
#	src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap
#	src/shell/utils.rs
#	src/shell_exec.rs
#	templates/bash.sh
#	templates/fish.fish
#	templates/zsh.zsh
#	tests/integration_tests/directives.rs
#	tests/snapshots/integration__integration_tests__init__init_bash.snap
#	tests/snapshots/integration__integration_tests__init__init_fish.snap
#	tests/snapshots/integration__integration_tests__init__init_zsh.snap
max-sixty and others added 5 commits April 12, 2026 15:00
…mpat

The pre-hook table form is deprecated; serial fallback in
execute_pipeline_foreground accepts the shape but documents it as compat,
not canonical.

Co-Authored-By: Claude <[email protected]>
# Conflicts:
#	src/commands/alias.rs
Lists four paths to actual LOC consolidation after the initial unification:
error-type unification, announcement policy, label-on-step, and longer-term
treating hooks as aliases bound to triggers.

Co-Authored-By: Claude <[email protected]>
@max-sixty
max-sixty merged commit dc365fb into main Apr 12, 2026
22 checks passed
@max-sixty
max-sixty deleted the unify-hook-alias branch April 12, 2026 23:47
max-sixty added a commit that referenced this pull request Apr 13, 2026
Conflict was layout-only: main (via #2128 refactor) moved the
test_format_alias_summary_* tests to the end of the tests module.
Branch added test_render_aliases_section_source_annotations in the
middle position. Resolution: accept main's layout and place the new
test next to the moved summary tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Jun 11, 2026
…#3042)

Hook templates expanded eagerly at prep time unless they referenced
`vars.*` (#1840); aliases were unconditionally lazy. The dual
representation (`expanded` + `lazy_template` on `PreparedCommand`) put a
mode choice in front of every consumer, and the seams produced real bugs
(#1855, #1910). The background runner also re-rendered eagerly-expanded
strings: a latent double-expansion whenever expansion output contained
`{{`.

This PR unifies on one rule: syntax is validated at preparation (before
step 1), templates render when each step runs, and `vars.*` always reads
fresh from git config. This is the direction #2128 recorded ("treat
hooks as aliases bound to triggers").

**Navigating the diff:**

- `src/commands/command_executor.rs`: `PreparedCommand` now carries the
raw template plus the frozen context map; JSON is produced only at the
process boundary. A `template_name` field keeps the moved errors' text
identical to the old prep-time messages. `prepare_steps` validates
syntax and freezes context; `resolve_command_str` renders at execution;
`map_config_steps` is the structural walker shared with aliases.
- `src/commands/alias.rs`: alias prep shares the walker. The residual
fork is genuinely alias-specific: context construction (filtered to
referenced vars, `{{ args }}` injection) and labels. A prep-time syntax
check turned out to be dead code (the arg-routing parse already aborts
on syntax errors), so `referenced_vars_for_config` now produces the rich
`TemplateExpandError` instead.
- `src/commands/hooks.rs`: the background spec always ships raw
templates; the runner renders each step (it already did for vars steps).
- Dry-run paths (`wt hook --dry-run`, `wt config alias dry-run`) share
`render_template_preview`: vars-referencing templates shown raw after a
syntax check, everything else rendered at display time.

**Behavior changes** (each pinned by a test or snapshot):

1. A foreground pipeline whose step N has a semantic template error
(undefined variable) runs steps 1..N-1 before failing, matching what
vars-referencing steps already did. New test:
`test_foreground_pipeline_undefined_var_runs_earlier_steps`.
2. A semantic error in a background hook template no longer fails the
foreground command; it surfaces in the runner log. Syntax errors still
abort at prep. New test:
`test_background_hook_undefined_var_fails_in_runner`;
`test_merge_drops_pending_hooks_when_post_merge_fails` switched to a
syntax-error fixture since that is what now reaches its subject (the
announcer Drop-flush).
3. `-v` no longer prints the parent-side rendered command for background
hooks (rendering happens in the runner). The variables table remains and
`wt hook <type> --dry-run` previews commands; help text updated. Three
snapshots changed by exactly this.
4. Announce gutters for vars-referencing foreground steps show the
rendered command instead of the raw template.
5. Syntax errors caught by the arg-routing parse (aliases, `wt hook`
`--KEY=VALUE` routing) render as the rich template error with the
source-line gutter, naming the alias or hook.

`ApprovedHookPlan` freezing, approval semantics (keyed and displayed by
template), config file format, and CLI flags are unchanged.

**Testing:** full local gate green (3917 tests + lints). The deferral
semantics in changes 1 and 2 previously had no coverage; both are now
pinned.

> _This was written by Claude Code on behalf of max_

Co-authored-by: Claude Fable 5 <[email protected]>
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