Skip to content

refactor(alias)!: source-tag steps and decide EXEC per-step - #2474

Merged
max-sixty merged 8 commits into
mainfrom
fix/issue-2101-user-alias-execute
May 1, 2026
Merged

max-sixty merged 8 commits into
mainfrom
fix/issue-2101-user-alias-execute

Conversation

@worktrunk-bot

@worktrunk-bot worktrunk-bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Two phases on the same theme — making per-source policy first-class instead of working around a name-keyed merge.

Phase 1 — source-tag steps, decide EXEC per-step:

  • SourcedStep (hook_type now Option<HookType>) is the shared sourced-step type; sourced_steps_to_foreground(steps, &PipelineKind) is the single resolver. User-source alias steps get DirectivePassthrough::inherit_from_env_with_exec(); everything else (project-source alias steps, hooks of either source) gets inherit_from_env().
  • ForegroundStep carries its own directives field, so execute_pipeline_foreground no longer takes a per-pipeline &DirectivePassthrough.
  • Removed the name-keyed project_aliases_contain EXEC switch — replaced by the per-step decision the source tag carries.

Phase 2 — key aliases by name + source instead of merging:

  • AliasMap = BTreeMap<String, AliasEntry { user, project }> replaces the BTreeMap<String, CommandConfig> that was previously built via append_aliases. Same-name collisions are no longer a special case — the data shape carries both sources directly.
  • load_aliases(repo, user_config, project_config) is the single resolver. load_merged_aliases, alias_needs_approval, and prepare_alias_sourced_steps are gone.
  • run_alias takes &AliasEntry, drops the duplicate user_config.aliases(...) lookup, drops the project_config and merged-map parameters; approval reads entry.project.as_ref().
  • format_alias_announcement walks both sources in runtime order.
  • unknown_alias_error (config/alias.rs) routes through load_aliases for canonical name iteration.
  • load_aliases_for_completion returns AliasMap; stub builders use entry.representative() for help text (user wins, matching the announcement order).
  • append_aliases is no longer used by alias dispatch — it survives inside UserConfig::aliases for the global vs. per-project user-config merge, which is a different axis.

Addresses @vandamm's use case directly:

[aliases]  # in the user's config — ~/.config/worktrunk/config.toml
issue = "wt switch --create {{ args | join('-') | lower }} -x claude -- 'Read Linear issue {{ args[0] | upper }} via the linear MCP and propose an approach.'"

wt issue XX-1200 add-button now lands the user in the new worktree and execs claude in their interactive shell.

Behavior change vs prior release

Same-name user+project alias collisions used to scrub EXEC for the whole merged pipeline — a conservative side effect of name-keyed merging in append_aliases. With per-step decisions, the user's own steps keep the EXEC relaxation; only the project-authored steps scrub. Strictly more permissive than the prior approach.

Test plan

  • test_user_alias_passes_exec_directive — user alias body running wt switch --execute echo from-user-alias writes the payload to the parent's EXEC file and emits no scrub warning.
  • test_project_alias_scrubs_exec_directive — project alias body running the same command leaves the EXEC file empty, emits the warning with the issue link, and exits 0.
  • test_user_and_project_alias_collision_scrubs_only_project_step — same alias name in both configs: user-step EXEC payload lands in the EXEC file, project-step EXEC payload is scrubbed, project warning fires once.
  • test_format_alias_announcement_concatenates_user_and_project — collision banner walks user steps first, then project steps.
  • Existing test_switch_exec_scrubbed_warns snapshot updated for the new wording.
  • cargo test --test integration — 1584 passed, 0 failed.
  • cargo clippy --all-targets clean.
  • cargo run -- hook pre-merge --yes — 3404/3404 tests, all lints pass end-to-end.

User-source aliases live in the user's own config, so a nested
`wt switch --execute claude` inside an alias body is no different from
the user typing the same command at the top level. Drop the conservative
EXEC scrub for user aliases and reword the refusal hint to point folks
with project-alias / hook needs at #2101.

Project aliases and hooks keep the existing scrub: bodies authored in
shared config still must not be able to inject arbitrary shell into a
contributor's interactive session.

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

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Behavior looks right — user-source aliases get the relaxation, project aliases and hooks keep the scrub, and the new directive_exec_file plumbing mirrors the existing CD path through Cmd, output::handlers, and output::concurrent.

One concrete concern: the project_aliases_contain doc comment misdescribes how same-name aliases merge. append_aliases (src/config/commands.rs:185) uses merge_append, which concatenates steps (user first, then project) — see test_alias_append_executes_both — so a same-named project alias does not "shadow" the user entry. The runtime choice is still correct (return true → scrub EXEC), but the rationale needs to be "the merged pipeline runs project-authored steps too, so we can't selectively pass EXEC to user steps only." Inline suggestion below.

Same-name collision case is also unverified by the new tests. Worth a third case alongside test_user_alias_passes_exec_directive / test_project_alias_scrubs_exec_directive — define the same alias name in both user and project config, assert EXEC is scrubbed and the warning fires.

Comment thread src/commands/alias.rs Resolved
Doc on `project_aliases_contain` claimed project entries shadow user
entries — they don't. `append_aliases` concatenates steps (user first,
then project), so a same-named project alias means the merged pipeline
runs project-authored steps, which is why we conservatively scrub EXEC
for the entire body.

Also adds an integration test for the collision case alongside
`test_user_alias_passes_exec_directive` /
`test_project_alias_scrubs_exec_directive`.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@max-sixty

Copy link
Copy Markdown
Owner

We need to design our data structure so we're not searching by name; more similar to hooks. that's also an opportunity for consolidation

@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Sketch of the redesign: have alias resolution mirror hooks — return a Vec<SourcedStep> (each step tagged with HookSource::User/Project) rather than name-keyed merging in append_aliases. EXEC passthrough then becomes per-step (user → pass, project → scrub), which is strictly more permissive than this PR's "any project step scrubs the whole pipeline" and makes the same-name collision case fall out for free — the user's own steps still get the relaxation in a merged body.

Consolidation lever: src/commands/alias.rs currently builds its own ForegroundStep list inline; with sourced steps it can flow through the same prepare_sourced_steps / SourcedStep shape src/commands/hooks.rs already uses, so alias and hook dispatch share one resolution pipeline.

Tradeoff to flag: DirectivePassthrough is per-pipeline today — a single value handed to execute_pipeline_foreground. Per-step source-aware EXEC means either threading directives into ForegroundStep or letting the executor pick by source; threading keeps the executor unaware of trust. Want me to spike the redesign on this branch, or close this PR and reopen with the source-tagged structure?

@max-sixty

Copy link
Copy Markdown
Owner

yes please

…pipeline

Previously, alias dispatch merged user and project alias bodies through
`append_aliases` and decided EXEC passthrough by checking whether the
project config defined a same-name alias (`project_aliases_contain`).
The lookup was name-keyed and the decision was per-pipeline, so a
same-name collision scrubbed EXEC for the whole merged body — including
the user's own steps.

Mirror the hook resolution shape:

- `SourcedStep` becomes the shared shape for both alias and hook
  dispatch (`hook_type` is now `Option<HookType>` so aliases can leave
  it `None`).
- `ForegroundStep` carries its own `DirectivePassthrough`, so
  `execute_pipeline_foreground` no longer takes a per-pipeline
  `directives` argument.
- `sourced_steps_to_foreground(steps, &PipelineKind)` is the single
  resolver: hook steps and project-source alias steps get
  `inherit_from_env()` (CD only); user-source alias steps get
  `inherit_from_env_with_exec()`.
- `prepare_alias_sourced_steps` builds the alias side from per-source
  `CommandConfig` lookups, dropping the merged-execution path and the
  `project_aliases_contain` name search.

Net behavior change: when both user and project define the same alias,
the user's steps now keep the EXEC relaxation while the project's steps
still scrub. Strictly more permissive than the previous per-pipeline
scrub, which was a conservative side effect of name-keyed merging.

Updated `test_user_and_project_alias_collision_scrubs_exec_directive` →
`test_user_and_project_alias_collision_scrubs_only_project_step` to
assert the new per-step behavior end-to-end.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@worktrunk-bot worktrunk-bot changed the title feat(alias): pass --execute through user-source alias bodies refactor(alias)!: source-tag steps and decide EXEC per-step Apr 30, 2026
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Spiked the redesign on this branch (787a445). Sketch from the earlier comment materialized as:

  • SourcedStep is now the shared shape for hook + alias dispatch (hook_type becomes Option<HookType>; aliases leave it None). prepare_alias_sourced_steps builds the alias side from per-source CommandConfig lookups (user_config.aliases(...).get(name) + project.aliases.get(name)) — no name-keyed merge in the execution path.
  • ForegroundStep carries its own DirectivePassthrough, so execute_pipeline_foreground no longer takes a per-pipeline directives argument.
  • sourced_steps_to_foreground(steps, &PipelineKind) is the single resolver. Trust is per-step: user-source alias steps get inherit_from_env_with_exec(); project-source alias steps and all hook steps get inherit_from_env(). Both run_alias and run_hooks_foreground flow through this — alias and hook dispatch share the resolution pipeline.
  • Dropped project_aliases_contain entirely; the EXEC switch is now derived from each step's HookSource.

One behavior change worth flagging: same-name user+project alias collisions previously scrubbed EXEC for the whole merged pipeline. With per-step decisions, the user's own steps keep the relaxation; only the project-authored steps scrub. Strictly more permissive than before, and the same-name collision case now falls out of the source tag rather than needing a special branch. test_user_and_project_alias_collision_scrubs_exec_directive was renamed to ..._scrubs_only_project_step and updated to assert the new shape end-to-end (user payload lands in the EXEC file; project payload doesn't; warning fires once for the project step).

Net diff: +209 / -111 across alias.rs, command_executor.rs, hooks.rs, and the integration test. cargo test --test integration 1571/1571 passed; clippy clean.

@max-sixty

Copy link
Copy Markdown
Owner

can you explain re the merged user + project alias? why are we merging them?

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

can you explain re the merged user + project alias? why are we merging them?

The user+project merge is preexisting, not introduced here. append_aliases (src/config/commands.rs:185) follows the same pattern as merge_append_hooks for hook layers — when both configs define the same name, both run (user first, then project). Anchored by test_alias_append_executes_both (cross-source) and test_aliases_accessor_appends_on_collision (global vs per-project user). The rationale baked into the doc comment is "matching how hooks merge across config layers": a project shouldn't silently disable a user's same-named alias by reusing the name, and the project side still goes through approval.

What this PR changes is how the merged execution is built — not what merges with what. Before: load_merged_aliases produced a single CommandConfig via append_aliases and the executor saw an opaque step list, so EXEC trust had to be a per-pipeline scrub keyed on "does the project define this name?". Now: steps stay source-tagged end-to-end, so the executor decides EXEC trust per-step. Same steps in the same order, just a different shape.

If the design question is actually whether merging is the right behavior at all (vs. shadowing or erroring on collision), that's orthogonal to this PR — happy to spike as a separate change.


Unrelated FYI: PR is mergeStateStatus: DIRTY — main has moved (HookAnnouncer refactors in #2484 / #2482, resolve_command_str extraction in #2476) and conflicts touch alias.rs, command_executor.rs, hooks.rs, output/{global,handlers}.rs, and the integration test. Will rebase once you've signed off on the redesign.

@max-sixty

Copy link
Copy Markdown
Owner

can we trigger both, but avoid merging them?

either have a go here, or add a Todo and we'll take it in another PR

@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

CI status note: the pull_request synchronize trigger didn't fire ci.yaml for 787a445c — only tend-review (which uses pull_request_target) ran on the push. GitHub is reporting an unresolved incomplete pull request results incident touching Pull Requests since 2026-04-28, which matches the symptom. I manually dispatched ci.yaml against the same SHA: all required jobs pass (lint, test (linux), test (macos), test (windows), code-coverage, feature-check, check-docs, check-unused-dependencies, msrv). benchmarks is still running per usual (non-required). The manual run won't show up in the PR rollup, so the rollup will look incomplete until the next pull_request event re-triggers.

The execution path is already source-aware after 787a445 —
`prepare_alias_sourced_steps` builds from per-source `CommandConfig`
lookups. The remaining merged map only serves orchestration (existence
check, referenced-vars union for arg parsing, announcement banner).
Document the follow-up shape (`BTreeMap<String, Vec<(HookSource,
CommandConfig)>>`) so the next PR can land it without re-deriving the
rationale.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

can we trigger both, but avoid merging them?

Good news — the spike at 787a445c already pulled merging out of the execution path. prepare_alias_sourced_steps builds steps from per-source CommandConfig lookups (user_config.aliases(...).get(name) + project.aliases.get(name)); both run, neither one is ever folded into a merged CommandConfig before execution.

What's still merged is the orchestration map (load_merged_aliases). Three uses:

  1. Existence check — aliases.get(&name) to decide "is this an alias at all?" before we parse args (try_alias) or synthesize an unknown-subcommand error (step_alias).
  2. Referenced-vars union — referenced_vars_for_config(cmd_config) feeds AliasOptions::parse so --KEY=VALUE routes correctly. Has to be the union across both bodies: if the user body references {{ env }} and the project body doesn't, --env=prod should still bind, not forward.
  3. Announcement banner — format_alias_announcement summarizes the merged step list.

Cleanest follow-up shape is BTreeMap<String, Vec<(HookSource, CommandConfig)>>: existence stays a single key probe, referenced-vars unions across the Vec, announcement either combines per-source summaries or emits two lines. Same observable behavior, no merged CommandConfig anywhere.

Going with the TODO option for now — added at src/commands/alias.rs:333 (ee3ed661). The PR is already a substantive \! refactor; stacking the orchestration cleanup feels like it'd dilute the EXEC-per-step story you just signed off on. Happy to spike it as the next PR.

@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot resolve conflicts

@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Merged main into the branch (9bde1b5b). Two real conflicts in src/commands/alias.rs and src/commands/hooks.rs, both around the same axis: main's redirect_stdout_to_stderr field on ForegroundStep (added in #2479 for alias stdout passthrough) vs. this branch's sourced_steps_to_foreground resolver. Resolved by keeping the resolver and routing the new field through it: Hook → true (merge stdout onto stderr so child output stays ordered with wt's announcement lines), Alias → false (passthrough so wt <alias> | … works in scripts). Same observable behavior as the per-call inline construction main was using, just decided once in the resolver instead.

Auto-merged everywhere else (incl. all the snapshot files, output/{global,handlers}.rs, and the integration test). cargo clippy --all-targets clean; cargo test --test integration step_alias 74/74 passed locally. Full cargo test --test integration has 82 pre-existing failures on this CI runner (mock-cargo PATH override not being picked up — test_docs_hook_pre_merge reproduces verbatim on a fresh origin/main checkout in the same environment), unrelated to the merge.

max-sixty and others added 3 commits April 30, 2026 20:46
Replace the merged `BTreeMap<String, CommandConfig>` from the alias
dispatch path with `AliasMap = BTreeMap<String, AliasEntry { user,
project }>`. Same-name collisions are no longer a special case: the
data shape carries both sources directly, so consumers never have to
reconstitute the source split.

- `load_aliases(repo, user_config, project_config)` is the single
  resolver. `load_merged_aliases`, `alias_needs_approval`, and
  `prepare_alias_sourced_steps` are gone.
- `run_alias` takes `&AliasEntry`, drops the duplicate
  `user_config.aliases(...)` lookup, drops `project_config` and the
  merged-map parameter; approval reads `entry.project.as_ref()`.
- `format_alias_announcement` walks both sources in runtime order.
- `unknown_alias_error` (config/alias.rs) and `entries_for_name`
  route through `load_aliases`.
- `load_aliases_for_completion` returns `AliasMap`; stub builders use
  `entry.representative()` for help text (user wins, matching the
  announcement order).
- `append_aliases` is no longer used by alias dispatch — it survives
  inside `UserConfig::aliases` for the global vs. per-project
  user-config merge, which is a different axis.

Same observable behavior; one canonical resolver, three callers
(dispatch, completion, `config alias show/dry-run`).

Co-Authored-By: Claude <[email protected]>
# Conflicts:
#	src/commands/alias.rs
#	src/commands/hooks.rs
#	src/output/handlers.rs
…okup

Drop comments that just narrate what the next line does ("Build JSON
context for stdin", etc.). Keep the non-obvious WHYs.

Revert `entries_for_name` to per-source `.get(name)` instead of
`load_aliases().remove(name)`. The latter built the full AliasMap
(allocating + cloning every alias's CommandConfig) just to read one
entry — strictly more work for a UI-command path that only ever wants
one name. Direct lookup is what the original code did.

Co-Authored-By: Claude <[email protected]>
@max-sixty
max-sixty merged commit af3be9e into main May 1, 2026
25 checks passed
@max-sixty
max-sixty deleted the fix/issue-2101-user-alias-execute branch May 1, 2026 04:11
max-sixty added a commit that referenced this pull request May 1, 2026
## Summary

When `wt switch <number>` fails because no branch by that name exists,
the hint now leads with how to switch to the matching PR/MR before
mentioning `--create`.

Platform is detected by hostname-matching the primary remote's effective
URL (so `url.insteadOf` rewrites are respected):
- **GitHub** → `wt switch pr:N`
- **GitLab** → `wt switch mr:N`
- **Unknown / opaque host** → both suggestions

Non-numeric branch names keep the original hint unchanged.

### Before

```
✗ No branch named 2474
↳ To create a new branch, run wt switch --create 2474; to list branches, run wt list --branches --remotes
```

### After (GitHub)

```
✗ No branch named 2474
↳ To switch to PR #2474, run wt switch pr:2474; to create a new branch, run wt switch --create 2474; to list branches, run wt list --branches --remotes
```

## Test plan

- [x] Snapshot tests cover GitHub, GitLab, and unknown-platform variants
- [x] Direct test for `Repository::detect_ref_type` covers all URL
branches
- [x] Existing `branch_not_found` snapshots unchanged (non-numeric
names)
- [x] `cargo run -- hook pre-merge --yes` passes (3412 tests, all lints)
- [x] Manual smoke test in temp repo: GitHub remote → `pr:N`, GitLab
remote → `mr:N`, no remote → both

---------

Co-authored-by: Claude <[email protected]>
max-sixty added a commit that referenced this pull request May 2, 2026
…ce enum (#2521)

Two follow-ups deferred from #2474, plus a coverage refinement on review
feedback.

## Lift hook-only metadata onto `PipelineKind::Hook`

`SourcedStep::hook_type: Option<HookType>` and `display_path:
Option<PathBuf>` were a smell — the invariant is per-pipeline, not
per-step, but living on `SourcedStep` forced four `.expect("hook
pipelines always set hook_type")` sites. Lifted both onto
`PipelineKind::Hook { hook_type, display_path }`, mirroring `Alias {
name }`. The invariant now lives on the type, and
`sourced_steps_to_foreground` reads the metadata directly from `kind`.

Background flow doesn't need `PipelineKind` at all — it only ever
handles hooks (aliases run in the foreground). Threading `PipelineKind`
through it forced two `unreachable!()` and one defensive `continue` for
the structurally unreachable `Alias` variant. Background functions now
take a `BackgroundPipeline` type alias for `(CommandContext, HookType,
Option<PathBuf>, Vec<SourcedStep>)` directly.

Touches `prepare_background_pipelines`, `run_hooks_background`,
`print_background_variable_table`, `spawn_hook_pipeline_quiet`,
`sourced_steps_to_foreground`, `run_hooks_foreground`, and the alias and
hook-commands call sites.

## Unify `AliasSource` into `HookSource`

`AliasSource` and `HookSource` were near-identical `User`/`Project`
enums. Removed `AliasSource`; all alias call sites now use `HookSource`.
The shared enum gains `PartialOrd`/`Ord` derives (needed for `(name,
source)` listing sort) and an updated docstring covering dual hook+alias
usage. `source.label()` becomes `{source}` via the existing
`strum::Display`.

## Test plan
- [x] `cargo nextest run` — 3261 tests pass (incl. new
`test_combined_post_remove_and_post_switch_hooks_verbose` covering the
multi-hook-type filter in `print_background_variable_table`)
- [x] `pre-commit run --all-files` — green
- [x] Snapshot tests unchanged for existing flows

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude <[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