Repository navigation
refactor: unify foreground execution of hooks and aliases - #2128
Conversation
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]>
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]>
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
left a comment
There was a problem hiding this comment.
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]>
codecov/patch failed — investigating coverage gap
worktrunk-bot
left a comment
There was a problem hiding this comment.
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:
-
warn_exec_scrubbed_once(lines 280–297) and its caller inexecute()(line 421): requiresWORKTRUNK_DIRECTIVE_CD_FILEset butWORKTRUNK_DIRECTIVE_EXEC_FILEabsent, then awt switch --executecall. Theconfigure_directive_cd_onlytest helper exists for exactly this scenario but isn't used in any integration test yet. -
escape_legacy_cdPowerShell branch (line 336): requiresWORKTRUNK_SHELL=powershellwith 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
…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]>
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]>
…#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]>
Extracts
execute_pipeline_foreground()incommand_executor.rsas the single foreground execution path for both hooks and aliases. Previouslyhooks.rsandalias.rseach had their own loop callingexecute_shell_commandwith 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 passconcurrent: false(serial execution per documented contract), aliases passconcurrent: true(thread::scope for concurrent steps).HookFailureStrategyis renamed toFailureStrategyand moved tocommand_executorsince 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
CommandOrigininternally, so net LOC grows rather than shrinks. Real consolidation tracked as inline TODOs onexecute_pipeline_foreground:CommandFailed { origin_label, exit_code, message }collapseshandle_command_error.announce_command's origin match disappears.PreparedCommandat prep time.hooks.rsbecomes a thin trigger-dispatcher over the alias machinery.