Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

85.0 KB
Raw Blame
//! Integration tests for `wt step <alias>`

use crate::common::{
    TestRepo, configure_directive_file, directive_file, make_snapshot_cmd,
    make_snapshot_cmd_with_global_flags, repo, repo_with_remote, setup_snapshot_settings, wt_bin,
};
// Used only by the `#[cfg(unix)]` signal tests below; gate the import to match,
// or it reads as unused on Windows under `-D warnings`.
#[cfg(unix)]
use crate::common::{SLEEP_FOR_ABSENCE_CHECK, SignalJob};
use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::io::Write;
use std::process::Stdio;

/// Alias from project config runs with template expansion (-y bypasses approval)
#[rstest]
fn test_step_alias_from_project_config(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["hello"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Alias expansion errors retain the alias identity and underlying diagnostic.
#[rstest]
fn test_step_alias_runtime_undefined_variable(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo {{ nope }}"
"#,
    );
    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["deploy"], None));
    });
}

/// `wt config alias dry-run <name>` shows the expanded command without running it
/// (no approval needed — preview never executes project commands).
#[rstest]
fn test_config_alias_dry_run(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "hello"],
        Some(&feature_path),
    ));
}

/// Unknown alias shows error with available aliases
#[rstest]
fn test_step_alias_unknown_with_available(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello"
deploy = "make deploy"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["nonexistent"],
        Some(&feature_path),
    ));
}

/// Typo in alias name suggests the closest match
#[rstest]
fn test_step_alias_did_you_mean(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo Hello"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deplyo"],
        Some(&feature_path),
    ));
}

/// Unknown step command with no aliases configured
#[rstest]
fn test_step_alias_unknown_no_aliases(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// `--KEY=VALUE` binds to `{{ KEY }}` when the template references it.
#[rstest]
fn test_step_alias_binds_referenced_var(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
greet = "echo Hello {{ name }} from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "greet", "--", "--name=World"],
        Some(&feature_path),
    ));
}

/// `--KEY VALUE` (space-separated) binds the same way `--KEY=VALUE` does
/// when KEY is referenced and VALUE doesn't look like a flag.
#[rstest]
fn test_step_alias_binds_space_separated_var(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
greet = "echo Hello {{ name }} from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "greet", "--", "--name", "World"],
        Some(&feature_path),
    ));
}

/// `--KEY=VALUE` for a key the template doesn't reference forwards to
/// `{{ args }}` instead of binding silently.
#[rstest]
fn test_step_alias_unreferenced_key_forwards_to_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &["--env=staging", "foo"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `--args=VALUE` can't bind `{{ args }}` — the alias's own positional list
/// fills that slot — so the token forwards into it rather than vanishing.
#[rstest]
fn test_step_alias_args_flag_forwards_to_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["-y", "run", "--args=x", "y"])
        .current_dir(&feature_path)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "alias should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("got --args=x y"),
        "--args=x should reach {{{{ args }}}}, got: {stdout}"
    );
}

/// `--` is a literal-forward escape: every later token goes to `{{ args }}`,
/// so flag-shaped values that would normally bind are passed through verbatim.
#[rstest]
fn test_step_alias_double_dash_escape(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &["--", "--env=staging", "literal"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `--KEY=VALUE` overrides built-in template variables. The user-supplied
/// value wins because `extra_refs` is applied after built-ins are seeded.
#[rstest]
fn test_step_alias_user_var_overshadows_builtin(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
show = "echo branch={{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "show",
        &["--branch=override"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Multi-step pipeline: each step's `{{ KEY }}` references contribute to
/// the binding-eligible set, so a single invocation can bind both `env`
/// (referenced in step 1) and `region` (referenced in step 2).
#[rstest]
fn test_step_alias_multi_step_binds_across_pipeline(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = [
    "echo step1 env={{ env }}",
    { publish = "echo step2 region={{ region }}" },
]
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    let mut cmd = make_snapshot_cmd(
        &repo,
        "step",
        &["deploy", "--env=prod", "--region=us-east"],
        Some(&feature_path),
    );
    cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
    assert_cmd_snapshot!(cmd);
}

/// Alias body output is delivered on stdout so it can be piped into other
/// commands (#2478). Worktrunk's own progress/announcement messages still go
/// to stderr; only the child shell's stdout passes through.
#[rstest]
fn test_alias_body_writes_to_stdout(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
emit = "echo hello"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["-y", "emit"])
        .current_dir(&feature_path)
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "alias failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.lines().any(|line| line.trim() == "hello"),
        "expected `hello` on stdout (so `wt <alias> | …` is usable in scripts), \
         got stdout={stdout:?} stderr={stderr:?}"
    );
}

/// A one-entry alias table is a single named command, not a concurrent group
/// of one: its output passes through on stdout without a `name │` prefix,
/// identical to the string and `[[aliases.x]]` spellings.
#[rstest]
fn test_alias_single_entry_table_writes_to_stdout(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases.emit]
say = "echo hello"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["-y", "emit"])
        .current_dir(&feature_path)
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "alias failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.lines().any(|line| line.trim() == "hello"),
        "expected unprefixed `hello` on stdout, got stdout={stdout:?} stderr={stderr:?}"
    );
    assert!(
        !stdout.contains('│') && !stderr.contains("say │"),
        "single named command must not use the concurrent `name │` prefix, \
         got stdout={stdout:?} stderr={stderr:?}"
    );
}

/// Alias command failure propagates exit code (-y bypasses approval)
#[rstest]
fn test_step_alias_exit_code(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
fail = "exit 42"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["fail"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// An alias child killed by a signal other than INT/TERM is reported: the
/// child printed nothing about its death, and wt exits `128 + signal` rather
/// than dying by it, so no shell reports it either.
#[cfg(unix)]
#[rstest]
fn test_step_alias_killed_by_signal(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
crash = "kill -KILL $$"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["crash"], None));
}

/// Alias from user config works
#[rstest]
fn test_step_alias_from_user_config(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
greet = "echo Greetings from {{ branch }}"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["greet"],
        Some(&feature_path),
    ));
}

/// Top-level alias dispatch: `wt <name>` runs an alias when `<name>` is not
/// a built-in subcommand, with the same template-expansion and approval flow
/// as `wt step <name>`.
#[rstest]
fn test_top_level_alias_dispatch(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
hello = "echo Hello from {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "hello",
        &[],
        Some(&feature_path),
        &["-y"],
    ));
}

/// An alias whose name matches a `wt step` built-in is unreachable via
/// `wt step <name>` (the built-in always wins) but runs from the top level
/// via `wt <name>` — there's no top-level `commit` built-in.
#[rstest]
fn test_top_level_alias_with_step_builtin_name(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
commit = "echo custom-commit"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "commit",
        &[],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Top-level typo on an alias name suggests the alias in the `tip:` line,
/// matching `wt step <typo>`.
#[rstest]
fn test_top_level_alias_did_you_mean(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo Hello"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "deplyo", &[], Some(&feature_path),));
}

/// Aliases shadowed by `wt step` built-ins are filtered from the typo
/// suggestion list — `wt step commit` does not suggest a (shadowed) alias
/// named `commit`, only the real built-in.
#[rstest]
fn test_step_alias_shadows_builtin(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
commit = "echo custom-commit"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["comit"],
        Some(&feature_path),
    ));
}

/// User config aliases merge with project config aliases
#[rstest]
fn test_step_alias_merge_user_and_project(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
project-cmd = "echo from-project"
shared = "echo project-version"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
user-cmd = "echo from-user"
shared = "echo user-version"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // User alias available
    assert_cmd_snapshot!(
        "user_alias",
        make_snapshot_cmd(
            &repo,
            "config",
            &["alias", "dry-run", "user-cmd"],
            Some(&feature_path),
        )
    );

    // Project alias available — dry-run never needs approval (it doesn't execute).
    assert_cmd_snapshot!(
        "project_alias",
        make_snapshot_cmd(
            &repo,
            "config",
            &["alias", "dry-run", "project-cmd"],
            Some(&feature_path),
        )
    );

    // Both definitions visible on collision: user first, then project (matches runtime order).
    assert_cmd_snapshot!(
        "user_and_project_append",
        make_snapshot_cmd(
            &repo,
            "config",
            &["alias", "dry-run", "shared"],
            Some(&feature_path),
        )
    );
}

/// Both global and per-project user aliases execute in order on name collision.
///
/// Uses project config (`.config/wt.toml`) + user config to verify the
/// project-vs-user append, since `test_aliases_accessor_appends_on_collision`
/// already covers the user-config internal append via unit test.
#[rstest]
fn test_alias_append_executes_both(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
greet = "echo PROJECT"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
greet = "echo USER"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Both commands execute: user first, then project (-y approves project alias)
    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["greet"],
        Some(&feature_path),
        &["-y"],
    ));
}

// ============================================================================
// Approval tests
// ============================================================================

/// Project-config alias prompts for approval in non-TTY (fails with hint)
#[rstest]
fn test_alias_approval_project_config_prompts(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Without --yes, project alias triggers approval prompt (fails in non-TTY)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// Already-approved project-config alias runs without re-prompting
#[rstest]
fn test_alias_approval_already_approved(mut repo: TestRepo) {
    // Remove origin so worktrunk uses directory name as project identifier
    repo.run_git(&["remote", "remove", "origin"]);

    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying {{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    // Pre-approve the alias command
    repo.write_test_approvals(&format!(
        r#"[projects.'{}']
approved-commands = ["echo deploying {{{{ branch }}}}"]
"#,
        repo.project_id()
    ));

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Should run without prompting
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// User-config alias skips approval entirely
#[rstest]
fn test_alias_approval_user_config_skips(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo deploying from user config"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // User alias runs without approval
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
    ));
}

/// User override of project alias skips approval (user is trusted)
#[rstest]
fn test_alias_approval_user_and_project_both_need_approval(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo project deploy"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo user deploy"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Both run with -y: user first, then project (project needs approval)
    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "step",
        &["deploy"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// -y bypasses approval for project-config alias without saving
#[rstest]
fn test_alias_approval_yes_bypasses(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo deploying"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // First run with -y succeeds
    assert_cmd_snapshot!(
        "alias_approval_yes_first_run",
        make_snapshot_cmd_with_global_flags(
            &repo,
            "step",
            &["deploy"],
            Some(&feature_path),
            &["-y"],
        )
    );

    // Second run without -y should still prompt (-y doesn't save approval)
    assert_cmd_snapshot!(
        "alias_approval_yes_second_run_prompts",
        make_snapshot_cmd(&repo, "step", &["deploy"], Some(&feature_path),)
    );
}

// ============================================================================
// Directive file passthrough
// ============================================================================

/// `wt step <alias>` passes the parent's `WORKTRUNK_DIRECTIVE_CD_FILE` through
/// to the alias subprocess so inner `wt switch --create` calls can land the
/// user in the new worktree.
///
/// Regression test for #2075: without the passthrough, an alias that wraps
/// `wt switch --create` prints the "shell integration not installed" hint and
/// the parent shell never `cd`s into the new worktree.
#[rstest]
fn test_alias_passes_directive_file_to_subprocess(repo: TestRepo) {
    repo.commit("initial");

    // Alias body invokes the test wt binary directly (PATH lookup in the
    // subprocess shell wouldn't find it).
    repo.write_test_config(&wt_alias_config(
        "new-branch",
        "switch --create alias-created",
    ));

    let (cd_path, _guard) = directive_file();

    let mut cmd = repo.wt_command();
    configure_directive_file(&mut cmd, &cd_path);
    cmd.args(["step", "new-branch"]);
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "wt step new-branch failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
    assert!(
        !cd_content.trim().is_empty(),
        "alias wrapping `wt switch --create` should write a path to the \
         CD directive file, got: {cd_content:?}"
    );
    assert!(
        cd_content.contains("alias-created"),
        "cd directive should target the new worktree (alias-created), got: {cd_content:?}"
    );

    // Stderr should NOT contain the "shell integration not installed" hint
    // — that hint is what appears when the inner wt can't find the directive
    // file, which is exactly the bug this test guards against.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("shell integration"),
        "inner wt should not warn about shell integration being uninstalled, got: {stderr}",
    );
}

/// Build an `[aliases]` config whose single alias body invokes the test `wt`
/// binary. Suits either config source — pass it to `write_test_config` for a
/// user alias or `write_project_config` for a project one.
///
/// The binary path has to be embedded in a TOML basic string inside a shell
/// command, so single quotes must be absent (they'd terminate the shell
/// quoting) and backslashes doubled (a Windows path like `D:\a\wt.exe` would
/// otherwise parse `\a` as a TOML escape).
fn wt_alias_config(name: &str, args: &str) -> String {
    let wt = wt_bin();
    let wt_str = wt.to_string_lossy();
    assert!(
        !wt_str.contains('\''),
        "wt binary path should not contain single quotes: {wt_str}"
    );
    let wt_toml = wt_str.replace('\\', r"\\");
    format!(
        r#"
[aliases]
{name} = "'{wt_toml}' {args}"
"#
    )
}

/// `wt switch` inside an alias body preserves the user's subdirectory position,
/// the same as a top-level `wt switch` does.
///
/// Regression test for #3723: alias steps run with the worktree root as their
/// working directory, so the nested `wt` used to see the root as the user's
/// cwd and land the shell at the target worktree's root instead of the
/// matching subdirectory.
#[rstest]
fn test_alias_wrapping_switch_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
    let feature_wt = repo.add_worktree("feature");

    // The same subdirectory exists in both worktrees.
    let subdir = std::path::Path::new("apps").join("gateway");
    std::fs::create_dir_all(repo.root_path().join(&subdir)).unwrap();
    std::fs::create_dir_all(feature_wt.join(&subdir)).unwrap();

    repo.write_test_config(&wt_alias_config("go", "switch feature"));

    let (cd_path, _guard) = directive_file();

    let mut cmd = repo.wt_command();
    configure_directive_file(&mut cmd, &cd_path);
    cmd.args(["step", "go"])
        .current_dir(repo.root_path().join(&subdir));
    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt step go failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
    let expected = feature_wt.join(&subdir);
    let expected_str = expected.to_string_lossy();
    assert!(
        cd_content.contains(&*expected_str),
        "CD file should preserve the subdirectory ({expected_str}), got: {cd_content:?}"
    );
}

/// `wt remove` inside an alias body preserves the user's subdirectory position.
///
/// Regression test for #3723: the reported case is a `remove`-wrapping alias
/// (`[aliases] finish = "wt remove -y"`) in a monorepo, which used to drop the
/// user at the primary worktree root instead of their sub-project.
#[rstest]
fn test_alias_wrapping_remove_preserves_subdir(#[from(repo_with_remote)] mut repo: TestRepo) {
    let feature_wt = repo.add_worktree("feature");

    // The same subdirectory exists in the worktree being removed (where the
    // user is) and in the main worktree (where removal lands).
    let subdir = std::path::Path::new("apps").join("gateway");
    std::fs::create_dir_all(repo.root_path().join(&subdir)).unwrap();
    std::fs::create_dir_all(feature_wt.join(&subdir)).unwrap();

    repo.write_test_config(&wt_alias_config("finish", "remove -y"));

    let (cd_path, _guard) = directive_file();

    let mut cmd = repo.wt_command();
    configure_directive_file(&mut cmd, &cd_path);
    cmd.args(["step", "finish"])
        .current_dir(feature_wt.join(&subdir));
    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt step finish failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let cd_content = std::fs::read_to_string(&cd_path).unwrap_or_default();
    let expected = repo.root_path().join(&subdir);
    let expected_str = expected.to_string_lossy();
    assert!(
        cd_content.contains(&*expected_str),
        "CD file should preserve the subdirectory ({expected_str}), got: {cd_content:?}"
    );
}

/// A nested switch runs `--execute` directly rather than depending on a
/// directive inherited through the alias shell.
#[rstest]
fn test_alias_runs_execute_directly(repo: TestRepo) {
    repo.commit("initial");

    repo.write_test_config(&wt_alias_config(
        "exec-passthrough",
        "switch --create user-alias-target --execute echo -- from-user-alias",
    ));

    let (cd_path, _guard) = directive_file();

    let mut cmd = repo.wt_command();
    configure_directive_file(&mut cmd, &cd_path);
    cmd.args(["step", "exec-passthrough"]);
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "wt step exec-passthrough failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    assert!(
        String::from_utf8_lossy(&output.stdout).contains("from-user-alias"),
        "nested --execute output missing"
    );
}

/// Alias subprocesses inherit the parent's stdin so interactive children
/// (e.g. `wt switch`'s picker) keep the controlling terminal.
///
/// Regression test for #406: alias execution used to pipe the template
/// context JSON into each child's stdin, which displaced the tty and broke
/// `stdin().is_terminal()` guards in interactive commands. Hooks no longer
/// pipe JSON either, so the `"branch"` assertion below pins the rule for
/// every foreground step rather than a hooks-vs-aliases distinction.
#[rstest]
fn test_alias_inherits_stdin(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
echo-stdin = "cat"
"#,
    );
    repo.commit("initial");

    let sentinel = "INHERITED_STDIN_TOKEN";
    let mut cmd = repo.wt_command();
    cmd.args(["step", "echo-stdin"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().unwrap();
    {
        // Drop closes the pipe so `cat` sees EOF and exits.
        let mut stdin = child.stdin.take().unwrap();
        stdin.write_all(sentinel.as_bytes()).unwrap();
    }
    let output = child.wait_with_output().unwrap();

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "wt step echo-stdin failed: stdout={stdout}\nstderr={stderr}",
    );

    // stderr carries the "Running alias" banner; the alias body's stdout is
    // redirected to stderr for deterministic ordering (see
    // `execute_shell_command`). Check the combined output.
    let combined = format!("{stdout}{stderr}");
    assert!(
        combined.contains(sentinel),
        "alias body should read the parent's stdin ({sentinel} expected), \
         got stdout={stdout:?} stderr={stderr:?}",
    );
    // The pre-fix behavior piped the context JSON (which always includes a
    // "branch" key) to stdin, so `cat` would have echoed that instead.
    assert!(
        !combined.contains("\"branch\""),
        "no foreground step should receive a JSON context on stdin, \
         got stdout={stdout:?} stderr={stderr:?}",
    );
}

/// Pipeline aliases announce their structure: named serial and concurrent
/// steps appear in the "Running alias" line, joined by `;` and `,`.
///
/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` forces the concurrent step to run
/// commands sequentially (in declaration order) so the snapshot captures a
/// deterministic interleaving — analogous to how `RAYON_NUM_THREADS=1` is
/// used in `step_prune` tests.
#[rstest]
fn test_alias_pipeline_announcement(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = [
    { install = "echo INSTALL" },
    { build = "echo BUILD", lint = "echo LINT" },
]
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    let mut cmd = make_snapshot_cmd(&repo, "step", &["deploy"], Some(&feature_path));
    cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
    assert_cmd_snapshot!(cmd);
}

/// Concurrent alias steps (named table) execute all commands
#[rstest]
fn test_alias_concurrent_steps(mut repo: TestRepo) {
    // Named table form: commands run concurrently within the step
    repo.write_test_config(
        r#"
[aliases.build]
lint = "echo LINT"
test = "echo TEST"
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "build"]).current_dir(&feature_path);
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "concurrent alias failed: stderr={}",
        String::from_utf8_lossy(&output.stderr),
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    // Both commands should have run (order may vary due to concurrency)
    assert!(stderr.contains("LINT"), "expected LINT in output: {stderr}");
    assert!(stderr.contains("TEST"), "expected TEST in output: {stderr}");
}

/// Concurrent alias commands have their output streamed with a per-command
/// colored prefix label (`{name} │ …`), so multiple children's lines remain
/// attributable even when they interleave.
#[rstest]
fn test_alias_concurrent_prefixes_output(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases.build]
lint = "echo HELLO_LINT"
test = "echo HELLO_TEST"
"#,
    );
    repo.commit("initial");
    let feature_path = repo.add_worktree("feature");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "build"])
        .current_dir(&feature_path)
        .env("NO_COLOR", "1");
    let output = cmd.output().unwrap();

    assert!(
        output.status.success(),
        "concurrent alias failed: stderr={}",
        String::from_utf8_lossy(&output.stderr),
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    // Each command must produce a line starting with its prefixed label and
    // separated by the box-drawing `│` that the executor emits. Whitespace
    // between label and `│` varies with padding-to-widest-label.
    for (label, body) in [("lint", "HELLO_LINT"), ("test", "HELLO_TEST")] {
        let has_prefixed_line = stderr
            .lines()
            .any(|l| l.starts_with(label) && l.contains('│') && l.contains(body));
        assert!(
            has_prefixed_line,
            "expected a line starting with '{label}' containing '{body}' and a '│' separator, got:\n{stderr}"
        );
    }
}

/// A failing concurrent step causes the alias to fail. Covers the error
/// propagation path in the `HookStep::Concurrent` join loop, complementing
/// the happy-path `test_alias_concurrent_steps` above.
#[rstest]
fn test_alias_concurrent_step_failure(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases.check]
ok = "true"
fail = "exit 1"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "check"]);
    let output = cmd.output().expect("wt step check failed to spawn");
    assert!(
        !output.status.success(),
        "wt step check should fail when a concurrent step exits non-zero"
    );
}

#[cfg(unix)]
fn signal_alias(repo: &TestRepo, concurrent: bool, caught_int: Option<bool>) -> Vec<&'static str> {
    let labels = if concurrent {
        vec!["one", "two"]
    } else {
        vec!["one"]
    };
    let commands: Vec<_> = labels.iter().map(|label| {
        let int_trap = match caught_int {
            Some(true) => format!("trap 'echo got-int >> int-{label}' INT; "),
            Some(false) => "trap '' INT; ".to_owned(),
            None => String::new(),
        };
        let body = format!("{int_trap}trap 'echo got-term > term-{label}; exit 0' TERM; echo $$ > pid-{label}; echo ready > start-{label}; while test ! -f release; do :; done");
        (*label, serde_json::to_string(&body).unwrap())
    }).collect();
    let first = if concurrent {
        format!(
            "{{ {} }}",
            commands
                .iter()
                .map(|(label, command)| format!("{label} = {command}"))
                .collect::<Vec<_>>()
                .join(", ")
        )
    } else {
        commands[0].1.clone()
    };
    repo.write_test_config(&format!(
        "[aliases]\nsignal-test = [{first}, 'echo next > next']\n"
    ));
    labels
}

#[cfg(unix)]
fn ready_alias_children(repo: &TestRepo, labels: &[&str], group: nix::unistd::Pid) -> Vec<i32> {
    labels
        .iter()
        .map(|label| {
            crate::common::wait_for_file_content(&repo.root_path().join(format!("start-{label}")));
            let pid =
                std::fs::read_to_string(repo.root_path().join(format!("pid-{label}"))).unwrap();
            let pid = nix::unistd::Pid::from_raw(pid.trim().parse().unwrap());
            assert_eq!(
                nix::unistd::getpgid(Some(pid)).unwrap(),
                group,
                "{label} left wt's native group"
            );
            pid.as_raw()
        })
        .collect()
}

/// A child that crashes in its TERM handler must not let a Warn hook pipeline
/// continue after controller cancellation. The same crash alone stays ordinary.
#[rstest]
#[case::ordinary_child_death(false)]
#[case::controller_cancellation(true)]
#[cfg(unix)]
fn test_controller_cancellation_survives_child_term_handler_crash(
    repo: TestRepo,
    #[case] controller_cancel: bool,
) {
    repo.write_project_config(r#"post-start = ["exec python3 worker.py", "printf NEXT > next"]"#);
    std::fs::write(
        repo.root_path().join("worker.py"),
        r#"import os, signal, time
from pathlib import Path
def on_term(*_):
    Path('term-handled').write_text('handled')
    os.kill(os.getpid(), signal.SIGKILL)
signal.signal(signal.SIGTERM, on_term)
Path('pid-one').write_text(str(os.getpid()))
Path('start-one').write_text('ready')
while not Path('release').exists():
    time.sleep(.001)
os.kill(os.getpid(), signal.SIGKILL)
"#,
    )
    .unwrap();
    let stderr_path = repo.root_path().join("stderr");
    let mut job = SignalJob::spawn(
        &repo,
        &["hook", "post-start", "--yes", "--foreground"],
        Stdio::from(std::fs::File::create(&stderr_path).unwrap()),
    );
    ready_alias_children(&repo, &["one"], job.group());
    if controller_cancel {
        nix::sys::signal::kill(job.pid(), nix::sys::signal::Signal::SIGTERM).unwrap();
        crate::common::wait_for_file_content(&repo.root_path().join("term-handled"));
    } else {
        job.release();
    }
    let status = job.wait();
    let stderr = std::fs::read_to_string(stderr_path).unwrap();
    assert_eq!(
        crate::common::shell_exit_code(&status),
        Some(if controller_cancel { 143 } else { 0 }),
        "{status:?}\n{stderr}",
    );
    assert_eq!(
        repo.root_path().join("next").exists(),
        !controller_cancel,
        "{stderr}",
    );
}

/// Native policy: TERM aimed at wt cancels owned work even when its
/// child handles TERM successfully. PID-only INT is never delivered to the
/// child, which runs to completion; wt's receipt still cancels the next step.
#[rstest]
#[case::single_term(false, true)]
#[case::concurrent_term(true, true)]
#[case::single_int(false, false)]
#[case::concurrent_int(true, false)]
#[cfg(unix)]
fn test_alias_pid_signal_policy(repo: TestRepo, #[case] concurrent: bool, #[case] terminate: bool) {
    use nix::sys::signal::{Signal, kill};
    let labels = signal_alias(&repo, concurrent, Some(true));
    let stderr_path = repo.root_path().join("stderr");
    let stderr = std::fs::File::create(&stderr_path).unwrap();
    let mut job = SignalJob::spawn(&repo, &["-vv", "step", "signal-test"], stderr.into());
    let children = ready_alias_children(&repo, &labels, job.group());
    // A child can announce readiness before wt returns from spawn. This test
    // sends its signal to an admitted command, not during startup cancellation.
    crate::common::wait_for_foreground_admission(&repo, &children);
    kill(
        job.pid(),
        if terminate {
            Signal::SIGTERM
        } else {
            Signal::SIGINT
        },
    )
    .unwrap();
    if terminate {
        for label in &labels {
            crate::common::wait_for_file_content(&repo.root_path().join(format!("term-{label}")));
        }
        use std::os::unix::process::ExitStatusExt;
        let status = job.wait();
        assert!(
            status.code() == Some(143) || status.signal() == Some(15),
            "forwarded TERM must cancel after caught success: {status:?}\n{}",
            std::fs::read_to_string(stderr_path).unwrap()
        );
        assert!(!repo.root_path().join("next").exists());
    } else {
        std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
        assert!(job.running(), "PID-only INT stopped the waiting caller");
        for label in &labels {
            assert!(
                !repo.root_path().join(format!("int-{label}")).exists(),
                "PID-only INT reached {label}"
            );
        }
        job.release();
        use std::os::unix::process::ExitStatusExt;
        let status = job.wait();
        assert!(
            status.code() == Some(130) || status.signal() == Some(2),
            "PID-only INT must cancel after the child's success: {status:?}\n{}",
            std::fs::read_to_string(stderr_path).unwrap()
        );
        assert!(!repo.root_path().join("next").exists());
    }
}

/// Kernel group delivery reaches both children; actual interrupted status
/// stops the following alias step.
#[rstest]
#[cfg(unix)]
fn test_alias_concurrent_receives_sigint(repo: TestRepo) {
    let labels = signal_alias(&repo, true, None);
    let mut job = SignalJob::spawn(&repo, &["step", "signal-test"], Stdio::null());
    ready_alias_children(&repo, &labels, job.group());
    nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();
    use std::os::unix::process::ExitStatusExt;
    let status = job.wait();
    assert!(
        status.code() == Some(130) || status.signal() == Some(2),
        "group INT should exit 130: {status:?}"
    );
    assert!(!repo.root_path().join("next").exists());
}

/// Repeated group interrupts retain the child's disposition and never kill wt
/// while the child runs, yet wt's receipt cancels the following step even after
/// the child succeeds. One contrast per handler/key/cardinality covers both
/// stream execution paths.
#[rstest]
#[case::single_caught_once(false, true, 1)]
#[case::concurrent_caught_twice(true, true, 2)]
#[case::single_ignored_twice(false, false, 2)]
#[case::concurrent_ignored_once(true, false, 1)]
#[cfg(unix)]
fn test_alias_group_sigint_does_not_escalate(
    repo: TestRepo,
    #[case] concurrent: bool,
    #[case] caught: bool,
    #[case] presses: usize,
) {
    let labels = signal_alias(&repo, concurrent, Some(caught));
    let mut job = SignalJob::spawn(&repo, &["-vv", "step", "signal-test"], Stdio::null());
    let children = ready_alias_children(&repo, &labels, job.group());
    crate::common::wait_for_foreground_admission(&repo, &children);
    for press in 1..=presses {
        nix::sys::signal::killpg(job.group(), nix::sys::signal::Signal::SIGINT).unwrap();
        if caught {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            for label in &labels {
                let marker = repo.root_path().join(format!("int-{label}"));
                while std::fs::read_to_string(&marker)
                    .unwrap_or_default()
                    .lines()
                    .count()
                    != press
                {
                    assert!(
                        std::time::Instant::now() < deadline,
                        "{label} did not handle interrupt {press} exactly once"
                    );
                    std::thread::sleep(std::time::Duration::from_millis(10));
                }
            }
        }
        std::thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
        assert!(job.running(), "interrupt {press} killed wt before release");
        ready_alias_children(&repo, &labels, job.group());
    }
    job.release();
    use std::os::unix::process::ExitStatusExt;
    let status = job.wait();
    assert!(
        status.code() == Some(130) || status.signal() == Some(2),
        "caught/ignored interrupts must still cancel the alias: {status:?}"
    );
    assert!(!repo.root_path().join("next").exists());
    if caught {
        for label in &labels {
            assert_eq!(
                std::fs::read_to_string(repo.root_path().join(format!("int-{label}")))
                    .unwrap()
                    .lines()
                    .count(),
                presses
            );
        }
    }
}

/// An alias is the whole command, so its last serial step owns Ctrl-C as input,
/// like `--execute`: a child that handles the key and exits successfully keeps
/// that status. Earlier steps cancel instead (`test_alias_group_sigint_does_not_escalate`).
#[rstest]
#[cfg(unix)]
fn test_alias_last_step_keeps_status_after_caught_ctrl_c(repo: TestRepo) {
    repo.write_test_config(
        "[aliases]\nsignal-test = \"trap 'echo handled > int; while [ ! -e release ]; do sleep 0.01; done; exit 0' INT; echo $$ > pid; while :; do sleep 0.1; done\"\n",
    );
    let stderr_path = repo.root_path().join("stderr");
    let stderr = std::fs::File::create(&stderr_path).unwrap();
    let mut job = SignalJob::spawn(&repo, &["-vv", "step", "signal-test"], stderr.into());
    job.interrupt_admitted_child(&repo, &repo.root_path().join("pid"));
    crate::common::wait_for_file_content(&repo.root_path().join("int"));
    // Keep the child alive until wt has received the group signal. Otherwise
    // the child can exit before SIGINT reaches wt, turning it into an idle key.
    let trace = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/logs/trace.jsonl");
    let receipt = format!(
        "Foreground signal received:{}",
        nix::sys::signal::Signal::SIGINT as i32
    );
    crate::common::wait_for("wt to receive SIGINT", || {
        std::fs::read_to_string(&trace).is_ok_and(|records| {
            worktrunk::trace::parse_lines(&records).iter().any(|entry| {
                matches!(&entry.kind, worktrunk::trace::TraceEntryKind::Instant { name } if name == &receipt)
            })
        })
    });
    job.release();
    let status = job.wait();
    assert!(
        status.success(),
        "the final child handled Ctrl-C successfully: {status:?}\n{}",
        std::fs::read_to_string(stderr_path).unwrap()
    );
}

/// Non-UTF-8 bytes and CRLF line endings in child output must not stall the
/// executor. Earlier code using `BufRead::lines()` returned `InvalidData` on
/// the first invalid byte and terminated the iterator, leaving the child's
/// pipe un-drained and `child.wait()` hanging forever. Also exercises the
/// `\r\n` strip path so trailing carriage returns don't render visibly.
#[rstest]
fn test_alias_concurrent_handles_non_utf8(repo: TestRepo) {
    // `printf` emits a raw 0xff byte (invalid as a lone UTF-8 sequence), a
    // CRLF-terminated line, then `yes` floods 50_000 more valid UTF-8 lines.
    // If the reader stopped at the bad byte, the pipe would fill and the
    // child would block — we'd time out. The trivial `other` command keeps
    // the step a multi-command group so it routes through the concurrent
    // executor (a one-command map parses as a plain `Single` step).
    repo.write_test_config(
        r#"
[aliases.noisy]
mixed = "sh -c 'printf \"BEFORE\\n\\xff\\nCRLF-LINE\\r\\nAFTER\\n\"; yes PAYLOAD | head -n 50000'"
other = "true"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "noisy"]);
    let output = cmd.output().expect("wt step noisy failed to spawn");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "alias should succeed despite non-UTF-8 byte, got: {status:?}\nlast 500 bytes of stderr: {tail}",
        status = output.status,
        tail = &stderr[stderr.len().saturating_sub(500)..],
    );

    // All clean lines plus all 50_000 flood lines must land — proves the
    // reader kept going past the invalid byte.
    assert!(stderr.contains("BEFORE"), "expected BEFORE in stderr");
    assert!(
        stderr.contains("AFTER"),
        "expected AFTER in stderr (reader stopped at the invalid byte)"
    );
    // CRLF line ending: the reader strips the trailing \r, so the visible
    // line is `CRLF-LINE` not `CRLF-LINE\r`. Any `\r` in the output would
    // indicate the strip didn't fire.
    assert!(
        stderr.contains("CRLF-LINE"),
        "expected CRLF-LINE (with the \\r stripped) in stderr"
    );
    assert!(
        !stderr.contains("CRLF-LINE\r"),
        "trailing \\r should have been stripped before printing"
    );
    assert_eq!(
        stderr.matches("PAYLOAD").count(),
        50_000,
        "expected 50000 PAYLOAD lines after the invalid byte, got {}",
        stderr.matches("PAYLOAD").count(),
    );
}

/// A concurrent child that produces a large volume of stdout must not
/// deadlock the executor — the reader thread has to keep draining the pipe so
/// the child can keep writing. We run two commands, each emitting ~400 KB, and
/// assert both streams land in stderr intact.
#[rstest]
fn test_alias_concurrent_large_output(repo: TestRepo) {
    // yes piped through head is a portable way to generate many lines fast.
    // Each command produces ~400 KB = 50_000 * ~8 bytes ("aaaa...\n" etc.).
    // If the reader thread were ever to stall, the child's stdout pipe would
    // fill (default ~64 KB) and the child would block forever — the test would
    // time out rather than produce a misleading pass.
    repo.write_test_config(
        r#"
[aliases.bulk]
first  = "yes 'FIRST-PAYLOAD-AAAAA' | head -n 50000"
second = "yes 'SECOND-PAYLOAD-BBBBB' | head -n 50000"
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "bulk"]);
    let output = cmd.output().expect("wt step bulk failed to spawn");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "concurrent alias with large output should exit 0, got: {status:?}\nlast 500 bytes of stderr: {tail}",
        status = output.status,
        tail = &stderr[stderr.len().saturating_sub(500)..],
    );

    // Count occurrences so we know both children's full output was streamed —
    // not truncated by a blocked pipe. 50_000 exact matches per payload.
    let first_count = stderr.matches("FIRST-PAYLOAD-AAAAA").count();
    let second_count = stderr.matches("SECOND-PAYLOAD-BBBBB").count();
    assert_eq!(
        first_count, 50_000,
        "expected 50000 occurrences of first payload in stderr, got {first_count}"
    );
    assert_eq!(
        second_count, 50_000,
        "expected 50000 occurrences of second payload in stderr, got {second_count}"
    );
}

/// Ordinary success and failure both retain EOF semantics, including delayed
/// diagnostics from the failed command and output from healthy siblings.
#[rstest]
#[cfg(unix)]
fn test_alias_failure_preserves_descendant_output(repo: TestRepo) {
    repo.write_test_config(
        r#"[aliases.signal-test]
bad = "(sleep .6; printf 'FAILED_%s' TAIL) & exit 17"
good = "(sleep .6; printf 'LATE_%s' TAIL) & printf EARLY_"
"#,
    );
    let output_path = repo.root_path().join("output");
    let stderr = std::fs::File::create(&output_path).unwrap();
    let mut job = SignalJob::spawn(&repo, &["step", "signal-test"], stderr.into());
    assert_eq!(job.wait().code(), Some(17));
    let output = std::fs::read_to_string(output_path).unwrap();
    assert!(
        output.contains("EARLY_LATE_TAIL"),
        "healthy output lost: {output}"
    );
    assert!(
        output.contains("FAILED_TAIL"),
        "failure diagnostics lost: {output}"
    );
}

/// Cancellation must finish even when an unowned descendant continuously
/// refills an output pipe, retaining buffered bytes and the final diagnostic.
#[rstest]
#[cfg(all(unix, feature = "shell-integration-tests"))]
fn test_alias_cancelled_continuous_writer_flushes_partial_output(repo: TestRepo) {
    std::fs::write(
        repo.root_path().join("writer.py"),
        r#"import os, signal, time
from pathlib import Path
signal.signal(signal.SIGTERM, lambda *_: os._exit(0))
if os.fork():
    while True:
        time.sleep(60)
os.write(1, b'BUFFERED_STDOUT')
os.write(2, b'FINAL_PARTIAL_DIAGNOSTIC')
Path('descendant-ready').write_text('ready')
try:
    while not Path('release').exists():
        os.write(1, b'x' * 8192)
except BrokenPipeError:
    pass
os._exit(0)
"#,
    )
    .unwrap();
    repo.write_test_config(
        r#"[aliases.signal-test]
bad = "exec python3 writer.py"
good = "true"
"#,
    );
    let output_path = repo.root_path().join("output");
    let stderr = std::fs::File::create(&output_path).unwrap();
    let mut job = SignalJob::spawn(&repo, &["step", "signal-test"], stderr.into());
    crate::common::wait_for_file_content(&repo.root_path().join("descendant-ready"));
    nix::sys::signal::kill(job.pid(), nix::sys::signal::Signal::SIGTERM).unwrap();
    let release = job.release.clone();
    let (stop, done) = std::sync::mpsc::channel::<()>();
    let (status, watchdog_fired) = std::thread::scope(|scope| {
        let watchdog = scope.spawn(move || {
            if matches!(
                done.recv_timeout(std::time::Duration::from_secs(5)),
                Err(std::sync::mpsc::RecvTimeoutError::Timeout)
            ) {
                std::fs::write(release, "release").unwrap();
                true
            } else {
                false
            }
        });
        let status = job.wait();
        let _ = stop.send(());
        (status, watchdog.join().unwrap())
    });
    assert!(
        !watchdog_fired,
        "cancelled reader needed producer release to finish"
    );
    use std::os::unix::process::ExitStatusExt;
    assert!(
        status.signal() == Some(15) || status.code() == Some(143),
        "{status:?}"
    );
    let output = std::fs::read_to_string(output_path).unwrap();
    assert!(output.contains("BUFFERED_STDOUT"));
    assert!(output.contains("FINAL_PARTIAL_DIAGNOSTIC"));
}

/// Pipeline-form aliases (list of steps) run sequentially. A later step
/// referencing `{{ vars.X }}` must see vars set by an earlier step —
/// `expand_shell_template` reads `vars.*` fresh from git config on each call.
#[rstest]
fn test_alias_pipeline_vars_across_steps(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = [
    "git config worktrunk.state.main.vars.target 'staging'",
    { publish = "echo target={{ vars.target }} > alias_lazy.txt" },
]
"#,
    );
    repo.commit("initial");

    let mut cmd = repo.wt_command();
    cmd.args(["step", "deploy"]);
    let output = cmd.output().expect("wt step deploy failed to spawn");
    assert!(
        output.status.success(),
        "wt step deploy failed: stdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let marker = repo.root_path().join("alias_lazy.txt");
    let content = std::fs::read_to_string(&marker)
        .unwrap_or_else(|e| panic!("missing marker {marker:?}: {e}"));
    assert_eq!(
        content.trim(),
        "target=staging",
        "lazy step should see var set by prior serial step"
    );
}

/// `dry-run` for a pipeline where a later step references `{{ vars.X }}` set by
/// an earlier step succeeds, mirroring the lazy execution path. The unresolved
/// `vars.*` reference is shown as the raw template since its value isn't
/// knowable until the earlier step actually runs.
#[rstest]
fn test_config_alias_dry_run_vars_across_steps(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = [
    "git config worktrunk.state.main.vars.target 'prod'",
    { publish = "echo deploying to {{ vars.target }}" },
]
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Must succeed: dry-run must not require vars.* to be resolvable.
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "deploy"],
        Some(&feature_path),
    ));
}

/// `dry-run` still catches template syntax errors (e.g., `{{ vars..foo }}`) even
/// on the lazy path where `vars.*` rendering is skipped.
#[rstest]
fn test_config_alias_dry_run_catches_syntax_error(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
broken = "echo {{ vars..target }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["config", "alias", "dry-run", "broken"])
        .current_dir(&feature_path)
        .output()
        .unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !output.status.success(),
        "dry-run should fail on syntax error; stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("syntax error"),
        "expected 'syntax error' in stderr, got:\n{stderr}"
    );
}

/// Retired `wt <alias> --dry-run` flag produces an actionable error pointing at
/// the new subcommand. Snapshots the top-level path; the shared parser covers
/// both `wt <alias>` and `wt step <alias>` dispatch routes (unit test in
/// `commands::alias::tests::test_parse_errors` verifies the message verbatim).
#[rstest]
fn test_retired_dry_run_flag(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "deploy",
        &["--dry-run"],
        Some(&feature_path),
    ));
}

/// Retired `--dry-run` bail also fires through `wt step <alias>` — the parser
/// is shared, but this pins the `step_alias` dispatch route specifically.
#[rstest]
fn test_retired_dry_run_flag_via_step(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["deploy", "--dry-run"],
        Some(&feature_path),
    ));
}

/// `wt <alias> --help` prints guidance rather than forwarding `--help` into
/// `{{ args }}`. Aliases have no clap-style help page; the canonical
/// inspection path is `wt config alias show / dry-run`.
#[rstest]
fn test_alias_help_flag_prints_hint(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "deploy",
        &["--help"],
        Some(&feature_path),
    ));
}

/// `wt <alias> -- --help` bypasses the intercept and forwards `--help` into
/// the alias body — the documented escape.
#[rstest]
fn test_alias_help_flag_after_double_dash_forwards(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "deploy",
        &["--", "--help"],
        Some(&feature_path),
    ));
}

/// `wt config alias show <name>` prints the configured template text, source-labeled.
#[rstest]
fn test_config_alias_show_single(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy BRANCH={{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deploy"],
        Some(&feature_path),
    ));
}

/// `wt config alias show` with no name prints every configured alias's full
/// definition — the same per-alias header + gutter block as `wt config alias
/// show <name>`, emitted for each alias in name order. Names defined in both
/// user and project config show twice (user first), and a name shadowed by a
/// top-level built-in gets the stderr warning.
#[rstest]
fn test_config_alias_show_lists_all(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo from project"
"only-project" = "echo p"
list = "echo custom list"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo from user"
greet = "echo hi {{ branch }}"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show"],
        Some(&feature_path),
    ));
}

/// User alias discovery does not require a Git repository, with or without a
/// name. A typo still gets alias suggestions rather than a repository error.
#[rstest]
fn test_config_alias_show_outside_repository(repo: TestRepo) {
    let outside = crate::common::test_tempdir();
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo {{ branch }}"
"#,
    );
    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    for (snapshot, args) in [
        ("alias_show_outside_all", vec!["alias", "show"]),
        ("alias_show_outside_named", vec!["alias", "show", "deploy"]),
        ("alias_show_outside_typo", vec!["alias", "show", "deplyo"]),
    ] {
        assert_cmd_snapshot!(
            snapshot,
            make_snapshot_cmd(&repo, "config", &args, Some(outside.path()))
        );
    }
}

/// Discovery stays quiet even when prewarm reads a deprecated user setting.
#[rstest]
fn test_config_alias_show_suppresses_deprecation_warnings(repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo hi"
[commit-generation]
command = "echo message"
"#,
    );
    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();
    for (snapshot, args) in [
        ("alias_show_deprecated_all", vec!["alias", "show"]),
        (
            "alias_show_deprecated_named",
            vec!["alias", "show", "deploy"],
        ),
    ] {
        assert_cmd_snapshot!(snapshot, make_snapshot_cmd(&repo, "config", &args, None));
    }
}

/// Project and user aliases display the templates that run: a retired
/// template variable shows as its replacement in both sources, matching the
/// migration execution applies.
#[rstest]
fn test_config_alias_show_migrates_retired_template_vars(repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
open = "code {{ repo_root }}"
"#,
    );
    repo.commit("Add alias config");
    repo.write_test_config(
        r#"
[aliases]
here = "echo {{ worktree }}"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "config", &["alias", "show"], None));
}

/// `wt config alias show` with no name and no aliases configured prints a note
/// rather than empty output.
#[rstest]
fn test_config_alias_show_lists_none(mut repo: TestRepo) {
    repo.commit("Initial commit");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show"],
        Some(&feature_path),
    ));
}

/// Unknown alias name triggers a did-you-mean suggestion. Format mirrors
/// `wt <typo>` and `wt step <typo>`: clap-native `InvalidSubcommand` with a
/// `tip:` line — same shape at every alias-typo surface.
#[rstest]
fn test_config_alias_show_unknown_suggests(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deplyo"],
        Some(&feature_path),
    ));
}

/// Aliases or typos that literally contain `subcommand` must be echoed
/// verbatim — the word-substitution pass that rewrites clap's
/// "unrecognized subcommand" to "unrecognized alias" must only touch
/// clap's fixed phrases, not the user's input.
#[rstest]
fn test_config_alias_show_unknown_preserves_user_input(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
"my-subcommand" = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Typo `my-subcommond` is close enough to `my-subcommand` to suggest it —
    // both the echoed typo and the suggestion must keep `subcommand` intact.
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "my-subcommond"],
        Some(&feature_path),
    ));
}

/// Single-match case: tip phrasing switches to the singular form
/// ("a similar alias exists") — mirrors clap's own singular rendering.
#[rstest]
fn test_config_alias_show_unknown_singular_suggestion(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deplyo"],
        Some(&feature_path),
    ));
}

/// `wt config alias dry-run <typo>` produces the same clap-native typo error
/// as `show` — consistent format across both introspection subcommands.
#[rstest]
fn test_config_alias_dry_run_unknown_suggests(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy"
hello = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "deplyo"],
        Some(&feature_path),
    ));
}

/// Multi-step pipeline renders with per-step structure in the header.
#[rstest]
fn test_config_alias_show_pipeline(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[[aliases.release]]
install = "npm install"

[[aliases.release]]
build = "npm run build"
lint = "npm run lint"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "release"],
        Some(&feature_path),
    ));
}

/// Positional args via `wt config alias dry-run <name> -- foo bar` flow through as `{{ args }}`.
#[rstest]
fn test_config_alias_dry_run_positional_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
s = "wt switch {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "s", "--", "target-branch"],
        Some(&feature_path),
    ));
}

/// `wt config alias show <name>` with the same alias defined in both user and
/// project config prints both entries in runtime order (user first).
#[rstest]
fn test_config_alias_show_user_and_project(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo from project"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");
    repo.write_test_config(
        r#"
[aliases]
deploy = "echo from user"
"#,
    );

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "deploy"],
        Some(&feature_path),
    ));
}

/// Unknown alias name with no similar configured aliases shows a plain error
/// without a "did you mean" tail.
#[rstest]
fn test_config_alias_show_unknown_no_suggestions(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "echo hi"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    // Query name shares no meaningful prefix with any configured alias — the
    // Jaro-Winkler threshold rejects it, so the error has no suggestion list.
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "zzzzzzzz"],
        Some(&feature_path),
    ));
}

/// `wt config alias show <name>` on an alias whose name is also a top-level
/// built-in subcommand warns that the alias is unreachable via `wt <name>`.
/// The alias is still configured, so the show output itself is shown — the
/// warning is an advisory on stderr.
#[rstest]
fn test_config_alias_show_warns_on_shadowed_name(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
list = "echo custom list"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "show", "list"],
        Some(&feature_path),
    ));
}

/// `wt config alias dry-run` on a shadowed name emits the same advisory as
/// `show` — both are discovery surfaces, so both point out the shadowing.
#[rstest]
fn test_config_alias_dry_run_warns_on_shadowed_name(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
list = "echo custom list"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "list"],
        Some(&feature_path),
    ));
}

/// `wt step` with no subcommand lists built-in steps plus configured aliases.
///
/// Skipped on Windows: clap renders `[experimental]` subcommand tags
/// differently (markdown escaping), same reason `tests/integration_tests/help.rs`
/// is Windows-gated.
#[cfg(not(windows))]
#[rstest]
fn test_step_list_with_aliases(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy BRANCH={{ branch }}"
port = "echo http://localhost:{{ branch | hash_port }}"
squash = "this shadows the built-in"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &[], Some(&feature_path)));
}

/// `wt step` without configured aliases still works — just prints help.
#[cfg(not(windows))]
#[rstest]
fn test_step_list_no_aliases(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &[], Some(&feature_path)));
}

/// `wt step --help` includes the same Aliases section as bare `wt step`.
///
/// Without this, users running `--help` in the normal discovery flow would
/// see only built-in commands and miss their configured aliases.
#[cfg(not(windows))]
#[rstest]
fn test_step_help_includes_aliases(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
deploy = "make deploy BRANCH={{ branch }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["-h"],
        Some(&feature_path)
    ));
}

/// `wt step --help` must not emit deprecation warnings or write `.new`
/// migration files when the user config contains deprecated patterns —
/// help is a discovery surface, not an execution surface, and the user
/// will see those warnings from `wt config show` and normal commands.
#[cfg(not(windows))]
#[rstest]
fn test_step_help_silent_with_deprecated_user_config(repo: TestRepo) {
    // Deprecated `main_worktree` template variable — migrated to `repo`.
    repo.write_test_config(
        r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
"#,
    );
    let migration_file = repo.test_config_path().with_extension("toml.new");

    let output = repo.wt_command().args(["step", "--help"]).output().unwrap();

    assert!(
        output.status.success(),
        "step --help should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr, "",
        "step --help must emit no stderr on deprecated user config"
    );
    assert!(
        !migration_file.exists(),
        "step --help must not write .new migration file at {}",
        migration_file.display()
    );
}

/// `wt -C <other> step --help` lists aliases from `<other>`'s project config,
/// not from the process cwd. Without applying global options before the help
/// branch, the Aliases section was rendered from the wrong repo.
#[cfg(not(windows))]
#[rstest]
fn test_step_help_honors_dash_c(repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
xyzzy = "echo nothing happens"
"#,
    );
    repo.commit("Add alias config");
    let repo_path = repo.root_path().to_path_buf();

    // Invoke from a directory that is *not* inside the repo so the alias can
    // only be discovered via -C. Using the system temp dir keeps this
    // independent of the test's working directory.
    let cwd = std::env::temp_dir();
    let mut cmd = repo.wt_command();
    cmd.current_dir(&cwd)
        .args(["-C", repo_path.to_str().unwrap(), "step", "--help"]);
    let output = cmd.output().expect("failed to run wt");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.contains("xyzzy"),
        "expected `xyzzy` alias to appear in `wt -C <repo> step --help` output\n\
         stdout:\n{stdout}\nstderr:\n{stderr}"
    );
}

/// Positional args after the alias name forward to `{{ args }}` in the
/// template — space-joined and shell-escaped so args with spaces, quotes,
/// or metacharacters splice safely into a command line.
#[rstest]
fn test_step_alias_forwards_positional_args(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo got {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &["one", "two three", "four"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// Templates can treat `{{ args }}` as a sequence: indexing, iteration,
/// and `length` all work because `ShellArgs` reports as `ObjectRepr::Seq`.
#[rstest]
fn test_step_alias_args_sequence_access(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
show = '''echo first={{ args[0] }}; echo count={{ args | length }}; echo each={% for a in args %} {{ a }}{% endfor %}'''
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "show",
        &["alpha", "beta gamma"],
        Some(&feature_path),
        &["-y"],
    ));
}

/// With no positionals, `{{ args }}` renders empty — the rest of the line
/// stays intact and no stray whitespace is introduced.
#[rstest]
fn test_step_alias_empty_args_renders_empty(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
run = "echo [{{ args }}]"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
        &repo,
        "run",
        &[],
        Some(&feature_path),
        &["-y"],
    ));
}

/// `wt s some-branch` with `s = "wt switch {{ args }}"` forwards the
/// positional into the expanded command. Verified via `wt config alias dry-run`
/// so the inner `wt switch` is not actually executed.
#[rstest]
fn test_top_level_alias_positional_expands_in_dry_run(mut repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
s = "wt switch {{ args }}"
"#,
    );
    repo.commit("Add alias config");
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    let _guard = settings.bind_to_scope();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "config",
        &["alias", "dry-run", "s", "--", "target-branch"],
        Some(&feature_path),
    ));
}

/// Under `-v`, aliases print a table of resolved template variables before
/// the announcement — symmetric with the hook-invocation verbose block, but
/// with alias-scoped vars (`args` included, no `hook_*` keys).
#[rstest]
fn test_alias_verbose_prints_variable_table(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
greet = "echo hello {{ args }}"
"#,
    );
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd_with_global_flags(
            &repo,
            "greet",
            &["world"],
            Some(&feature_path),
            &["-v"],
        );
        assert_cmd_snapshot!("alias_verbose_variable_table", cmd);
    });
}

/// Multi-token args with whitespace render shell-escaped in the `-v` table,
/// matching what `{{ args }}` actually expands to on the line below.
#[rstest]
fn test_alias_verbose_renders_args_shell_escaped(mut repo: TestRepo) {
    repo.write_test_config(
        r#"
[aliases]
greet = "echo hello {{ args }}"
"#,
    );
    let feature_path = repo.add_worktree("feature");

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd_with_global_flags(
            &repo,
            "greet",
            &["foo", "bar baz"],
            Some(&feature_path),
            &["-v"],
        );
        assert_cmd_snapshot!("alias_verbose_args_shell_escaped", cmd);
    });
}

/// Aliases keep `wt`'s inherited git-discovery context: `wt <alias>` is the
/// user's own top-level command, run where they invoked it, so the inherited
/// `GIT_DIR`/`GIT_WORK_TREE` pass through — unlike hooks and `wt step
/// for-each`, which `wt` relocates into worktrees it selects and therefore
/// scrubs (the keep side of the classification in
/// `scrub_git_discovery_env_vars`; issue #3373).
#[rstest]
#[cfg(unix)]
fn test_alias_keeps_inherited_git_discovery_vars(repo: TestRepo) {
    repo.write_project_config(
        r#"
[aliases]
record-git-env = "printf '[%s][%s]' \"$GIT_DIR\" \"$GIT_WORK_TREE\" > env_seen.txt"
"#,
    );
    repo.commit("Add alias config");

    let git_dir = repo.root_path().join(".git");
    let output = repo
        .wt_command()
        .args(["-y", "record-git-env"])
        .env("GIT_DIR", &git_dir)
        .env("GIT_WORK_TREE", repo.root_path())
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "alias failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let seen = std::fs::read_to_string(repo.root_path().join("env_seen.txt")).unwrap();
    let expected = format!("[{}][{}]", git_dir.display(), repo.root_path().display());
    assert_eq!(
        seen, expected,
        "alias should see wt's inherited git-discovery vars unchanged"
    );
}

/// A detached worktree leaves `{{ branch }}` undefined, so `{% if branch %}`
/// guards it the way the hook docs prescribe for every optional variable.
///
/// Regression test for #4009: `branch` used to fall back to the literal
/// `HEAD`, which is a non-empty string git happily resolves as a ref — so
/// every guard written around `branch` passed and the alias ran against the
/// wrong thing (`git push origin --delete HEAD`). It also disagreed with
/// `wt list --json`, which reports `branch: null` for the same worktree.
#[rstest]
fn test_alias_branch_unset_in_detached_worktree(mut repo: TestRepo) {
    repo.add_worktree("detached-test");
    repo.detach_head_in_worktree("detached-test");
    let detached = repo.worktree_path("detached-test").to_path_buf();

    repo.write_test_config(
        r#"
[aliases]
probe = "echo [{% if branch %}{{ branch }}{% endif %}]"
"#,
    );

    let output = repo
        .wt_command()
        .args(["-y", "probe"])
        .current_dir(&detached)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "alias failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        combined.contains("[]"),
        "`{{% if branch %}}` should not fire in a detached worktree, got: {combined}"
    );
    assert!(
        !combined.contains("[HEAD]"),
        "`branch` must not fall back to the literal `HEAD`, got: {combined}"
    );
}

/// `branch` is cheap enough that `build_hook_context` computes it whatever the
/// scope, so its absence in a detached worktree is `(unset)` — a fact about the
/// worktree — even in an alias body that never names it. `(unused)` is reserved
/// for a var the scope gate actually skipped computing.
#[rstest]
fn test_verbose_variables_table_marks_detached_branch_unset(mut repo: TestRepo) {
    repo.add_worktree("detached-vars");
    repo.detach_head_in_worktree("detached-vars");
    let detached = repo.worktree_path("detached-vars").to_path_buf();

    // The body references neither `branch` nor `upstream`, so the scope gate
    // skips only the latter — an expensive var behind a git-config read.
    repo.write_test_config(
        r#"
[aliases]
probe = "echo hello"
"#,
    );

    let output = repo
        .wt_command()
        .args(["-v", "-y", "probe"])
        .current_dir(&detached)
        .output()
        .unwrap();
    let raw_stderr = String::from_utf8_lossy(&output.stderr);
    let stderr = raw_stderr.ansi_strip();

    let branch_row = stderr
        .lines()
        .map(str::trim)
        .find(|line| line.starts_with("branch "))
        .unwrap_or_else(|| panic!("no `branch` row in the variables table:\n{stderr}"));
    assert!(
        branch_row.ends_with("= (unset)"),
        "detached `branch` should read `(unset)`, not `(unused)`, got: {branch_row}"
    );
}

/// The first alias step moves its worktree, so the next child's cwd is absent.
#[rstest]
#[cfg(unix)]
#[case::serial(false)]
#[case::concurrent(true)]
fn test_alias_spawn_failure_has_one_source_detail(repo: TestRepo, #[case] concurrent: bool) {
    repo.write_test_config(
        if concurrent {
            r#"[aliases]
move-away = ["mv {{ worktree_path }} {{ worktree_path }}.moved", { check = "true", sibling = "true" }]
"#
        } else {
            r#"[aliases]
move-away = ["mv {{ worktree_path }} {{ worktree_path }}.moved", "true"]
"#
        }
    );
    let output = repo.wt_command().arg("move-away").output().unwrap();
    assert_eq!(output.status.code(), Some(1));
    assert!(!repo.root_path().exists());
    assert!(repo.root_path().with_file_name("repo.moved").exists());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(stderr.matches("Failed to execute").count(), 1, "{stderr}");
    assert_eq!(stderr.matches("os error 2").count(), 1, "{stderr}");
    if concurrent {
        assert!(stderr.contains("command 'check'"), "{stderr}");
    }
    setup_snapshot_settings(&repo).bind(|| {
        insta::assert_snapshot!(
            if concurrent {
                "alias_concurrent_spawn_failure_has_one_source_detail"
            } else {
                "alias_spawn_failure_has_one_source_detail"
            },
            stderr
        );
    });
}