Skip to content

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

26.1 KB
Raw Blame
//! Integration tests for `wt step for-each`

use crate::common::{TestRepo, make_snapshot_cmd, repo};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;

#[rstest]
fn test_for_each_single_worktree(repo: TestRepo) {
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "git", "status", "--short"],
        None,
    ));
}

#[rstest]
fn test_for_each_multiple_worktrees(mut repo: TestRepo) {
    repo.add_worktree("feature-a");
    repo.add_worktree("feature-b");

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "git", "branch", "--show-current"],
        None,
    ));
}

#[rstest]
fn test_for_each_command_fails_in_one(mut repo: TestRepo) {
    repo.add_worktree("feature");

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "git", "show", "nonexistent-ref"],
        None,
    ));
}

#[rstest]
fn test_for_each_no_args_error(repo: TestRepo) {
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["for-each"], None));
}

#[rstest]
fn test_for_each_with_detached_head(mut repo: TestRepo) {
    // A generic directory name needs its location even without a collision.
    let lone_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("solo")
        .join("worktrunk");
    repo.add_worktree_at_path("detached-test", &lone_path);
    repo.detach_head_in_worktree("detached-test");

    // A detached checkout and an off-template branch can share a directory name.
    for name in ["a", "on-branch"] {
        let path = repo.root_path().parent().unwrap().join(name).join("repo");
        repo.add_worktree_at_path(name, &path);
        if name != "on-branch" {
            repo.detach_head_in_worktree(name);
        }
    }

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "git", "status", "--short"],
        None,
    ));
}

#[rstest]
fn test_for_each_with_template(repo: TestRepo) {
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "echo", "Branch: {{ branch }}"],
        None,
    ));
}

/// A detached worktree leaves `{{ branch }}` unset, so `{% if branch %}` guards
/// it and the loop visits every worktree (issue #4009).
#[rstest]
fn test_for_each_detached_branch_variable(mut repo: TestRepo) {
    repo.add_worktree("detached-test");
    repo.detach_head_in_worktree("detached-test");

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &[
            "for-each",
            "--",
            "echo",
            "Branch: [{% if branch %}{{ branch }}{% endif %}]",
        ],
        None,
    ));
}

/// The unguarded form is an undefined-variable error in the detached worktree,
/// the same as any other optional variable. Before #4009 it rendered the
/// literal `HEAD` — a string git resolves as a ref, so the command ran against
/// the wrong thing instead of saying so.
#[rstest]
fn test_for_each_detached_branch_variable_unguarded(repo: TestRepo) {
    repo.detach_head_in_worktree("feature-b");

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "echo", "Branch: {{ branch }}"],
        None,
    ));
}

/// Preparation failures belong to one worktree: retain earlier results and
/// continue to the next worktree, just as for a child command failure.
#[rstest]
fn test_for_each_json_retains_results_after_template_failure(repo: TestRepo) {
    repo.detach_head_in_worktree("feature-b");
    let output = repo
        .wt_command()
        .args([
            "step",
            "for-each",
            "--format=json",
            "--",
            "echo",
            "{{ branch }}",
        ])
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(1));
    let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    insta::assert_snapshot!(serde_json::to_string_pretty(&json).unwrap(), @r#"
    [
      {
        "branch": "main",
        "path": "_REPO_",
        "exit_code": 0,
        "success": true
      },
      {
        "branch": "feature-a",
        "path": "_REPO_.feature-a",
        "exit_code": 0,
        "success": true
      },
      {
        "branch": null,
        "path": "_REPO_.feature-b",
        "exit_code": null,
        "success": false,
        "error": "Failed to expand for-each argument: undefined variable branch @ line 1"
      },
      {
        "branch": "feature-c",
        "path": "_REPO_.feature-c",
        "exit_code": 0,
        "success": true
      }
    ]
    "#);
}

#[rstest]
fn test_for_each_spawn_fails(mut repo: TestRepo) {
    repo.add_worktree("feature");

    // Normalize platform-specific spawn-error text so the snapshot is
    // identical on Unix (`No such file or directory (os error 2)`) and
    // Windows (`program not found`).
    insta::with_settings!({
        filters => vec![
            (r"No such file or directory \(os error \d+\)", "[SPAWN_FAIL]"),
            (r"program not found", "[SPAWN_FAIL]"),
        ],
    }, {
        assert_cmd_snapshot!(make_snapshot_cmd(
            &repo,
            "step",
            &["for-each", "--", "nonexistent-command-12345", "--some-arg"],
            None,
        ));
    });
}

/// argv boundaries from the post-`--` args reach the program intact. The
/// command is exec'd directly — no implicit shell — so each argv element
/// arrives at the child as a single argument regardless of its content.
/// See issue #2461 for the legacy bug where joining argv into `sh -c`
/// collapsed `python3 -c 'import sys; print(sys.argv[1:])' 'a b'` into a
/// shell syntax error.
#[rstest]
#[cfg(unix)]
fn test_for_each_preserves_argv_quoting(repo: TestRepo) {
    let output = repo
        .wt_command()
        .args([
            "step",
            "for-each",
            "--",
            "python3",
            "-c",
            "import sys; print(sys.argv[1:])",
            "a b",
        ])
        .output()
        .expect("run wt step for-each");

    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    assert!(
        output.status.success(),
        "for-each should succeed when argv quoting is preserved: {combined}",
    );
    assert!(
        combined.contains("['a b']"),
        "expected python to receive 'a b' as a single argv element, got: {combined}",
    );
    assert!(
        !combined.contains("Syntax error"),
        "for-each should not produce shell syntax errors when argv has quoted args: {combined}",
    );
}

/// Spawn failure (program not found) is the one branch in the failure
/// handler that does NOT downcast to `WorktrunkError::ChildProcessExited`,
/// and it appears in JSON mode as `exit_code: null`. Without this test the
/// spawn-failed JSON path is unreachable from the integration suite
/// (#2089 review).
#[rstest]
#[cfg(unix)]
fn test_for_each_json_spawn_failure(repo: TestRepo) {
    let mut cmd = repo.wt_command();
    cmd.args([
        "step",
        "for-each",
        "--format=json",
        "--",
        "nonexistent-command-12345",
    ]);
    let output = cmd.output().unwrap();

    assert!(
        !output.status.success(),
        "for-each should fail when shell spawn fails: stdout={} stderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
        panic!(
            "for-each --format=json should emit valid JSON on spawn failure: {e}\nstdout: {stdout}"
        )
    });
    let items = json.as_array().expect("JSON output should be an array");
    assert!(!items.is_empty(), "expected at least one worktree result");
    for item in items {
        assert_eq!(item["success"], false);
        // Spawn failure ⇒ no exit code (vs. exit-code path which uses an integer)
        assert!(
            item["exit_code"].is_null(),
            "spawn failure should report exit_code: null, got {item}"
        );
        let error = item["error"]
            .as_str()
            .expect("error field should be a string");
        assert!(
            !error.is_empty(),
            "spawn failure error message should be non-empty"
        );
    }
}

/// A child terminated by a signal aborts the loop before the next worktree.
/// Self-signalling TERM exercises native child status without a terminal.
#[rstest]
#[cfg(unix)]
fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {
    // The standard fixture already includes main + feature-{a,b,c} worktrees,
    // so we just need the command to abort on the first visit.

    // A marker file per visited worktree lets us assert that the loop stopped
    // after the first signal. for-each exec's argv directly with no implicit
    // shell, so shell features (`&&`, `$$`, `$(...)`) need an explicit
    // `sh -c` invocation.
    let marker_dir = worktrunk::testing::tempdir().expect("create marker tmpdir");
    let marker_path = marker_dir.path().to_string_lossy().to_string();

    let shell_cmd = format!("touch {marker_path}/$(basename \"$(pwd)\") && kill -TERM $$");

    let output = repo
        .wt_command()
        .args(["step", "for-each", "--", "sh", "-c", &shell_cmd])
        .output()
        .expect("run wt step for-each");

    // Exit code: 128 + SIGTERM (15) = 143
    assert_eq!(
        crate::common::shell_exit_code(&output.status),
        Some(143),
        "expected exit 143 (SIGTERM), got {:?}\nstderr: {}",
        output.status.code(),
        String::from_utf8_lossy(&output.stderr),
    );

    // Exactly one marker file should exist — the remaining worktrees must
    // not have been visited after the signal aborted the loop.
    let markers: Vec<_> = std::fs::read_dir(marker_dir.path())
        .expect("read marker dir")
        .filter_map(Result::ok)
        .collect();
    assert_eq!(
        markers.len(),
        1,
        "expected exactly one worktree visited before abort, got {}: stderr={}",
        markers.len(),
        String::from_utf8_lossy(&output.stderr),
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Interrupted"),
        "expected 'Interrupted' message in stderr, got: {stderr}"
    );
}

/// Ctrl-C stops the loop even when the child catches it and exits successfully:
/// wt received the key itself, so no later worktree is visited.
#[rstest]
#[cfg(unix)]
fn test_for_each_stops_on_caught_ctrl_c(repo: TestRepo) {
    let marker_dir = worktrunk::testing::tempdir().unwrap();
    let pid_file = marker_dir.path().join("pid");
    let script = format!(
        "trap 'exit 0' INT; touch {dir}/\"$(basename \"$PWD\")\"; echo $$ > {pid}; while :; do sleep 0.1; done",
        dir = shell_escape::unix::escape(marker_dir.path().join("visited").to_string_lossy()),
        pid = shell_escape::unix::escape(pid_file.to_string_lossy()),
    );
    std::fs::create_dir(marker_dir.path().join("visited")).unwrap();
    let mut job = crate::common::SignalJob::spawn(
        &repo,
        &["-vv", "step", "for-each", "--", "sh", "-c", &script],
        std::process::Stdio::null(),
    );
    job.interrupt_admitted_child(&repo, &pid_file);
    assert_eq!(crate::common::shell_exit_code(&job.wait()), Some(130));
    let visited = std::fs::read_dir(marker_dir.path().join("visited"))
        .unwrap()
        .count();
    assert_eq!(
        visited, 1,
        "Ctrl-C must stop the loop after its first visit"
    );
}

/// An interrupted `--format=json` run still owes its consumer the results it
/// collected before the signal: the machine-readable answer is emitted on the
/// abort path too, not just on the completing one.
#[rstest]
#[cfg(unix)]
fn test_for_each_json_emitted_on_signal_abort(repo: TestRepo) {
    let output = repo
        .wt_command()
        .args([
            "step",
            "for-each",
            "--format=json",
            "--",
            "sh",
            "-c",
            "kill -TERM $$",
        ])
        .output()
        .expect("run wt step for-each");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        crate::common::shell_exit_code(&output.status),
        Some(143),
        "expected exit 143 (SIGTERM), got {:?}\nstderr: {stderr}",
        output.status.code(),
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("interrupted run must still emit JSON: {e}\nstdout: {stdout}"));
    let items = json.as_array().expect("results are an array");
    assert_eq!(
        items.len(),
        1,
        "only the worktree visited before the signal is reported:\n{stdout}"
    );
}

/// Controller cancellation stops iteration even when the child handles TERM,
/// while JSON retains the child's actual exit rather than reporting spawn failure.
#[rstest]
#[case::caught_success(0)]
#[case::caught_failure(3)]
#[cfg(unix)]
fn test_for_each_json_preserves_caught_exit_on_controller_term(
    repo: TestRepo,
    #[case] exit_code: i32,
) {
    use nix::sys::signal::{Signal, kill, killpg};
    use nix::unistd::Pid;
    use std::os::unix::process::CommandExt;
    use std::process::{Child, Command, Stdio};

    struct OwnedJob {
        keeper: Child,
        child: Option<Child>,
    }
    impl Drop for OwnedJob {
        fn drop(&mut self) {
            // The keeper is never reaped before this signal: its PID reserves
            // the group even if wt has already exited and been collected.
            let _ = killpg(Pid::from_raw(self.keeper.id() as i32), Signal::SIGKILL);
            if let Some(child) = &mut self.child {
                let _ = child.wait();
            }
            let _ = self.keeper.wait();
        }
    }

    let markers = worktrunk::testing::tempdir().unwrap();
    let ready = markers.path().join("ready");
    std::fs::create_dir(&ready).unwrap();
    let worker = r#"import json, os, pathlib, signal, sys
signal.signal(signal.SIGTERM, lambda *_: os._exit(int(sys.argv[2])))
directory = pathlib.Path(sys.argv[1])
temporary = directory.parent / f'{os.getpid()}.tmp'
temporary.write_text(json.dumps({'pid': os.getpid(), 'parent': os.getppid()}))
temporary.rename(directory / str(os.getpid()))
while True:
    signal.pause()
"#;

    let mut job = OwnedJob {
        keeper: Command::new("sleep")
            .arg("300")
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .process_group(0)
            .spawn()
            .unwrap(),
        child: None,
    };
    job.child = Some(
        repo.wt_command()
            .args([
                "-vv",
                "step",
                "for-each",
                "--format=json",
                "--",
                "python3",
                "-c",
            ])
            .arg(worker)
            .arg(&ready)
            .arg(exit_code.to_string())
            .env("RUST_LOG", crate::common::FOREGROUND_TRACE_FILTER)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .process_group(job.keeper.id() as i32)
            .spawn()
            .unwrap(),
    );

    crate::common::wait_for("for-each command readiness", || {
        assert!(
            job.child.as_mut().unwrap().try_wait().unwrap().is_none(),
            "wt exited before its command became ready"
        );
        std::fs::read_dir(&ready).unwrap().next().is_some()
    });
    let entry = std::fs::read_dir(&ready).unwrap().next().unwrap().unwrap();
    let metadata: serde_json::Value =
        serde_json::from_slice(&std::fs::read(entry.path()).unwrap()).unwrap();
    let controller = job.child.as_ref().unwrap().id() as i32;
    assert_eq!(metadata["parent"], controller);
    crate::common::wait_for_foreground_admission(
        &repo,
        &[metadata["pid"].as_i64().unwrap() as i32],
    );
    assert_eq!(
        nix::unistd::getpgid(Some(
            Pid::from_raw(metadata["pid"].as_i64().unwrap() as i32)
        ))
        .unwrap(),
        Pid::from_raw(job.keeper.id() as i32),
    );
    kill(Pid::from_raw(controller), Signal::SIGTERM).unwrap();

    crate::common::wait_for("cancelled for-each completion", || {
        job.child.as_mut().unwrap().try_wait().unwrap().is_some()
    });
    let output = job.child.take().unwrap().wait_with_output().unwrap();
    assert_eq!(crate::common::shell_exit_code(&output.status), Some(143));
    let json: serde_json::Value = serde_json::from_slice(&output.stdout)
        .unwrap_or_else(|e| panic!("cancelled run must emit JSON: {e}\n{output:?}"));
    let items = json.as_array().unwrap();
    assert_eq!(items.len(), 1, "{json}");
    assert_eq!(items[0]["exit_code"], exit_code, "{json}");
    assert_eq!(std::fs::read_dir(&ready).unwrap().count(), 1);
}

/// for-each relocates the user's command into each worktree, so inherited
/// git-discovery vars (`GIT_DIR`/`GIT_WORK_TREE`) must be scrubbed — git
/// resolves them before walking up from the cwd, so a forwarded value would
/// misdirect every iteration's `git` calls to the one inherited repo
/// (issue #3373; same contract as the hook tests in `user_hooks.rs`).
///
/// Sets a discovery context consistent with the repo wt operates on (as a
/// `!wt` git alias would), so wt itself runs normally; each visited worktree
/// records the `GIT_DIR`/`GIT_WORK_TREE` it sees — `[][]` once scrubbed.
#[rstest]
#[cfg(unix)]
fn test_for_each_does_not_inherit_git_discovery_vars(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let marker_dir = worktrunk::testing::tempdir().expect("create marker tmpdir");
    let marker_path = marker_dir.path().to_string_lossy().to_string();
    let shell_cmd = format!(
        r#"printf '[%s][%s]' "$GIT_DIR" "$GIT_WORK_TREE" > {marker_path}/$(basename "$(pwd)")"#
    );

    let output = repo
        .wt_command()
        .args(["step", "for-each", "--", "sh", "-c", &shell_cmd])
        .env("GIT_DIR", repo.root_path().join(".git"))
        .env("GIT_WORK_TREE", repo.root_path())
        .output()
        .expect("run wt step for-each");
    assert!(
        output.status.success(),
        "for-each run failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Both the primary worktree and the added one must have been visited and
    // seen a scrubbed environment; misdirection is only observable when the
    // command runs in a worktree other than the inherited context's.
    for dir in [repo.root_path(), feature_path.as_path()] {
        let marker = marker_dir
            .path()
            .join(dir.file_name().expect("worktree dir has a name"));
        let seen = std::fs::read_to_string(&marker)
            .unwrap_or_else(|e| panic!("marker for {} missing: {e}", dir.display()));
        assert_eq!(
            seen,
            "[][]",
            "for-each child in {} inherited git-discovery vars ([GIT_DIR][GIT_WORK_TREE]): {seen}",
            dir.display()
        );
    }
}

#[rstest]
fn test_for_each_skips_prunable_worktrees(mut repo: TestRepo) {
    let worktree_path = repo.add_worktree("feature");
    // Delete the worktree directory to make it prunable
    std::fs::remove_dir_all(&worktree_path).unwrap();

    // Verify git sees it as prunable
    let output = repo
        .git_command()
        .args(["worktree", "list", "--porcelain"])
        .run()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("prunable"),
        "Expected worktree to be prunable after deleting directory"
    );

    // wt step for-each should skip the prunable worktree and complete without errors
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["for-each", "--", "echo", "Running in {{ branch }}"],
        None,
    ));
}

// ============================================================================
// --format=json
// ============================================================================

#[rstest]
fn test_for_each_json(mut repo: TestRepo) {
    repo.commit("initial");
    repo.add_worktree("feature");

    let output = repo
        .wt_command()
        .args(["step", "for-each", "--format=json", "--", "true"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let json: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    let items = json.as_array().unwrap();
    assert!(items.len() >= 2, "expected at least 2 worktrees");
    for item in items {
        assert_eq!(item["success"], true);
        assert_eq!(item["exit_code"], 0);
        assert!(item["path"].as_str().is_some());
    }
    // feature worktree should be in results
    assert!(
        items.iter().any(|i| i["branch"] == "feature"),
        "feature branch should be in results"
    );
}

/// `{{ commit }}` must resolve per-worktree when iterating across worktrees
/// whose branches differ from the running worktree's branch. This exercises
/// the `rev-parse <branch>` fallback in `build_hook_context` — the on-branch
/// cache-reuse path would return the main worktree's SHA for every iteration.
#[rstest]
fn test_for_each_commit_matches_per_worktree_head(repo: TestRepo) {
    // Give each fixture feature worktree a distinct HEAD so a buggy cache
    // reuse (same SHA everywhere) fails visibly.
    let mut expected = std::collections::HashMap::new();
    expected.insert("main".to_string(), repo.git_output(&["rev-parse", "HEAD"]));
    for branch in ["feature-a", "feature-b", "feature-c"] {
        let wt_path = repo
            .root_path()
            .parent()
            .unwrap()
            .join(format!("repo.{branch}"));
        repo.run_git_in(
            &wt_path,
            &["commit", "--allow-empty", "-m", &format!("{branch} tip")],
        );
        let sha = repo
            .git_command()
            .args(["rev-parse", "HEAD"])
            .current_dir(&wt_path)
            .run()
            .unwrap();
        expected.insert(
            branch.to_string(),
            String::from_utf8_lossy(&sha.stdout).trim().to_owned(),
        );
    }

    // echo both fields so we can match each SHA to its branch.
    let output = repo
        .wt_command()
        .args([
            "step",
            "for-each",
            "--",
            "echo",
            "{{ branch }} {{ commit }}",
        ])
        .output()
        .expect("run wt step for-each");

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

    // for-each pipes foreground output through wt's styling layer, which may
    // wrap lines in ANSI codes. Substring-match `branch sha` anywhere in the
    // combined output — each worktree's echo contributes exactly one such
    // pairing, so a mis-resolved SHA (e.g., main's SHA appearing after
    // feature-b's branch label) is still caught.
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    for (branch, sha) in &expected {
        let needle = format!("{branch} {sha}");
        assert!(
            combined.contains(&needle),
            "expected {branch}'s {{{{ commit }}}} = {sha} in output\noutput={combined}",
        );
    }
}

/// `{{ commit }}` for a sibling worktree on detached HEAD must resolve to that
/// worktree's HEAD — not the running worktree's HEAD. The cache key for
/// `WorkingTree::head_sha` is the worktree path, and HEAD is per-worktree, so
/// reading via `repo.current_worktree()` in a detached sibling would return
/// the main worktree's SHA. Build a divergence: advance `feature-b` past the
/// shared tip, then detach it at that new SHA so its HEAD differs from main.
#[rstest]
fn test_for_each_commit_detached_sibling_matches_per_worktree_head(repo: TestRepo) {
    let feature_b_path = repo.worktree_path("feature-b").to_path_buf();
    repo.run_git_in(
        &feature_b_path,
        &["commit", "--allow-empty", "-m", "feature-b tip"],
    );
    repo.detach_head_in_worktree("feature-b");

    let main_sha = repo.git_output(&["rev-parse", "HEAD"]);
    let feature_b_sha = repo.head_sha_in(&feature_b_path);
    assert_ne!(
        main_sha, feature_b_sha,
        "detached sibling must have a distinct HEAD so a buggy fallback to the running worktree's SHA is visible",
    );

    let output = repo
        .wt_command()
        .args([
            "step",
            "for-each",
            "--",
            "echo",
            "[{% if branch %}{{ branch }}{% endif %}] {{ commit }}",
        ])
        .output()
        .expect("run wt step for-each");

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

    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    // A detached worktree leaves `{{ branch }}` unset, so its row renders the
    // empty guard. The sibling's commit must be its own HEAD, not the running
    // worktree's.
    let needle = format!("[] {feature_b_sha}");
    assert!(
        combined.contains(&needle),
        "expected detached sibling's {{{{ commit }}}} = {feature_b_sha} in output\noutput={combined}",
    );
    assert!(
        !combined.contains(&format!("[] {main_sha}")),
        "detached sibling's {{{{ commit }}}} must not resolve to main's SHA {main_sha}\noutput={combined}",
    );
}

#[rstest]
fn test_for_each_json_with_failure(repo: TestRepo) {
    repo.commit("initial");

    let output = repo
        .wt_command()
        .args(["step", "for-each", "--format=json", "--", "false"])
        .output()
        .unwrap();
    assert!(!output.status.success());
    let json: serde_json::Value =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    let items = json.as_array().unwrap();
    assert!(!items.is_empty());
    for item in items {
        assert_eq!(item["success"], false);
        assert_eq!(item["exit_code"], 1);
        // error field contains the raw message from the child process
        assert_eq!(item["error"], "exit code 1");
    }
}