Skip to content

refactor(hooks): always-lazy template expansion for hooks and aliases - #3042

Merged
max-sixty merged 1 commit into
mainfrom
always-lazy-templates
Jun 11, 2026
Merged

max-sixty merged 1 commit into
mainfrom
always-lazy-templates

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

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

Unify hook and alias template preparation on a single rule: syntax is
validated at prep (before step 1), rendering happens when each step
runs, and vars.* always read fresh from git config. This deletes the
dual expanded/lazy_template representation on PreparedCommand, the
vars-referencing gate in prep, and the eager branch — and with them the
latent double-render of eager strings in the background runner.

Behavior changes:
- A foreground pipeline whose step N has a semantic template error
  (e.g. undefined variable) now runs steps 1..N-1 before failing.
- Semantic template errors in background hooks no longer fail the
  foreground command; they surface in the runner log.
- -v no longer shows the parent-side rendered command for background
  hooks (rendering moved to the runner); the variables table remains.
- Announce gutters for vars-referencing foreground steps show the
  rendered command instead of the raw template.
- Alias and wt-hook arg-routing syntax errors render as the rich
  TemplateExpandError instead of a plain parse-failure message.

Also: PreparedCommand stores the context map (JSON only at the process
boundary), log labels derive from PipelineKind at execution, and alias
prep shares the map_config_steps walker with hooks.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@max-sixty
max-sixty merged commit 371d286 into main Jun 11, 2026
36 checks passed
@max-sixty
max-sixty deleted the always-lazy-templates branch June 11, 2026 22:50
max-sixty added a commit that referenced this pull request Jun 12, 2026
…und (#3047)

Follow-up from review on #3042. The background pipeline runner labeled
template-expansion errors with `name.unwrap_or("pipeline step")`, so a
runner log read `Failed to expand broken: …` (or `Failed to expand
pipeline step: …`) where the foreground says `Failed to expand
user:broken: …`.

The prep-computed `template_name` ("user:foo" for named hook commands,
"user pre-merge hook" for unnamed ones) now travels through
`PipelineStepSpec` / `PipelineCommandSpec` and is used as the render
label in the runner, so the label is computed once in `prepare_steps`
and the two paths can't drift. The spec is an internal JSON blob piped
to the detached `wt hook run-pipeline` process spawned from the same
binary, so the new required field has no compatibility concerns.

Command-failure messages intentionally keep the bare command name rather
than `template_name`: that mirrors the foreground, where
`hook_error_wrapper` puts `cmd.name` into `HookCommandFailed` and only
expansion errors get the source-qualified name. The serial path's
failure label is aligned with the concurrent path's existing convention
(`name.unwrap_or(expanded)` — it previously used the expanded command
even for named steps).

Runner-log error renderings are now pinned by inline snapshots: the
expansion error (matching the committed foreground snapshot
byte-for-byte) and both command-failure label shapes (named and
unnamed). The concurrent-group failure label isn't separately
snapshotted — it's the same `failure_error` call and label choice the
new test pins, unchanged by this PR.

> _This was written by Claude Code on behalf of max_

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
@max-sixty max-sixty mentioned this pull request Jun 13, 2026
max-sixty added a commit that referenced this pull request Jun 13, 2026
Release v0.58.0.

Highlights since v0.57.0:

- **Table-form `pre-*` hooks run concurrently** (#3052) — completes the
cut-over announced in v0.37.0. Breaking for configs relying on serial
ordering; pipeline form (`[[pre-merge]]`) stays serial.
- **CI column shows the PR/MR number and review state** (#3041, #3044) —
`wt list --full` and the statusline show the open PR/MR reference
colored by CI status, with review state folded in.
- **Hooks/aliases share one lazy template model** (#3042, #3047) —
templates render per-step; `{{ vars.* }}` reads fresh.
- **`wt config state cache`** (#3027) — consolidates regenerable caches;
`state clear` now confirms first.
- Statusline rate-limit display, `/wt-switch-create` optional branch
name, plugin worktree-hook hardening, and a batch of config-deprecation
and snapshot-determinism fixes.

Full notes in `CHANGELOG.md`.

The release tag is pushed to the squash-merge commit after this lands;
`release.yaml` then publishes to crates.io, Homebrew, and winget.

> _This was written by Claude Code on behalf of max_
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.58.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

- **Table-form `pre-*` hooks run concurrently**: A multi-entry table hook (`[pre-merge]` with several keys) now runs its commands concurrently, completing the cut-over announced in v0.37.0: every hook type has one execution semantic, where table form is concurrent and pipeline form (`[[pre-merge]]` blocks) is serial. Configs that need ordering should use pipeline form; affected configs have warned on every invocation since v0.37.0, with `wt config update` offering a serial-preserving migration. Two adjacent inconsistencies are also gone: `wt hook <post-type>` foreground runs of multi-entry table hooks now run concurrently like their background counterpart, and single-entry table aliases write to stdout like the other alias spellings, so `wt <alias> | …` works for that spelling too. (Breaking: multi-entry table-form `pre-*` hooks no longer run serially) ([#3052](max-sixty/worktrunk#3052))

- **CI column shows the PR/MR number and review state**: The CI column in `wt list --full` and the statusline shows the branch's open PR/MR reference (`#3041` on GitHub/Gitea/Azure DevOps, `!3041` on GitLab) instead of a plain dot: colored by CI status, hyperlinked to the PR, dimmed when stale or draft. Review state folds into the color, with magenta for changes requested and cyan for awaiting review. `wt list --format=json` gains `ci.number` and `ci.review_state`. ([#3041](max-sixty/worktrunk#3041), [#3044](max-sixty/worktrunk#3044))

- **Hook and alias templates render when each step runs**: Templates are syntax-checked before the first step runs and rendered as each step executes, so `{{ vars.* }}` always reads fresh values and hooks and aliases share one expansion model. Two consequences: a pipeline step with an undefined variable fails when that step is reached (earlier steps run first), and a template error in a background hook surfaces in the hook log rather than failing the foreground command. The background runner also labels template errors the way the foreground does. ([#3042](max-sixty/worktrunk#3042), [#3047](max-sixty/worktrunk#3047))

- **`wt config state cache`**: The regenerable caches (CI status, branch summaries, git-command caches, hints, the `wt switch -` target) are consolidated under `wt config state cache`; `cache clear` drops them all without prompting, since everything regenerates. `wt config state clear`, which also wipes hand-authored markers and vars, now asks for confirmation; `--yes` skips, and non-interactive runs without `--yes` cancel. The `ci-status`, `hints`, and `previous-branch` subcommands are deprecated but still work. ([#3027](max-sixty/worktrunk#3027))

- **Statusline rate-limit segment**: Above 90% of the binding window the segment shows the used percentage (`95%(8:30am–1:30pm)`) instead of the pace ratio; near the cap, what's left matters more than the rate. The pace form drops the word "pace" (`2.9×(Tue–Tue 5pm)`), and `-vv` logs each window's inputs and selection to `.git/wt/logs/trace.log` so the binding-window choice can be reconstructed. ([#3057](max-sixty/worktrunk#3057), [#3053](max-sixty/worktrunk#3053), [#3029](max-sixty/worktrunk#3029))

- **`/wt-switch-create` branch name is optional**: The Claude Code plugin command picks a branch name from the task when none is given, and the skill's workflow is one route (create, then enter) with an error-driven fallback instead of three guarded paths. Worktrees created mid-session persist after the session ends. ([#3058](max-sixty/worktrunk#3058))

### Fixed

- **Plugin worktree hooks fail before side effects**: The Claude Code plugin's `WorktreeCreate`/`WorktreeRemove` hooks validate the payload before running `wt`; a malformed payload previously created a branch named `null` or could remove the wrong worktree. `wt remove`'s help now documents that the positional argument accepts a worktree path as well as a branch name. ([#3058](max-sixty/worktrunk#3058), [#3060](max-sixty/worktrunk#3060))

- **Waiting-for-input marker covers questions, permission prompts, and turn end**: The Claude Code plugin sets the 💬 marker on `AskUserQuestion`, permission requests, and turn end. Previously only the `Notification` event set it, which never fires for the built-in question picker (and on some platforms not for permission prompts), so the marker stayed 🤖 while Claude waited. Part of [#2916](max-sixty/worktrunk#2916). ([#3023](max-sixty/worktrunk#3023), thanks @Ismael for reporting)

- **`wt list --help` no longer panics when piped**: With no detectable terminal width (output piped, `COLUMNS` unset), `wt list --help` panicked with a capacity overflow, and the post-commit diffstat truncated filenames to ~10 characters. Both now handle unknown width. ([#3040](max-sixty/worktrunk#3040))

- **Deprecation warnings match `wt config update`**: A config deprecation warning now fires exactly when `wt config update` would change the file. The old detection and migration logic had drifted in several places: `ff` and `no-ff` together silently dropped `no-ff`, a scalar `forge` key was overwritten by the `[ci]` migration, an empty `[ci] platform` migrated without warning, and an empty `approved-commands = []` could be removed by an unrelated update. ([#3055](max-sixty/worktrunk#3055))

- **Migrated `[forge]` keeps `[ci]`'s spot**: The `[ci]` → `[forge]` migration rendered the new section at the end of the file and could drop comments above `[ci]`; it now takes over `[ci]`'s position, comments included, so `wt config show` and `wt config update` diffs stay minimal. ([#3051](max-sixty/worktrunk#3051))

- **`wt config state get` is read-only**: The aggregate dump resolved (and re-cached) the default branch, so running it right after `clear` silently repopulated the cache, and on a cold clone it could hit the network. It now reports the cached value or `(none)`. `wt config state default-branch get` still resolves and caches. ([#3024](max-sixty/worktrunk#3024))

### Documentation

- **Reading vs resolving cached state**: `wt config state default-branch get` resolves and caches; the aggregate `wt config state get` only reports the cache. The help text and module docs now state the split. ([#3028](max-sixty/worktrunk#3028))

### Internal

- `wt switch`/`wt remove` orchestration moved from `main.rs` to their command modules, and the hook execution call chain lost two delegation layers. ([#3049](max-sixty/worktrunk#3049), [#3036](max-sixty/worktrunk#3036))

- Config deprecations are driven by a single rule table; each rule is one function that migrates and reports what it changed. ([#3045](max-sixty/worktrunk#3045), [#3055](max-sixty/worktrunk#3055))

- `terminal_width()` returns `Option<usize>` instead of a `usize::MAX` sentinel, making the no-width case a compile-time concern. ([#3043](max-sixty/worktrunk#3043))

- Snapshot tests regenerate identically across machines: host-specific paths are guarded, host-dependent env-block markers are normalized, and help snapshots share one settings builder. ([#3009](max-sixty/worktrunk#3009), [#3026](max-sixty/worktrunk#3026), [#3037](max-sixty/worktrunk#3037), [#3061](max-sixty/worktrunk#3061))

- Nightly CI runs lib tests across the full feature powerset. ([#3059](max-sixty/worktrunk#3059))

- MSRV bumped from 1.94 to 1.95. ([#2948](max-sixty/worktrunk#2948))

## Install worktrunk 0.58.0

### Install prebuilt binaries via shell script

```sh
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-installer.sh | sh && wt config shell install
```

### Install prebuilt binaries via powershell script

```sh
powershell -ExecutionPolicy Bypass -c "irm https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-installer.ps1 | iex"; git-wt config shell install
```

### Install prebuilt binaries via Homebrew

```sh
brew install worktrunk && wt config shell install
```

## Download worktrunk 0.58.0

|  File  | Platform | Checksum |
|--------|----------|----------|
| [worktrunk-aarch64-apple-darwin.tar.xz](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-aarch64-apple-darwin.tar.xz) | Apple Silicon macOS | [checksum](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-aarch64-apple-darwin.tar.xz.sha256) |
| [worktrunk-x86_64-apple-darwin.tar.xz](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-x86_64-apple-darwin.tar.xz) | Intel macOS | [checksum](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-x86_64-apple-darwin.tar.xz.sha256) |
| [worktrunk-x86_64-pc-windows-msvc.zip](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-x86_64-pc-windows-msvc.zip) | x64 Windows | [checksum](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-x86_64-pc-windows-msvc.zip.sha256) |
| [worktrunk-aarch64-unknown-linux-musl.tar.xz](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-aarch64-unknown-linux-musl.tar.xz) | ARM64 MUSL Linux | [checksum](https://github.com/max-sixty/worktrunk/releases/download/v0.58.0/worktrunk-aarch64-unknown-linux-musl.tar.xz.sha256) |

See merge request: Harmonybrew/homebrew-core!11501
max-sixty added a commit that referenced this pull request Nov 15, 2026
…lready decided (#4787)

A hook with an unguarded `{{ branch }}` can't expand in a detached
worktree, where `branch` is unset by design (#4009). In a background
hook that failure was silent: the runner renders each step (#3042), so
`wt remove` announced the `post-remove` hook, exited 0, and the error
reached only `runner.log`. In a jj-colocated repo, where every worktree
is detached, that happens on every removal.

Hook preparation already rejects a template that can't parse before any
step runs. `PreparedPipeline::validated` now also rejects one whose
render fails without reading anything an earlier step can change, which
excludes `vars.*` on a branch and Worktrunk's template functions. Such a
template gets the same error and exit status as a syntax error, in every
hook, foreground and background. An error that depends on `vars` or a
function still surfaces when its step runs. The hook help says so, and
points a command that identifies the worktree at `worktree_name` or
`worktree_path`.

Worth weighing: `wt remove` with such a `post-remove` hook now removes
the worktree, prints the error and exits 1, as a syntax error already
makes it. Blocking hooks such as `pre-remove` now fail before step 1
rather than at the broken step, which reverses part of #3042's deferral
for errors decided at preparation. Aliases keep deferring every
expansion error to its step, and the picker's alt-x removal sends the
error only to the debug log, as it does for syntax errors.

johnstegeman reported this in
[rex-config#9](https://redirect.github.com/johnstegeman/rex-config/pull/9).
Requested by max-sixty. With the source change reverted, the new
detached `post-remove` test and the new decided-error foreground case
fail; with it they pass. The run-time tests now use a `vars`-dependent
fixture that really is deferred, and the hooks, remove, prune, merge,
switch, picker and alias integration tests pass.

> _This was written by Claude Code on behalf of max-sixty_
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