Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python
202 KB
Raw Blame
import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import zipfile
from dataclasses import dataclass
from pathlib import Path

import pytest

FCC_COMMANDS = (
    "fcc-desktop",
    "fcc-server",
    "fcc-claude",
    "fcc-codex",
    "fcc-pi",
    "fcc-opencode",
    "fcc-cline",
    "fcc-hermes",
    "fcc-dsh",
    "fcc-grok",
    "fcc-muse",
    "fcc-aider",
    "fcc-doctor",
    "fcc-update",
    "fcc-init",
    "free-claude-code",
)

CODING_AGENTS = (
    "claude",
    "codex",
    "pi",
    "opencode",
    "cline",
    "hermes",
    "dsh",
    "grok",
    "muse",
    "aider",
)


@pytest.mark.parametrize("voice", [False, True])
def test_install_sh_pins_selected_fcc_release(posix_harness, voice):
    posix_harness.env["FCC_INSTALL_VERSION"] = "2.0.0"
    posix_harness.add_uv("0.13.4")
    result = posix_harness.run_functions(
        f"voice_local={int(voice)}\nvalidate_args\ninstall_free_claude_code\ninstaller_path=''\nprint_installer_retry"
    )
    assert result.returncode == 0, result.stdout + result.stderr
    spec = (
        "free-claude-code[voice_local]==2.0.0" if voice else "free-claude-code==2.0.0"
    )
    assert any(call.endswith(spec) for call in posix_harness.calls())
    assert "/v2.0.0/scripts/install.sh" in result.stdout
    assert "FCC_INSTALL_VERSION=" in result.stdout


@pytest.mark.parametrize("voice", [False, True])
def test_install_ps1_pins_selected_fcc_release(powershell_harness, voice):
    powershell_harness.env["FCC_INSTALL_VERSION"] = "2.0.0"
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run_functions(
        "Install-FreeClaudeCode\n$script:InstallerPath = ''\nWrite-Output (Get-InstallerRetryCommand)",
        *(["-VoiceLocal"] if voice else []),
    )
    assert result.returncode == 0, result.stdout + result.stderr
    spec = (
        "free-claude-code[voice_local]==2.0.0" if voice else "free-claude-code==2.0.0"
    )
    assert any(call.endswith(spec) for call in powershell_harness.calls())
    assert "/v2.0.0/scripts/install.ps1" in result.stdout
    assert "$env:FCC_INSTALL_VERSION = '2.0.0'" in result.stdout


@pytest.mark.parametrize(
    "version",
    [
        "2.0",
        "v2.0.0",
        "02.0.0",
        "2.0.0rc1",
        "2.0.0+local",
        "2.0.0\n3.0.0",
        "2.0.0/../main",
    ],
)
def test_install_sh_rejects_invalid_fcc_release_before_changes(posix_harness, version):
    posix_harness.env["FCC_INSTALL_VERSION"] = version
    result = posix_harness.run("--dry-run")
    assert result.returncode != 0
    assert "FCC_INSTALL_VERSION" in result.stderr
    assert posix_harness.calls() == []
    assert not (Path(posix_harness.env["HOME"]) / ".fcc/logs").exists()


@pytest.mark.parametrize(
    "version",
    [
        "2.0",
        "v2.0.0",
        "02.0.0",
        "2.0.0rc1",
        "2.0.0+local",
        "2.0.0\n3.0.0",
        "2.0.0/../main",
    ],
)
def test_install_ps1_rejects_invalid_fcc_release_before_changes(
    powershell_harness, version
):
    powershell_harness.env["FCC_INSTALL_VERSION"] = version
    result = powershell_harness.run("-DryRun")
    assert result.returncode != 0
    assert "FCC_INSTALL_VERSION" in result.stderr
    assert powershell_harness.calls() == []
    assert not (Path(powershell_harness.env["USERPROFILE"]) / ".fcc/logs").exists()


def test_install_ps1_bundle_dry_run_includes_headroom(powershell_harness):
    result = powershell_harness.run("-RtkHeadroom", "-DryRun")
    assert result.returncode == 0, result.stderr
    assert "headroom-ai[mcp]==0.40.0" in result.stdout
    assert "mcp install --agent claude" in result.stdout
    assert "_fcc-configure-headroom" not in result.stdout
    assert not any("headroom-ai" in call for call in powershell_harness.calls())


def test_install_sh_bundle_dry_run_includes_headroom(posix_harness):
    result = posix_harness.run("--rtk-headroom", "--dry-run")
    assert result.returncode == 0, result.stderr
    assert "headroom-ai[mcp]==0.40.0" in result.stdout
    assert "mcp install --agent claude" in result.stdout
    assert "_fcc-configure-headroom" not in result.stdout
    assert not any("headroom-ai" in call for call in posix_harness.calls())


def _assert_headroom_bundle_workflow(harness, failure, reuse):
    windows = isinstance(harness, PowerShellHarness)
    for agent in CODING_AGENTS:
        harness.add_client(agent)
    harness.add_uv("0.13.4")
    harness.add_rtk()
    if reuse:
        harness.add_client("headroom")
    flag = "-RtkHeadroom" if windows else "--rtk-headroom"
    result = harness.run(flag, fail_step=failure)
    calls = harness.calls()
    package = [call for call in calls if "headroom-ai[mcp]" in call]
    setup = [call for call in calls if call.startswith("headroom:mcp install --agent")]
    rtk = [call for call in calls if call.startswith("rtk:init")]
    assert bool(package) is (not reuse)
    if failure:
        assert result.returncode != 0, result.stdout + result.stderr
        stage = (
            "Headroom configuration"
            if failure == "headroom-configure"
            else "Headroom verification"
        )
        assert f"Failed: {stage}" in result.stdout
        assert flag in result.stdout.split("Retry:", 1)[1]
        if failure in {"headroom-install", "headroom-check"}:
            assert not rtk and not setup
        else:
            assert rtk and setup == [
                "headroom:mcp install --agent claude",
                "headroom:mcp install --agent codex",
            ]
        offset = len(calls)
        result = harness.run(flag)
        assert result.returncode == 0, result.stdout + result.stderr
        calls = harness.calls()[offset:]
        setup = [
            call for call in calls if call.startswith("headroom:mcp install --agent")
        ]
        rtk = [call for call in calls if call.startswith("rtk:init")]
    assert result.returncode == 0, result.stdout + result.stderr
    assert setup == [
        f"headroom:mcp install --agent {agent}" for agent in ("claude", "codex", "grok")
    ]
    assert (
        calls.index("headroom:--version") < calls.index(rtk[0]) < calls.index(setup[0])
    )
    assert not any("_fcc-configure-headroom" in call for call in calls)


@pytest.mark.parametrize(
    ("failure", "reuse"),
    [
        ("", False),
        ("", True),
        ("headroom-install", False),
        ("headroom-check", False),
        ("headroom-configure", False),
    ],
)
def test_install_ps1_headroom_bundle_workflow(powershell_harness, failure, reuse):
    _assert_headroom_bundle_workflow(powershell_harness, failure, reuse)


@pytest.mark.parametrize(
    ("failure", "reuse"),
    [
        ("", False),
        ("", True),
        ("headroom-install", False),
        ("headroom-check", False),
        ("headroom-configure", False),
    ],
)
def test_install_sh_headroom_bundle_workflow(posix_harness, failure, reuse):
    _assert_headroom_bundle_workflow(posix_harness, failure, reuse)


@pytest.mark.parametrize("selected", ["claude", "codex", "grok", "unsupported"])
def test_install_sh_headroom_native_selection(posix_harness, selected):
    posix_harness.add_client("headroom")
    flags = "\n".join(f"install_{name}=0" for name in ("claude", "codex", "grok"))
    if selected != "unsupported":
        flags += f"\ninstall_{selected}=1"
    result = posix_harness.run_functions(
        flags
        + "\nheadroom_path=$(command -v headroom)\nconfigure_headroom_for_selected_agents"
    )
    assert result.returncode == 0, result.stdout + result.stderr
    assert posix_harness.calls() == (
        []
        if selected == "unsupported"
        else [f"headroom:mcp install --agent {selected}"]
    )
    if selected == "unsupported":
        assert "skip" in result.stdout.lower()


@pytest.mark.parametrize("selected", ["claude", "codex", "grok", "unsupported"])
def test_install_ps1_headroom_native_selection(powershell_harness, selected):
    powershell_harness.add_client("headroom")
    variables = {
        "claude": "InstallClaudeCode",
        "codex": "InstallCodex",
        "grok": "InstallGrok",
    }
    flags = "\n".join(f"$script:{name} = $false" for name in variables.values())
    if selected != "unsupported":
        flags += f"\n$script:{variables[selected]} = $true"
    result = powershell_harness.run_functions(
        flags
        + '\n$script:HeadroomPath = (Get-ApplicationCommand "headroom").Source\nConfigure-HeadroomForSelectedAgents'
    )
    assert result.returncode == 0, result.stdout + result.stderr
    assert powershell_harness.calls() == (
        []
        if selected == "unsupported"
        else [f"headroom:mcp install --agent {selected}"]
    )
    if selected == "unsupported":
        assert "skip" in result.stdout.lower()


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[2]


def _assert_uv_ready_without_fcc_install(calls: list[str]) -> None:
    assert "uv:--version" in calls
    assert not any("--refresh-package free-claude-code" in call for call in calls)


def _write_executable(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")
    path.chmod(0o755)


def _braced_body(text: str, declaration: str) -> str:
    start = text.index(declaration)
    brace_start = text.index("{", start)
    depth = 0
    for index, char in enumerate(text[brace_start:], start=brace_start):
        if char == "{":
            depth += 1
        elif char == "}":
            depth -= 1
            if depth == 0:
                return text[brace_start + 1 : index]
    raise AssertionError(f"Unclosed function body for {declaration}")


def _posix_command(name: str, *, version_output: str | None = None) -> str:
    version = {
        "opencode": "v2.0.10",
        "cline": "3.0.55",
        "hermes": "0.20.4",
        "dsh": "0.2.0-rc.2",
        "grok": "1.0.5",
        "muse": "0.2.1",
        "node": "22.19.0",
    }.get(name, "1.0.0")
    if version_output is None:
        if name == "hermes":
            version_output = f"Hermes Agent v{version} (test build)"
        elif name == "grok":
            version_output = f"grok {version} (5115b46bc9) [stable]"
        elif name == "muse":
            version_output = f"Muse Code {version} ({version}-R1215.1)"
        else:
            version_output = f"{name} {version}"
    version_command = f'''if [ "${{1:-}}" = "--version" ]; then
    echo "{version_output}"
fi'''
    help_output = (
        '    echo "  --extension, -e <path>  Load an extension"\n'
        '    echo "  --models <patterns>     Scope models"'
        if name == "pi"
        else "    :"
    )
    return f"""#!/bin/sh
echo "{name}:$*" >> "$CALL_LOG"
if [ "{name}" = "opencode" ] && [ "${{FCC_RUNNING_PHASE:-}}" = "opencode-plugin" ]; then
    if [ -e "$FCC_PROCESS_MARKER.probed" ]; then
        : > "$FCC_PROCESS_MARKER"
    else
        : > "$FCC_PROCESS_MARKER.probed"
    fi
fi
if [ "{name}" = "headroom" ]; then
    [ "$FAIL_STEP" != "headroom-check" ] || exit 79
    if [ "$FAIL_STEP" = "headroom-configure" ] && [ "${{4:-}}" = "codex" ]; then exit 80; fi
fi
if [ "$FAIL_STEP" = "{name}-verify" ]; then
    exit 31
fi
{version_command}
if [ "${{1:-}}" = "--help" ]; then
{help_output}
fi
"""


def _posix_npm_command() -> str:
    return """#!/bin/sh
echo "npm:$*" >> "$CALL_LOG"
if [ "${1:-}" = "install" ] && [ "${2:-}" = "-g" ] && [ "${3:-}" = "cline" ]; then
    [ "$FAIL_STEP" = "cline-install" ] && exit 72
    mkdir -p "$FAKE_NPM_PREFIX/bin"
    cp "$FAKE_FIXTURES/cline-command.sh" "$FAKE_NPM_PREFIX/bin/cline"
    chmod +x "$FAKE_NPM_PREFIX/bin/cline"
    exit 0
fi
if [ "${1:-}" = "install" ] && [ "${2:-}" = "-g" ] && [ "${3:-}" = "@deepseek-ai/dsh@latest" ]; then
    [ "$FAIL_STEP" = "dsh-install" ] && exit 73
    mkdir -p "$FAKE_NPM_PREFIX/bin"
    cp "$FAKE_FIXTURES/dsh-command.sh" "$FAKE_NPM_PREFIX/bin/dsh"
    chmod +x "$FAKE_NPM_PREFIX/bin/dsh"
    exit 0
fi
if [ "${1:-}" = "prefix" ] && [ "${2:-}" = "-g" ]; then
    printf '%s\n' "$FAKE_NPM_PREFIX"
    exit 0
fi
if [ "${1:-}" = "config" ] && [ "${2:-}" = "get" ] && [ "${3:-}" = "prefix" ]; then
    printf '%s\n' "$FAKE_NPM_PREFIX"
    exit 0
fi
exit 71
"""


def _posix_uv_command(version: str) -> str:
    return f"""#!/bin/sh
echo "uv:$*" >> "$CALL_LOG"
tool_bin=${{UV_TOOL_BIN_DIR:-$FAKE_TOOL_BIN}}
if [ "${{1:-}}" = "--version" ]; then
    if [ "${{FCC_RUNNING_PHASE:-}}" = "late" ]; then
        : > "$FCC_PROCESS_MARKER"
    fi
    if [ "$FAIL_STEP" = "uv-verify" ]; then
        exit 32
    fi
    echo "uv {version}"
    exit 0
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "install" ]; then
    case " $* " in
        *" headroom-ai[mcp]==0.40.0 "*)
            [ "$FAIL_STEP" = "headroom-install" ] && exit 78
            mkdir -p "$tool_bin"
            cp "$FAKE_FIXTURES/headroom-command.sh" "$tool_bin/headroom"
            chmod +x "$tool_bin/headroom"
            exit 0
            ;;
        *" aider-chat@latest "*)
            if [ "$FAIL_STEP" = "aider-install" ]; then
                exit 29
            fi
            mkdir -p "$tool_bin"
            cp "$FAKE_FIXTURES/aider-command.sh" "$tool_bin/aider"
            chmod +x "$tool_bin/aider"
            exit 0
            ;;
    esac
    if [ "$FAIL_STEP" = "fcc-install" ]; then
        exit 33
    fi
    mkdir -p "$tool_bin"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-server"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-desktop"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-claude"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-pi"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-opencode"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-cline"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-hermes"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-dsh"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-grok"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-muse"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-aider"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-doctor"
    cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-update"
    if [ "$FAIL_STEP" != "fcc-missing" ]; then
        cp "$FAKE_FIXTURES/fcc-command.sh" "$tool_bin/fcc-codex"
    fi
    chmod +x "$tool_bin"/fcc-*
    exit 0
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "update-shell" ]; then
    if [ "$FAIL_STEP" = "path-update" ]; then
        exit 34
    fi
    exit 0
fi
if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "dir" ] && [ "${{3:-}}" = "--bin" ]; then
    printf '%s\n' "$tool_bin"
    exit 0
fi
exit 35
"""


def _posix_rtk_command() -> str:
    return """#!/bin/sh
echo "rtk:$*:telemetry=${RTK_TELEMETRY_DISABLED:-}" >> "$CALL_LOG"
if [ "$*" = "init --global --auto-patch" ]; then
    claude_config_directory=${CLAUDE_CONFIG_DIR:-$HOME/.claude}
    [ -d "$claude_config_directory" ] || exit 77
fi
case "${1:-}:$FAIL_STEP" in
    --version:rtk-verify|gain:rtk-verify) exit 72 ;;
esac
case "$*:$FAIL_STEP" in
    "init --global --auto-patch:rtk-init-claude") exit 73 ;;
    "init --global --codex:rtk-init-codex") exit 74 ;;
    "init --global --agent pi:rtk-init-pi") exit 75 ;;
    "init --global --opencode:rtk-init-opencode") exit 76 ;;
esac
if [ "${1:-}" = "--version" ]; then
    echo "rtk 0.44.2"
fi
exit 0
"""


@dataclass
class PosixHarness:
    root: Path
    bin_dir: Path
    fixtures: Path
    tool_bin: Path
    log: Path
    env: dict[str, str]

    def add_client(self, name: str) -> None:
        _write_executable(self.bin_dir / name, _posix_command(name))

    def add_unrelated_pi(self) -> None:
        _write_executable(self.bin_dir / "pi", _posix_command("unrelated-pi"))

    def add_npm_prefix(self, prefix: Path) -> None:
        prefix.mkdir(parents=True)
        self.env["FAKE_NPM_PREFIX"] = str(prefix)
        _write_executable(self.bin_dir / "npm", _posix_npm_command())

    def add_uv(self, version: str) -> None:
        _write_executable(self.bin_dir / "uv", _posix_uv_command(version))

    def add_rtk(self) -> None:
        _write_executable(self.bin_dir / "rtk", _posix_rtk_command())

    def add_unrelated_rtk(self) -> None:
        _write_executable(
            self.bin_dir / "rtk",
            """#!/bin/sh
echo "unrelated-rtk:$*" >> "$CALL_LOG"
[ "${1:-}" = "--version" ] && echo "rtk 1.0.0" && exit 0
exit 76
""",
        )

    def use_process_list_fallback(self, process_line: str) -> None:
        fallback_bin = self.root / "fallback-bin"
        fallback_bin.mkdir()
        _write_executable(
            fallback_bin / "ps",
            """#!/bin/sh
printf '%s\n' "$FCC_PS_OUTPUT"
""",
        )
        awk = shutil.which("awk", path=self.env["PATH"])
        if awk is None:
            pytest.skip("awk is required for the POSIX process fallback scenario")
        shutil.copy(awk, fallback_bin / "awk")
        self.env["FCC_PS_OUTPUT"] = process_line
        self.env["PATH"] = str(fallback_bin)

    def run(self, *args: str, fail_step: str = "") -> subprocess.CompletedProcess[str]:
        env = self.env | {"FAIL_STEP": fail_step}
        return subprocess.run(
            ["/bin/sh", str(_repo_root() / "scripts" / "install.sh"), *args],
            check=False,
            capture_output=True,
            text=True,
            env=env,
        )

    def run_interactive(
        self,
        answers: str,
        *args: str,
        fail_step: str = "",
    ) -> subprocess.CompletedProcess[str]:
        source = (_repo_root() / "scripts/install.sh").read_text(encoding="utf-8")
        source = source.replace(
            '    step "Choosing coding agents"',
            "    selection_path_before=$PATH\n"
            "    selection_opencode_before=$original_opencode_path\n"
            '    step "Choosing coding agents"',
        ).replace(
            "    choose_coding_agents /dev/tty /dev/tty",
            "    choose_coding_agents /dev/tty /dev/tty\n"
            '    [ "$PATH" = "$selection_path_before" ] || fail "Selection changed PATH"\n'
            '    [ "$original_opencode_path" = "$selection_opencode_before" ] || fail "Selection changed original OpenCode"',
        )
        installer = self.root / "interactive-installer.sh"
        installer.write_text(source, encoding="utf-8")
        env = self.env | {
            "FAIL_STEP": fail_step,
            "FCC_INSTALLER": str(installer),
        }
        command = [
            "/bin/sh",
            "-c",
            'cat "$FCC_INSTALLER" | /bin/sh -s -- "$@"',
            "fcc-installer",
            *args,
        ]
        return subprocess.run(
            [
                sys.executable,
                "-W",
                "error",
                str(Path(__file__).with_name("_pty_runner.py")),
                *command,
            ],
            input=answers,
            check=False,
            capture_output=True,
            text=True,
            env=env,
            timeout=30,
        )

    def function_scenario(self, body: str) -> Path:
        source = (_repo_root() / "scripts/install.sh").read_text(encoding="utf-8")
        scenario = self.root / "function-scenario.sh"
        scenario.write_text(
            source.split('\nparse_args "$@"\n', 1)[0] + "\n" + body + "\n",
            encoding="utf-8",
        )
        return scenario

    def run_functions(self, body: str) -> subprocess.CompletedProcess[str]:
        return subprocess.run(
            ["/bin/sh", str(self.function_scenario(body))],
            check=False,
            capture_output=True,
            text=True,
            env=self.env,
            timeout=20,
        )

    def calls(self) -> list[str]:
        if not self.log.exists():
            return []
        return self.log.read_text(encoding="utf-8").splitlines()


@pytest.fixture
def posix_harness(tmp_path: Path) -> PosixHarness:
    if os.name == "nt":
        pytest.skip("POSIX installer scenarios run on POSIX hosts")

    bin_dir = tmp_path / "bin"
    fixtures = tmp_path / "fixtures"
    tool_bin = tmp_path / "tool-bin"
    home = tmp_path / "home"
    log = tmp_path / "calls.log"
    for path in (bin_dir, fixtures, tool_bin, home):
        path.mkdir(parents=True)

    _write_executable(
        bin_dir / "pgrep",
        """#!/bin/sh
[ -n "${FCC_RUNNING_COMMAND:-}" ] || exit 1
if [ "${FCC_RUNNING_PHASE:-early}" != "early" ] && [ ! -e "$FCC_PROCESS_MARKER" ]; then
    exit 1
fi
case "$*" in
    "-x $FCC_RUNNING_COMMAND"|"-f (^|/)$FCC_RUNNING_COMMAND([[:space:]]|$)") printf '4242\n'; exit 0 ;;
    *) exit 1 ;;
esac
""",
    )
    _write_executable(
        bin_dir / "getent",
        """#!/bin/sh
[ "${1:-}" = "passwd" ] || exit 61
printf 'fcc-test:x:1000:1000::%s:/bin/sh\n' "$FAKE_INFERRED_HOME"
""",
    )
    _write_executable(
        bin_dir / "curl",
        """#!/bin/sh
url=""
output=""
while [ "$#" -gt 0 ]; do
    case "$1" in
        -o)
            shift
            output=$1
            ;;
        http*)
            url=$1
            ;;
    esac
    shift
done
echo "download:$url" >> "$CALL_LOG"
case "$url:$FAIL_STEP" in
    *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*opencode.ai*:opencode-download|*hermes-agent.nousresearch.com*:hermes-download|*x.ai*:grok-download|*dev.meta.ai*:muse-download|*rtk-ai*:rtk-download|*astral.sh*:uv-download)
        exit 41
        ;;
esac
case "$url" in
    *claude.ai*) source="$FAKE_FIXTURES/claude-installer.sh" ;;
    *chatgpt.com*) source="$FAKE_FIXTURES/codex-installer.sh" ;;
    *pi.dev*) source="$FAKE_FIXTURES/pi-installer.sh" ;;
    *opencode.ai*)
        source="$FAKE_FIXTURES/opencode-installer.sh"
        if [ "${FCC_RUNNING_PHASE:-}" = "opencode-download" ]; then
            : > "$FCC_PROCESS_MARKER"
        fi
        ;;
    *hermes-agent.nousresearch.com*) source="$FAKE_FIXTURES/hermes-installer.sh" ;;
    *x.ai*) source="$FAKE_FIXTURES/grok-installer.sh" ;;
    *dev.meta.ai*) source="$FAKE_FIXTURES/muse-installer.sh" ;;
    *rtk-ai*)
        if [ "$FAIL_STEP" = "rtk-install" ]; then
            printf 'invalid archive\n' > "$output"
            exit 0
        fi
        source="$FAKE_FIXTURES/rtk-x86_64-unknown-linux-musl.tar.gz"
        ;;
    *astral.sh*) source="$FAKE_FIXTURES/uv-installer.sh" ;;
    *) exit 42 ;;
esac
cp "$source" "$output"
""",
    )
    _write_executable(
        fixtures / "claude-installer.sh",
        """#!/bin/sh
echo "claude-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "claude-install" ] && exit 21
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/claude-command.sh" "$HOME/.local/bin/claude"
chmod +x "$HOME/.local/bin/claude"
""",
    )
    _write_executable(
        fixtures / "codex-installer.sh",
        """#!/bin/sh
echo "codex-install:$CODEX_NON_INTERACTIVE" >> "$CALL_LOG"
[ "$FAIL_STEP" = "codex-install" ] && exit 22
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/codex-command.sh" "$HOME/.local/bin/codex"
chmod +x "$HOME/.local/bin/codex"
""",
    )
    _write_executable(
        fixtures / "pi-installer.sh",
        """#!/bin/sh
echo "pi-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "pi-install" ] && exit 24
[ "$FAIL_STEP" = "pi-skip" ] && exit 0
if [ -n "${FAKE_NPM_PREFIX:-}" ]; then
    pi_bin="$FAKE_NPM_PREFIX/bin"
else
    pi_bin="$HOME/.local/bin"
fi
mkdir -p "$pi_bin"
cp "$FAKE_FIXTURES/pi-command.sh" "$pi_bin/pi"
chmod +x "$pi_bin/pi"
""",
    )
    _write_executable(
        fixtures / "opencode-installer.sh",
        """#!/bin/sh
echo "opencode-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "opencode-install" ] && exit 25
mkdir -p "$HOME/.opencode/bin"
cp "$FAKE_FIXTURES/opencode-command.sh" "$HOME/.opencode/bin/opencode"
if [ -n "${VERSION:-}" ]; then
    printf '#!/bin/sh\necho "opencode v%s"\n' "$VERSION" > "$HOME/.opencode/bin/opencode"
fi
chmod +x "$HOME/.opencode/bin/opencode"
""",
    )
    _write_executable(
        fixtures / "hermes-installer.sh",
        """#!/bin/sh
echo "hermes-install:$*" >> "$CALL_LOG"
[ "$FAIL_STEP" = "hermes-install" ] && exit 26
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/hermes-command.sh" "$HOME/.local/bin/hermes"
chmod +x "$HOME/.local/bin/hermes"
""",
    )
    _write_executable(
        fixtures / "grok-installer.sh",
        """#!/bin/sh
echo "grok-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "grok-install" ] && exit 27
grok_bin="${GROK_BIN_DIR:-$HOME/.grok/bin}"
mkdir -p "$grok_bin"
cp "$FAKE_FIXTURES/grok-command.sh" "$grok_bin/grok"
chmod +x "$grok_bin/grok"
""",
    )
    _write_executable(
        fixtures / "muse-installer.sh",
        """#!/bin/sh
echo "muse-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "muse-install" ] && exit 28
mkdir -p "$HOME/.local/bin"
cp "$FAKE_FIXTURES/muse-command.sh" "$HOME/.local/bin/muse"
chmod +x "$HOME/.local/bin/muse"
""",
    )
    _write_executable(
        fixtures / "uv-installer.sh",
        """#!/bin/sh
echo "uv-install" >> "$CALL_LOG"
[ "$FAIL_STEP" = "uv-install" ] && exit 23
inferred_home=${HOME:-}
if [ -z "$inferred_home" ]; then
    if [ -n "${USER:-}" ]; then
        inferred_home=$(getent passwd "$USER" | cut -d: -f6)
    else
        inferred_home=$(getent passwd "$(id -un)" | cut -d: -f6)
    fi
fi
force_install_dir=""
if [ -n "${UV_INSTALL_DIR:-}" ]; then
    force_install_dir=$UV_INSTALL_DIR
elif [ -n "${UV_UNMANAGED_INSTALL:-}" ]; then
    force_install_dir=$UV_UNMANAGED_INSTALL
fi
if [ -n "$force_install_dir" ]; then
    uv_bin=$force_install_dir
    if [ "$force_install_dir" = "${CARGO_HOME:-$inferred_home/.cargo}" ]; then
        uv_bin=$force_install_dir/bin
    fi
elif [ -n "${XDG_BIN_HOME:-}" ]; then
    uv_bin=$XDG_BIN_HOME
elif [ -n "${XDG_DATA_HOME:-}" ]; then
    uv_bin=$XDG_DATA_HOME/../bin
else
    uv_bin=$inferred_home/.local/bin
fi
mkdir -p "$uv_bin"
cp "$FAKE_FIXTURES/uv-command.sh" "$uv_bin/uv"
chmod +x "$uv_bin/uv"
""",
    )
    _write_executable(fixtures / "claude-command.sh", _posix_command("claude"))
    _write_executable(fixtures / "codex-command.sh", _posix_command("codex"))
    _write_executable(fixtures / "pi-command.sh", _posix_command("pi"))
    _write_executable(fixtures / "opencode-command.sh", _posix_command("opencode"))
    _write_executable(fixtures / "cline-command.sh", _posix_command("cline"))
    _write_executable(fixtures / "hermes-command.sh", _posix_command("hermes"))
    _write_executable(fixtures / "dsh-command.sh", _posix_command("dsh"))
    _write_executable(fixtures / "grok-command.sh", _posix_command("grok"))
    _write_executable(fixtures / "muse-command.sh", _posix_command("muse"))
    _write_executable(fixtures / "aider-command.sh", _posix_command("aider"))
    rtk_command = _posix_rtk_command().encode()
    with tarfile.open(
        fixtures / "rtk-x86_64-unknown-linux-musl.tar.gz", "w:gz"
    ) as archive:
        metadata = tarfile.TarInfo("rtk")
        metadata.mode = 0o755
        metadata.size = len(rtk_command)
        archive.addfile(metadata, io.BytesIO(rtk_command))
    _write_executable(fixtures / "uv-command.sh", _posix_uv_command("0.13.4"))
    _write_executable(fixtures / "headroom-command.sh", _posix_command("headroom"))
    _write_executable(
        fixtures / "fcc-command.sh",
        """#!/bin/sh
name=${0##*/}
echo "$name:$*" >> "$CALL_LOG"
if [ "$FAIL_STEP" = "fcc-verify" ]; then
    exit 36
fi
if [ "$name" = "fcc-desktop" ] && [ "${1:-}" = "--install-macos-app" ]; then
    [ "$FAIL_STEP" = "macos-app-setup" ] && exit 37
fi
if [ "$name" = "fcc-server" ] && [ "${1:-}" = "--version" ]; then
    echo "free-claude-code 3.5.18"
fi
""",
    )
    _write_executable(
        bin_dir / "uname",
        """#!/bin/sh
case "${1:-}" in
    -m) printf '%s\n' "${FAKE_UNAME_MACHINE:-x86_64}" ;;
    *) printf '%s\n' "${FAKE_UNAME:-Linux}" ;;
esac
""",
    )
    _write_executable(bin_dir / "opencode", _posix_command("opencode"))
    _write_executable(bin_dir / "node", _posix_command("node"))
    npm_prefix = tmp_path / "npm-prefix"
    npm_prefix.mkdir()
    _write_executable(bin_dir / "npm", _posix_npm_command())
    _write_executable(
        bin_dir / "sha256sum",
        """#!/bin/sh
echo "sha256sum:$*" >> "$CALL_LOG"
case "$1" in
    */rtk.ts) exec /usr/bin/shasum -a 256 "$1" ;;
esac
if [ "$FAIL_STEP" = "rtk-checksum" ]; then
    checksum="0000000000000000000000000000000000000000000000000000000000000000"
else
    checksum="d94cc2a3e57fa534892b5235a726e7eeb7523f205a5f8f48f853bfcae7be7e33"
fi
printf '%s  %s\n' "$checksum" "$1"
""",
    )

    env = os.environ.copy()
    env.update(
        {
            "PATH": f"{bin_dir}:/usr/bin:/bin",
            "HOME": str(home),
            "CALL_LOG": str(log),
            "FAKE_FIXTURES": str(fixtures),
            "FAKE_TOOL_BIN": str(tool_bin),
            "FAKE_INFERRED_HOME": str(home),
            "FCC_PROCESS_MARKER": str(tmp_path / "fcc-process-ready"),
            "FCC_RUNNING_COMMAND": "",
            "FCC_RUNNING_PHASE": "early",
            "FAKE_UNAME": "Linux",
            "FAKE_NPM_PREFIX": str(npm_prefix),
            "USER": "fcc-test",
            "CLAUDE_CONFIG_DIR": "",
            "FAIL_STEP": "",
        }
    )
    env.pop("XDG_BIN_HOME", None)
    env.pop("XDG_DATA_HOME", None)
    env.pop("UV_INSTALL_DIR", None)
    env.pop("UV_UNMANAGED_INSTALL", None)
    env.pop("UV_TOOL_BIN_DIR", None)
    env.pop("CARGO_HOME", None)
    env.pop("GROK_BIN_DIR", None)
    return PosixHarness(tmp_path, bin_dir, fixtures, tool_bin, log, env)


@pytest.mark.parametrize("rtk", (False, True, None))
def test_install_sh_auto_selects_installed_harnesses(
    posix_harness: PosixHarness, rtk: bool | None
) -> None:
    if rtk is not None:
        posix_harness.add_rtk()
    for command in CODING_AGENTS:
        posix_harness.add_client(command)

    result = posix_harness.run_interactive(
        "" if rtk else "\n", *(("--rtk-headroom",) if rtk else ())
    )

    assert result.returncode == 0, result.stdout
    assert "Install or verify" not in result.stdout
    assert "for fcc-" not in result.stdout
    assert ("Enable RTK + Headroom token optimization" in result.stdout) is (
        rtk is not True
    )
    for command in CODING_AGENTS:
        assert f"{command}:--version" in posix_harness.calls()
    assert ("rtk:--version:telemetry=1" in posix_harness.calls()) is (rtk is True)
    assert ("rtk:init --global --codex:telemetry=1" in posix_harness.calls()) is (
        rtk is True
    )


@pytest.mark.parametrize("install_codex", (False, True))
@pytest.mark.parametrize("rtk", (False, True))
def test_install_sh_asks_only_about_missing_harnesses(
    posix_harness: PosixHarness, install_codex: bool, rtk: bool
) -> None:
    posix_harness.add_client("claude")
    if rtk:
        posix_harness.add_rtk()

    result = posix_harness.run_interactive(
        ("y\n" if install_codex else "\n") + "\n" * 8
    )

    assert result.returncode == 0, result.stdout
    assert re.findall(r"for fcc-(\w+)\?", result.stdout) == [
        "codex",
        "pi",
        "cline",
        "hermes",
        "dsh",
        "grok",
        "muse",
        "aider",
    ]
    calls = posix_harness.calls()
    assert "claude:--version" in calls
    assert "opencode:--version" in calls
    assert ("codex-install:1" in calls) is install_codex
    assert not any(f"{command}:--version" in calls for command in CODING_AGENTS[4:])
    assert "Enable RTK + Headroom token optimization" in result.stdout
    assert not any(call.startswith("rtk:init") for call in calls)


def test_install_sh_discovers_installed_npm_harnesses_before_questions(
    posix_harness: PosixHarness,
) -> None:
    prefix = posix_harness.root / "custom npm"
    posix_harness.add_npm_prefix(prefix)
    for command in ("pi", "cline", "dsh"):
        _write_executable(prefix / "bin" / command, _posix_command(command))

    result = posix_harness.run_interactive("n\n" * 7)

    assert result.returncode == 0, result.stdout
    assert re.findall(r"for fcc-(\w+)\?", result.stdout) == [
        "claude",
        "codex",
        "hermes",
        "grok",
        "muse",
        "aider",
    ]
    calls = posix_harness.calls()
    assert "pi-install" not in calls
    assert not any(call.startswith("npm:install") for call in calls)
    for command in ("pi", "cline", "dsh"):
        assert f"{command}:--version" in calls


@pytest.mark.parametrize(
    "location", ("UV_TOOL_BIN_DIR", "XDG_BIN_HOME", "XDG_DATA_HOME", "home")
)
def test_install_sh_discovers_installed_aider_without_uv(
    posix_harness: PosixHarness, location: str
) -> None:
    tool_bin = _aider_discovery_location(
        posix_harness.root, posix_harness.env, location
    )
    _write_executable(tool_bin / "aider", _posix_command("aider"))

    result = posix_harness.run_interactive("n\n" * 9)

    assert result.returncode == 0, result.stdout
    assert "for fcc-aider?" not in result.stdout
    calls = posix_harness.calls()
    assert "aider:--version" in calls
    assert not any("aider-chat@latest" in call for call in calls)
    assert "uv-install" in calls


def test_install_sh_asks_about_unrelated_pi(posix_harness: PosixHarness) -> None:
    posix_harness.add_unrelated_pi()

    result = posix_harness.run_interactive("n\n" * 10)

    assert result.returncode == 0, result.stdout
    assert "Install Pi for fcc-pi?" in result.stdout
    calls = posix_harness.calls()
    assert "unrelated-pi:--help" in calls
    assert "unrelated-pi:--version" not in calls
    assert "pi-install" not in calls


def test_install_sh_interactive_dry_run_does_not_execute_probes(
    posix_harness: PosixHarness,
) -> None:
    for command in CODING_AGENTS:
        posix_harness.add_client(command)

    result = posix_harness.run_interactive("n\n", "--dry-run")

    assert result.returncode == 0, result.stdout
    assert "for fcc-" not in result.stdout
    assert posix_harness.calls() == []


def test_install_sh_failed_npm_discovery_does_not_block_selection(
    posix_harness: PosixHarness,
) -> None:
    _write_executable(
        posix_harness.bin_dir / "npm",
        '#!/bin/sh\necho "npm:$*" >> "$CALL_LOG"\nexit 72\n',
    )

    result = posix_harness.run_interactive("n\n" * 10)

    assert result.returncode == 0, result.stdout
    assert "opencode:--version" in posix_harness.calls()
    assert "npm:config get prefix" in posix_harness.calls()


@pytest.mark.parametrize("variable", ("UV_INSTALL_DIR", "UV_UNMANAGED_INSTALL"))
def test_install_sh_does_not_use_uv_install_directory_for_aider(
    posix_harness: PosixHarness, variable: str
) -> None:
    uv_bin = posix_harness.root / "uv bin"
    posix_harness.env[variable] = str(uv_bin)
    _write_executable(uv_bin / "aider", _posix_command("aider"))

    result = posix_harness.run_interactive("n\n" * 10)

    assert result.returncode == 0, result.stdout
    assert "Install Aider for fcc-aider?" in result.stdout
    assert "aider:--version" not in posix_harness.calls()


def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Free Claude Code is installed and verified." in result.stdout
    calls = posix_harness.calls()
    assert calls.index("claude-install") < calls.index("claude:--version")
    assert calls.index("codex-install:1") < calls.index("codex:--version")
    assert calls.index("pi-install") < calls.index("pi:--version")
    assert calls.index("opencode-install") < calls.index("opencode:--version")
    assert calls.index("npm:install -g cline") < calls.index("cline:--version")
    assert calls.index("hermes-install:--non-interactive --skip-setup") < calls.index(
        "hermes:--version"
    )
    assert calls.index("npm:install -g @deepseek-ai/dsh@latest") < calls.index(
        "dsh:--version"
    )
    assert calls.index("grok-install") < calls.index("grok:--version")
    assert calls.index("muse-install") < calls.index("muse:--version")
    assert calls.index("uv-install") < calls.index("uv:--version")
    aider_install = (
        "uv:tool install --force --python python3.12 --with pip aider-chat@latest"
    )
    assert calls.index("uv:--version") < calls.index("claude-install")
    assert calls.index(aider_install) < calls.index("aider:--version")
    assert any(
        call.startswith(
            "uv:tool install --force --refresh-package free-claude-code "
            "--python 3.14.7 free-claude-code"
        )
        for call in calls
    )
    assert not any(call.startswith("git:") for call in calls)
    assert calls[-3:] == [
        "uv:tool update-shell",
        "uv:tool dir --bin",
        "fcc-server:--version",
    ]
    assert not any("hermes:setup" in call for call in calls)
    home = Path(posix_harness.env["HOME"])
    assert (home / ".grok" / "bin" / "grok").is_file()
    assert not (home / ".local" / "bin" / "grok").exists()


def test_install_sh_discovers_grok_in_custom_bin_directory(
    posix_harness: PosixHarness,
) -> None:
    custom_grok_bin = posix_harness.root / "custom-grok-bin"
    posix_harness.env["GROK_BIN_DIR"] = str(custom_grok_bin)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert (custom_grok_bin / "grok").is_file()
    assert not (Path(posix_harness.env["HOME"]) / ".grok" / "bin" / "grok").exists()
    calls = posix_harness.calls()
    assert calls.index("grok-install") < calls.index("grok:--version")


def test_install_sh_installs_selected_hermes_without_setup(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\nn\nn\nn\n")

    assert result.returncode == 0, result.stdout
    calls = posix_harness.calls()
    assert "download:https://hermes-agent.nousresearch.com/install.sh" in calls
    assert "hermes-install:--non-interactive --skip-setup" in calls
    assert calls.index("hermes-install:--non-interactive --skip-setup") < calls.index(
        "hermes:--version"
    )
    assert "Run Hermes Agent with: fcc-hermes" in result.stdout
    assert not any("hermes:setup" in call for call in calls)
    assert not any(call.startswith("rtk:init") for call in calls)


@pytest.mark.parametrize("failure", ["hermes-download", "hermes-install"])
def test_install_sh_stops_when_selected_hermes_install_fails(
    posix_harness: PosixHarness,
    failure: str,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive(
        "n\nn\nn\nn\nn\ny\nn\nn\nn\nn\nn\n", fail_step=failure
    )

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    _assert_uv_ready_without_fcc_install(posix_harness.calls())


def test_install_sh_rejects_unsupported_hermes_platform_before_download(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    posix_harness.env["FAKE_UNAME"] = "Darwin"
    posix_harness.env["FAKE_UNAME_MACHINE"] = "x86_64"

    result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\nn\nn\nn\n")

    assert result.returncode != 0
    assert "does not provide a supported release for Darwin x86_64" in result.stdout
    assert not any(
        "hermes-agent.nousresearch.com" in call for call in posix_harness.calls()
    )


@pytest.mark.parametrize(
    ("client", "install_call"),
    [
        ("cline", "npm:install -g cline"),
        ("hermes", "hermes-install:--non-interactive --skip-setup"),
        ("grok", "grok-install"),
        ("muse", "muse-install"),
        (
            "aider",
            "uv:tool install --force --python python3.12 --with pip aider-chat@latest",
        ),
    ],
)
def test_install_sh_preserves_upstream_managed_harness_without_parsing_version(
    posix_harness: PosixHarness,
    client: str,
    install_call: str,
) -> None:
    _write_executable(
        posix_harness.bin_dir / client,
        _posix_command(client, version_output="opaque upstream version output"),
    )

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    calls = posix_harness.calls()
    assert f"{client}:--version" in calls
    assert install_call not in calls


@pytest.mark.parametrize("failure", ["grok-download", "grok-install"])
def test_install_sh_stops_when_grok_install_fails(
    posix_harness: PosixHarness,
    failure: str,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive(
        "n\nn\nn\nn\nn\nn\nn\ny\nn\nn\nn\n", fail_step=failure
    )

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    _assert_uv_ready_without_fcc_install(posix_harness.calls())


@pytest.mark.parametrize("failure", ["muse-download", "muse-install"])
def test_install_sh_stops_when_muse_install_fails(
    posix_harness: PosixHarness,
    failure: str,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive(
        "n\nn\nn\nn\nn\nn\nn\nn\ny\nn\nn\n", fail_step=failure
    )

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    _assert_uv_ready_without_fcc_install(posix_harness.calls())


def test_install_sh_stops_when_aider_install_fails(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive(
        "n\nn\nn\nn\nn\nn\nn\nn\nn\ny\nn\n", fail_step="aider-install"
    )

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    calls = posix_harness.calls()
    aider_install = (
        "uv:tool install --force --python python3.12 --with pip aider-chat@latest"
    )
    assert calls.index("uv:--version") < calls.index(aider_install)
    assert not any("aider.chat/install" in call for call in calls)
    assert not any("--refresh-package free-claude-code" in call for call in calls)


def test_install_sh_accepts_aider_as_the_only_selected_agent(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\nn\nn\nn\ny\nn\n")

    assert result.returncode == 0, result.stdout
    calls = posix_harness.calls()
    aider_install = (
        "uv:tool install --force --python python3.12 --with pip aider-chat@latest"
    )
    assert calls.index("uv:--version") < calls.index(aider_install)
    assert calls.index(aider_install) < calls.index("aider:--version")
    assert not any("aider.chat/install" in call for call in calls)
    assert "Run Aider with: fcc-aider" in result.stdout
    assert "Select at least one coding agent." not in result.stdout


def test_install_sh_discovers_aider_in_custom_uv_tool_bin(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    custom_tool_bin = posix_harness.root / "custom-tool-bin"
    posix_harness.env["UV_TOOL_BIN_DIR"] = str(custom_tool_bin)

    result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\nn\nn\nn\ny\nn\n")

    assert result.returncode == 0, result.stderr
    assert (custom_tool_bin / "aider").is_file()
    calls = posix_harness.calls()
    assert "uv:tool dir --bin" in calls
    assert "aider:--version" in calls


@pytest.mark.parametrize("fail_step", ("", "aider-verify"), ids=("valid", "broken"))
def test_install_sh_checks_existing_aider_in_custom_uv_tool_bin_before_installing(
    posix_harness: PosixHarness,
    fail_step: str,
) -> None:
    custom_tool_bin = posix_harness.root / "custom-tool-bin"
    existing_aider = custom_tool_bin / "aider"
    posix_harness.env["UV_TOOL_BIN_DIR"] = str(custom_tool_bin)
    _write_executable(
        existing_aider,
        _posix_command("aider", version_output="existing aider 1.0.0"),
    )
    original = existing_aider.read_bytes()

    result = posix_harness.run_interactive("n\n" * 9, fail_step=fail_step)

    if fail_step:
        assert result.returncode != 0
    else:
        assert result.returncode == 0, result.stderr
    calls = posix_harness.calls()
    assert "for fcc-aider?" not in result.stdout
    assert "aider:--version" in calls
    assert not any("aider-chat@latest" in call for call in calls)
    assert existing_aider.read_bytes() == original


def test_install_sh_rejects_broken_existing_aider_without_replacing_it(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("aider")

    result = posix_harness.run(fail_step="aider-verify")

    assert result.returncode != 0
    calls = posix_harness.calls()
    assert "aider:--version" in calls
    assert not any("aider-chat@latest" in call for call in calls)
    assert not any("aider.chat" in call for call in calls)


def test_install_sh_installs_latest_selected_dsh(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\ny\nn\nn\nn\nn\n")

    assert result.returncode == 0, result.stdout
    calls = posix_harness.calls()
    assert "npm:install -g @deepseek-ai/dsh@latest" in calls
    assert calls.index("npm:install -g @deepseek-ai/dsh@latest") < calls.index(
        "dsh:--version"
    )
    assert "Run DeepSeek Harness with: fcc-dsh" in result.stdout
    assert not any(call.startswith("rtk:init") for call in calls)


@pytest.mark.parametrize("interactive", (False, True))
def test_install_sh_upgrades_older_dsh_to_latest(
    posix_harness: PosixHarness,
    interactive: bool,
) -> None:
    _write_executable(
        posix_harness.bin_dir / "dsh",
        _posix_command("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),
    )

    result = (
        posix_harness.run_interactive("n\n" * 9) if interactive else posix_harness.run()
    )

    assert result.returncode == 0, result.stdout + result.stderr
    assert "requires >=0.2.0-rc.2" in result.stdout
    assert "npm:install -g @deepseek-ai/dsh@latest" in posix_harness.calls()


def test_install_sh_rejects_exact_dsh_on_unsupported_node(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("dsh")
    posix_harness.add_client("pi")
    _write_executable(
        posix_harness.bin_dir / "node",
        _posix_command("node").replace("node 22.19.0", "node 23.9.0"),
    )

    result = posix_harness.run()

    assert result.returncode != 0
    assert "requires Node.js ^22.19.0 or >=24.0.0" in result.stderr
    assert not any(
        call.startswith(("uv:", "download:", "npm:install"))
        for call in posix_harness.calls()
    )
    assert re.search(r"failed.*Preflight", result.stdout, re.IGNORECASE)


@pytest.mark.parametrize("node_version", ["22.18.0", "23.9.0", "not-a-version"])
def test_install_sh_rejects_incompatible_node_for_selected_dsh(
    posix_harness: PosixHarness,
    node_version: str,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    _write_executable(
        posix_harness.bin_dir / "node",
        _posix_command("node").replace("node 22.19.0", f"node {node_version}"),
    )

    result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\ny\nn\nn\nn\nn\n")

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    assert not any(
        call.startswith(("uv:", "download:", "npm:install"))
        for call in posix_harness.calls()
    )
    assert re.search(r"failed.*Preflight", result.stdout, re.IGNORECASE)


def test_install_sh_noninteractive_skips_dsh_without_node(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "node").unlink()
    (posix_harness.bin_dir / "npm").unlink()

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Run DeepSeek Harness with: fcc-dsh" not in result.stdout
    assert not any("@deepseek-ai/dsh" in call for call in posix_harness.calls())


def test_install_sh_stops_when_selected_dsh_install_fails(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive(
        "n\nn\nn\nn\nn\nn\ny\nn\nn\nn\nn\n", fail_step="dsh-install"
    )

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    _assert_uv_ready_without_fcc_install(posix_harness.calls())


def test_install_sh_installs_and_configures_rtk_for_selected_agents(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run("--rtk-headroom")

    assert result.returncode == 0, result.stderr
    calls = posix_harness.calls()
    assert (
        "download:https://github.com/rtk-ai/rtk/releases/download/v0.44.2/rtk-x86_64-unknown-linux-musl.tar.gz"
        in calls
    )
    assert any(call.startswith("sha256sum:") for call in calls)
    assert calls.index("rtk:--version:telemetry=1") > next(
        index for index, call in enumerate(calls) if call.startswith("sha256sum:")
    )
    assert calls.index("rtk:--version:telemetry=1") < calls.index(
        "rtk:gain:telemetry=1"
    )
    assert [call for call in calls if call.startswith("rtk:init")] == [
        "rtk:init --global --auto-patch:telemetry=1",
        "rtk:init --global --codex:telemetry=1",
        "rtk:init --global --agent pi:telemetry=1",
    ]
    assert calls.index("uv:--version") < calls.index(
        "rtk:init --global --agent pi:telemetry=1"
    )
    assert (Path(posix_harness.env["HOME"]) / ".claude").is_dir()


def test_install_sh_prepares_custom_claude_config_directory_for_rtk(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_rtk()
    custom_config = posix_harness.root / "custom-claude"
    posix_harness.env["CLAUDE_CONFIG_DIR"] = str(custom_config)

    result = posix_harness.run("--rtk-headroom")

    assert result.returncode == 0, result.stderr
    assert custom_config.is_dir()
    assert not (Path(posix_harness.env["HOME"]) / ".claude").exists()


@pytest.mark.parametrize(
    ("system", "machine", "asset"),
    [
        ("Linux", "x86_64", "rtk-x86_64-unknown-linux-musl.tar.gz"),
        ("Linux", "aarch64", "rtk-aarch64-unknown-linux-gnu.tar.gz"),
        ("Darwin", "x86_64", "rtk-x86_64-apple-darwin.tar.gz"),
        ("Darwin", "arm64", "rtk-aarch64-apple-darwin.tar.gz"),
    ],
)
def test_install_sh_selects_pinned_rtk_release_for_platform(
    posix_harness: PosixHarness,
    system: str,
    machine: str,
    asset: str,
) -> None:
    posix_harness.env["FAKE_UNAME"] = system
    posix_harness.env["FAKE_UNAME_MACHINE"] = machine

    result = posix_harness.run("--rtk-headroom", "--dry-run")

    assert result.returncode == 0, result.stderr
    assert f"rtk-ai/rtk/releases/download/v0.44.2/{asset}" in result.stdout
    assert "raw.githubusercontent.com/rtk-ai/rtk" not in result.stdout


def test_install_sh_rejects_unsupported_rtk_platform(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("muse")
    posix_harness.env["FAKE_UNAME"] = "FreeBSD"
    posix_harness.env["FAKE_UNAME_MACHINE"] = "riscv64"

    result = posix_harness.run("--rtk-headroom", "--dry-run")

    assert result.returncode != 0
    assert "does not provide a release for FreeBSD riscv64" in result.stderr


def test_install_sh_preserves_existing_rtk_and_configures_only_selected_agent(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    posix_harness.add_rtk()

    result = posix_harness.run_interactive("n\ny\nn\nn\nn\nn\nn\nn\nn\nn\ny\n")

    assert result.returncode == 0, result.stdout
    assert "verifying it without updating it" in result.stdout
    assert not any("rtk-ai/rtk" in call for call in posix_harness.calls())
    assert [call for call in posix_harness.calls() if call.startswith("rtk:init")] == [
        "rtk:init --global --codex:telemetry=1"
    ]


def test_install_sh_rejects_conflicting_rtk_command(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_unrelated_rtk()

    result = posix_harness.run("--rtk-headroom")

    assert result.returncode != 0
    assert "not a compatible Rust Token Killer installation" in result.stderr
    assert not any("rtk-ai/rtk" in call for call in posix_harness.calls())
    assert "fcc-server:--version" in posix_harness.calls()
    assert re.search(r"failed.*RTK configuration", result.stdout, re.IGNORECASE)


@pytest.mark.parametrize(
    "failure",
    [
        "rtk-download",
        "rtk-checksum",
        "rtk-install",
        "rtk-verify",
        "rtk-init-claude",
    ],
)
def test_install_sh_stops_when_rtk_setup_fails(
    posix_harness: PosixHarness,
    failure: str,
) -> None:
    result = posix_harness.run("--rtk-headroom", fail_step=failure)

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." in result.stdout
    assert "fcc-server:--version" in posix_harness.calls()
    assert re.search(r"failed.*RTK configuration", result.stdout, re.IGNORECASE)


def test_install_sh_installs_then_updates_only_selected_agent(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive("\n" * 11 + "y\n" + "\n" * 9)

    assert result.returncode == 0, result.stdout
    assert "Select at least one coding agent." in result.stdout
    assert "Run Codex with: fcc-codex" in result.stdout
    assert "Run Claude Code with: fcc-claude" not in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    assert "Run OpenCode with: fcc-opencode" not in result.stdout
    assert "Run Cline with: fcc-cline" not in result.stdout
    calls = posix_harness.calls()
    assert "codex-install:1" in calls
    assert not any(
        f"{command}:--version" in calls
        for command in CODING_AGENTS
        if command != "codex"
    )
    assert not any("rtk-ai/rtk" in call for call in calls)
    assert "[Y/n]" not in result.stdout

    update = posix_harness.run_interactive("\n" * 10)

    assert update.returncode == 0, update.stdout
    assert "for fcc-codex?" not in update.stdout
    update_calls = posix_harness.calls()[len(calls) :]
    assert "codex:--version" in update_calls
    assert not any(call.startswith("download:") for call in update_calls)
    assert any("--refresh-package free-claude-code" in call for call in update_calls)


def test_install_sh_rejects_uninstalled_only_selection(
    posix_harness: PosixHarness,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run_interactive(
        "n\nn\ny\nn\nn\nn\nn\nn\nn\nn\nn\n", fail_step="pi-skip"
    )

    assert result.returncode != 0
    assert "No selected coding agent was installed." in result.stdout
    _assert_uv_ready_without_fcc_install(posix_harness.calls())


def test_install_sh_delegates_macos_bundle_to_installed_helper(posix_harness):
    posix_harness.env["FAKE_UNAME"] = "Darwin"
    posix_harness.env["FAKE_TOOL_BIN"] = str(posix_harness.root / "tool's bin")
    result = posix_harness.run()
    assert result.returncode == 0, result.stderr
    calls = posix_harness.calls()
    assert calls.count("fcc-desktop:--install-macos-app") == 1
    assert calls.index("fcc-server:--version") < calls.index(
        "fcc-desktop:--install-macos-app"
    )
    install = next(
        call for call in calls if "--refresh-package free-claude-code" in call
    )
    assert "--managed-python" in install and "+gil" in install


@pytest.mark.parametrize(
    "system,preference", [("Darwin", "unset"), ("Linux", "system")]
)
def test_install_sh_macos_python_selection_overrides_only_its_preference(
    posix_harness, system, preference
):
    posix_harness.env["FAKE_UNAME"] = system
    posix_harness.env["UV_PYTHON_PREFERENCE"] = "system"
    _write_executable(
        posix_harness.bin_dir / "uv",
        _posix_uv_command("0.13.4").replace(
            "#!/bin/sh\n",
            f'#!/bin/sh\n[ "${{UV_PYTHON_PREFERENCE-unset}}" = "{preference}" ] || exit 83\n',
            1,
        ),
    )
    result = posix_harness.run_functions("install_free_claude_code")
    assert result.returncode == 0, result.stderr
    install = next(
        call
        for call in posix_harness.calls()
        if "--refresh-package free-claude-code" in call
    )
    assert ("--managed-python" in install) == (system == "Darwin")
    assert ("+gil" in install) == (system == "Darwin")


@pytest.mark.parametrize("system,dry_run", [("Darwin", True), ("Linux", False)])
def test_install_sh_macos_helper_dry_run_and_platform_scope(
    posix_harness, system, dry_run
):
    posix_harness.env["FAKE_UNAME"] = system
    result = posix_harness.run_functions(
        f"dry_run={int(dry_run)}\ninstall_macos_desktop_app"
    )
    assert result.returncode == 0, result.stderr
    assert not any(call.startswith("fcc-desktop:") for call in posix_harness.calls())
    assert ("--install-macos-app" in result.stdout) == dry_run
    assert not (posix_harness.root / "home/Applications").exists()


def test_install_sh_stops_if_macos_bundle_setup_fails(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FAKE_UNAME"] = "Darwin"

    result = posix_harness.run(fail_step="macos-app-setup")

    assert result.returncode != 0
    assert "Command failed with exit code 37" in result.stderr
    assert "Free Claude Code is installed and verified." in result.stdout
    assert "Start the proxy with: fcc-server" in result.stdout
    assert "Open Free Claude Code from Applications" not in result.stdout
    assert not (
        posix_harness.root / "home" / "Desktop" / "Free Claude Code.app"
    ).exists()


@pytest.mark.parametrize("uv_version", ("0.13.4", "0.13.4+build.1", "0.13.5"))
def test_install_sh_preserves_compatible_uv(
    posix_harness: PosixHarness, uv_version: str
) -> None:
    posix_harness.add_uv(uv_version)
    executable = posix_harness.bin_dir / "uv"
    original = executable.read_bytes()

    result = posix_harness.run_functions("ensure_uv")

    assert result.returncode == 0, result.stderr
    assert not any(call.startswith("download:") for call in posix_harness.calls())
    assert "uv-install" not in posix_harness.calls()
    assert executable.read_bytes() == original
    assert "leaving it unchanged" in result.stdout


@pytest.mark.parametrize("interactive", (False, True))
def test_install_sh_replaces_unrelated_pi_command(
    posix_harness: PosixHarness,
    interactive: bool,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_unrelated_pi()
    posix_harness.add_uv("0.13.4")

    result = (
        posix_harness.run_interactive("y\n" + "n\n" * 7)
        if interactive
        else posix_harness.run()
    )

    assert result.returncode == 0, result.stdout + result.stderr
    assert "is not Pi Coding Agent; installing Pi" in result.stdout
    assert "pi-install" in posix_harness.calls()
    assert "pi:--version" in posix_harness.calls()


def test_install_sh_discovers_custom_pi_npm_prefix(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_npm_prefix(posix_harness.root / "custom-npm")
    posix_harness.add_uv("0.13.4")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    calls = posix_harness.calls()
    assert "npm:prefix -g" in calls
    assert "pi:--help" in calls
    assert "pi:--version" in calls


def test_install_sh_continues_when_pi_is_not_installed(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "pi-install" in calls
    assert not any(call.startswith("pi:") for call in calls)
    assert "uv-install" in calls
    assert "fcc-server:--version" in calls


def test_install_sh_continues_when_unrelated_pi_is_unchanged(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_unrelated_pi()

    result = posix_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "unrelated-pi:--help" in calls
    assert "unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


def test_install_sh_continues_when_pi_resolution_changes_to_unrelated_command(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_unrelated_pi()
    npm_prefix = posix_harness.root / "custom-npm"
    posix_harness.add_npm_prefix(npm_prefix)
    _write_executable(
        npm_prefix / "bin" / "pi",
        _posix_command("other-unrelated-pi"),
    )

    result = posix_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = posix_harness.calls()
    assert "other-unrelated-pi:--help" in calls
    assert "other-unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


@pytest.mark.parametrize(
    "uv_version", ("0.5.9", "0.11.16", "0.12.9", "0.12.12", "0.12.13", "0.13.3")
)
def test_install_sh_replaces_obsolete_uv(
    posix_harness: PosixHarness,
    uv_version: str,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv(uv_version)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "uv-install" in posix_harness.calls()
    assert f"uv {uv_version} does not satisfy stable >=0.13.4" in result.stdout


def test_install_sh_prioritizes_replacement_uv_over_obsolete_cargo_uv(
    posix_harness: PosixHarness,
) -> None:
    home = Path(posix_harness.env["HOME"])
    cargo_bin = home / ".cargo" / "bin"
    local_bin = home / ".local" / "bin"
    _write_executable(cargo_bin / "uv", _posix_uv_command("0.5.9"))
    local_bin.mkdir(parents=True)
    posix_harness.env["PATH"] = f"{cargo_bin}:{local_bin}:{posix_harness.env['PATH']}"

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Verified uv 0.13.4." in result.stdout
    assert "uv-install" in posix_harness.calls()


@pytest.mark.parametrize("install_variable", ("UV_INSTALL_DIR", "UV_UNMANAGED_INSTALL"))
def test_install_sh_prioritizes_forced_cargo_home_uv_install_layout(
    posix_harness: PosixHarness,
    install_variable: str,
) -> None:
    home = Path(posix_harness.env["HOME"])
    cargo_home = home / ".cargo"
    cargo_bin = cargo_home / "bin"
    posix_harness.env["CARGO_HOME"] = str(cargo_home)
    posix_harness.env[install_variable] = str(cargo_home)
    posix_harness.env["PATH"] = f"{posix_harness.env['PATH']}:{cargo_bin}"
    posix_harness.add_uv("0.5.9")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Verified uv 0.13.4." in result.stdout
    assert "uv-install" in posix_harness.calls()


def test_install_sh_uv_install_dir_takes_precedence_over_unmanaged_install(
    posix_harness: PosixHarness,
) -> None:
    install_bin = posix_harness.root / "uv-install-bin"
    unmanaged_bin = posix_harness.root / "unmanaged-uv-bin"
    posix_harness.env["UV_INSTALL_DIR"] = str(install_bin)
    posix_harness.env["UV_UNMANAGED_INSTALL"] = str(unmanaged_bin)
    posix_harness.add_uv("0.5.9")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert (install_bin / "uv").is_file()
    assert not (unmanaged_bin / "uv").exists()


def test_install_sh_prioritizes_replacement_uv_from_unmanaged_install_directory(
    posix_harness: PosixHarness,
) -> None:
    unmanaged_bin = posix_harness.root / "unmanaged-uv-bin"
    posix_harness.env["UV_UNMANAGED_INSTALL"] = str(unmanaged_bin)
    posix_harness.add_uv("0.5.9")

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Verified uv 0.13.4." in result.stdout
    assert "uv-install" in posix_harness.calls()


@pytest.mark.parametrize("cargo_layout", (False, True), ids=("default", "cargo-home"))
def test_install_sh_infers_home_for_replacement_uv(
    posix_harness: PosixHarness,
    cargo_layout: bool,
) -> None:
    (posix_harness.bin_dir / "opencode").unlink()
    inferred_home = Path(posix_harness.env["FAKE_INFERRED_HOME"])
    posix_harness.env.pop("HOME")
    if cargo_layout:
        posix_harness.env["UV_INSTALL_DIR"] = str(inferred_home / ".cargo")

    result = posix_harness.run_interactive("n\nn\nn\nn\nn\nn\nn\nn\nn\ny\nn\n")

    assert result.returncode == 0, result.stderr
    relative_uv = Path(".cargo/bin/uv") if cargo_layout else Path(".local/bin/uv")
    assert (inferred_home / relative_uv).is_file()
    assert "Verified uv 0.13.4." in result.stdout


@pytest.mark.parametrize("version", ("0.13.4-alpha.1", "0.14.0-rc.1"))
def test_install_sh_replaces_prerelease_uv(
    posix_harness: PosixHarness,
    version: str,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv(version)

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr
    assert f"uv {version} does not satisfy stable >=0.13.4" in result.stdout
    assert "uv-install" in posix_harness.calls()


@pytest.mark.parametrize(
    "failure",
    [
        "claude-download",
        "claude-install",
        "claude-verify",
        "codex-download",
        "codex-install",
        "codex-verify",
        "pi-download",
        "pi-install",
        "pi-verify",
        "opencode-download",
        "opencode-install",
        "opencode-verify",
        "cline-install",
        "cline-verify",
        "uv-download",
        "uv-install",
        "uv-verify",
        "fcc-install",
        "path-update",
        "fcc-missing",
        "fcc-verify",
    ],
)
def test_install_sh_stops_without_success_on_each_failure(
    posix_harness: PosixHarness,
    failure: str,
) -> None:
    if failure.startswith("opencode-"):
        (posix_harness.bin_dir / "opencode").unlink()
    result = posix_harness.run(fail_step=failure)

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    calls = posix_harness.calls()
    if failure == "path-update":
        failure_index = calls.index("uv:tool update-shell")
        assert "uv:tool dir --bin" not in calls[failure_index + 1 :]

    forbidden = {
        "claude-download": "claude-install",
        "claude-install": "claude:--version",
        "claude-verify": "chatgpt.com",
        "codex-download": "codex-install",
        "codex-install": "codex:--version",
        "codex-verify": "pi.dev",
        "pi-download": "pi-install",
        "pi-install": "pi:--version",
        "pi-verify": "opencode:--version",
        "opencode-download": "opencode-install",
        "opencode-install": "opencode:--version",
        "opencode-verify": "npm:install -g cline",
        "cline-install": "cline:--version",
        "cline-verify": "hermes-agent.nousresearch.com",
        "uv-download": "uv-install",
        "uv-install": "uv:--version",
        "uv-verify": "uv:tool install",
        "fcc-install": "uv:tool update-shell",
        "fcc-missing": "fcc-server:--version",
    }.get(failure)
    if failure == "pi-verify":
        # OpenCode is probed during preflight. No later phase may run after Pi fails.
        pi_index = max(
            index for index, call in enumerate(calls) if call.startswith("pi:")
        )
        calls = calls[pi_index + 1 :]
    if forbidden is not None:
        assert not any(forbidden in call for call in calls)


def test_install_sh_dry_run_never_executes_commands(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run("--dry-run")

    assert result.returncode == 0, result.stderr
    assert posix_harness.calls() == []
    assert "Dry run complete. No changes were made." in result.stdout
    assert "Free Claude Code is installed and verified." not in result.stdout


def test_install_sh_rejects_broken_existing_client_without_replacing_it(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")

    result = posix_harness.run(fail_step="claude-verify")

    assert result.returncode != 0
    calls = posix_harness.calls()
    _assert_uv_ready_without_fcc_install(calls)
    assert not any("claude.ai" in call for call in calls)


def test_install_sh_rejects_unparseable_existing_uv(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv("not-a-version")

    result = posix_harness.run()

    assert result.returncode != 0
    assert not any("astral.sh" in call for call in posix_harness.calls())


@pytest.mark.parametrize(
    ("args", "package"),
    [
        ((), "free-claude-code"),
        (("--voice-local",), "free-claude-code[voice_local]"),
        (
            ("--voice-local", "--torch-backend", "cu130"),
            "free-claude-code[voice_local]",
        ),
    ],
)
def test_install_sh_voice_flags_only_change_fcc_spec(
    posix_harness: PosixHarness,
    args: tuple[str, ...],
    package: str,
) -> None:
    result = posix_harness.run(*args)

    assert result.returncode == 0, result.stderr
    install_calls = [
        call
        for call in posix_harness.calls()
        if "tool install" in call and "--refresh-package free-claude-code" in call
    ]
    assert len(install_calls) == 1
    assert package in install_calls[0]
    assert ("--torch-backend cu130" in install_calls[0]) == ("cu130" in args)


@pytest.mark.parametrize("flag", ("--voice-nim", "--voice-all"))
def test_install_sh_rejects_retired_voice_flags_before_mutation(
    posix_harness: PosixHarness,
    flag: str,
) -> None:
    result = posix_harness.run(flag)

    assert result.returncode != 0
    assert posix_harness.calls() == []


def test_install_sh_rejects_invalid_options_before_mutation(
    posix_harness: PosixHarness,
) -> None:
    result = posix_harness.run("--torch-backend", "cu130")

    assert result.returncode != 0
    assert posix_harness.calls() == []


@pytest.mark.parametrize("command_name", FCC_COMMANDS)
def test_install_sh_rejects_running_fcc_before_mutation(
    posix_harness: PosixHarness,
    command_name: str,
) -> None:
    posix_harness.env["FCC_RUNNING_COMMAND"] = command_name

    result = posix_harness.run()

    assert result.returncode != 0
    assert posix_harness.calls() == []
    assert f"{command_name} (PID 4242)" in result.stderr


def test_install_sh_rechecks_for_fcc_process_before_tool_replacement(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.add_client("claude")
    posix_harness.add_client("codex")
    posix_harness.add_client("pi")
    posix_harness.add_uv("0.13.4")
    posix_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server"
    posix_harness.env["FCC_RUNNING_PHASE"] = "late"

    result = posix_harness.run()

    assert result.returncode != 0
    assert "fcc-server (PID 4242)" in result.stderr
    assert not any(
        "--refresh-package free-claude-code" in call for call in posix_harness.calls()
    )


def test_install_sh_ignores_similarly_named_process(
    posix_harness: PosixHarness,
) -> None:
    posix_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server-helper"

    result = posix_harness.run()

    assert result.returncode == 0, result.stderr


@pytest.mark.parametrize(
    ("command_name", "process_args"),
    (
        ("free-claude-code", "/home/user/.local/bin/free-claude-code"),
        ("fcc-server", "/usr/bin/python3 /home/user/.local/bin/fcc-server"),
    ),
)
def test_install_sh_process_fallback_reads_full_command_line(
    posix_harness: PosixHarness,
    command_name: str,
    process_args: str,
) -> None:
    posix_harness.use_process_list_fallback(f"4242 {process_args}")

    result = posix_harness.run()

    assert result.returncode != 0
    assert posix_harness.calls() == []
    assert f"{command_name} (PID 4242)" in result.stderr


def _powershells() -> tuple[str, ...]:
    candidates = (shutil.which("pwsh"), shutil.which("powershell"))
    return tuple(dict.fromkeys(path for path in candidates if path is not None))


def test_install_ps1_gui_icon_export_completes_before_returning(
    powershell_harness: PowerShellHarness,
) -> None:
    desktop_command = powershell_harness.root / "icon-exporter.exe"
    shutil.copy2(Path(sys.executable).with_name("fcc-desktop.exe"), desktop_command)
    destination = (
        powershell_harness.root / "profile with spaces" / ".fcc" / "app-icon.ico"
    )
    powershell_harness.env.update(
        FCC_TEST_DESKTOP_COMMAND=str(desktop_command),
        FCC_TEST_ICON_PATH=str(destination),
    )
    completed = powershell_harness.run_functions(
        "Export-FccDesktopIcon -DesktopCommand $env:FCC_TEST_DESKTOP_COMMAND "
        "-IconPath $env:FCC_TEST_ICON_PATH"
    )
    assert completed.returncode == 0, completed.stderr
    assert (
        destination.read_bytes()
        == (_repo_root() / "src/free_claude_code/assets/app-icon.ico").read_bytes()
    )


def _create_windows_shortcut(
    powershell: str,
    shortcut_path: Path,
    target_path: Path,
) -> None:
    shortcut_path.parent.mkdir(parents=True, exist_ok=True)
    env = os.environ | {
        "FCC_TEST_SHORTCUT": str(shortcut_path),
        "FCC_TEST_TARGET": str(target_path),
    }
    subprocess.run(
        [
            powershell,
            "-NoProfile",
            "-Command",
            (
                "$shell = New-Object -ComObject WScript.Shell; "
                "$shortcut = $shell.CreateShortcut($env:FCC_TEST_SHORTCUT); "
                "$shortcut.TargetPath = $env:FCC_TEST_TARGET; "
                "$shortcut.Save()"
            ),
        ],
        check=True,
        capture_output=True,
        text=True,
        env=env,
    )


def _windows_shortcut_icon(
    powershell: str,
    shortcut_path: Path,
    env: dict[str, str],
) -> str:
    process_env = env | {"FCC_TEST_SHORTCUT": str(shortcut_path)}
    completed = subprocess.run(
        [
            powershell,
            "-NoProfile",
            "-Command",
            (
                "$shell = New-Object -ComObject WScript.Shell; "
                "$shortcut = $shell.CreateShortcut($env:FCC_TEST_SHORTCUT); "
                "[Console]::Out.Write($shortcut.IconLocation)"
            ),
        ],
        check=True,
        capture_output=True,
        text=True,
        env=process_env,
    )
    return completed.stdout


def _batch_client(name: str, *, version_output: str | None = None) -> str:
    version = {
        "opencode": "v2.0.10",
        "cline": "3.0.55",
        "hermes": "0.20.4",
        "dsh": "0.2.0-rc.2",
        "grok": "1.0.5",
        "muse": "0.2.1",
        "node": "22.19.0",
    }.get(name, "1.0.0")
    if version_output is not None:
        version_command = f'if "%1"=="--version" echo {version_output}'
    elif name == "hermes":
        version_command = (
            f'if "%1"=="--version" echo Hermes Agent v{version} '
            "(2026.8.18) · upstream deadbeef\n"
            'if "%1"=="--version" echo Install directory: C:\\fake-hermes\n'
            'if "%1"=="--version" echo Install method: git\n'
            'if "%1"=="--version" echo Python: 3.12.11\n'
            'if "%1"=="--version" echo OpenAI SDK: 2.15.0\n'
            'if "%1"=="--version" echo Up to date'
        )
    elif name == "grok":
        version_command = (
            f'if "%1"=="--version" echo grok {version} (5115b46bc9) [stable]'
        )
    elif name == "muse":
        version_command = (
            f'if "%1"=="--version" echo Muse Code {version} ({version}-R1215.1)'
        )
    else:
        version_command = f'if "%1"=="--version" echo {name} {version}'
    help_output = (
        "echo   --extension, -e ^<path^>  Load an extension\n"
        "echo   --models ^<patterns^>     Scope models"
        if name == "pi"
        else "rem no product help"
    )
    return f"""@echo off
echo {name}:%*>>"%CALL_LOG%"
if "{name}"=="opencode" if "%FCC_RUNNING_PHASE%"=="opencode-plugin" (
    if exist "%FCC_PROCESS_MARKER%.probed" (
        type nul > "%FCC_PROCESS_MARKER%"
    ) else (
        type nul > "%FCC_PROCESS_MARKER%.probed"
    )
)
if "{name}"=="headroom" if "%FAIL_STEP%"=="headroom-check" exit /b 79
if "{name}"=="headroom" if "%FAIL_STEP%"=="headroom-configure" if "%4"=="codex" exit /b 80
if "%FAIL_STEP%"=="{name}-verify" exit /b 51
{version_command}
if "%1"=="--help" (
{help_output}
)
exit /b 0
"""


def _batch_npm() -> str:
    return r"""@echo off
echo npm:%*>>"%CALL_LOG%"
if "%1"=="install" if "%2"=="-g" if "%3"=="cline" goto install_cline
if "%1"=="install" if "%2"=="-g" if "%3"=="@deepseek-ai/dsh@latest" goto install_dsh
if "%1"=="prefix" if "%2"=="-g" echo %FAKE_NPM_PREFIX%& exit /b 0
if "%1"=="config" if "%2"=="get" if "%3"=="prefix" echo %FAKE_NPM_PREFIX%& exit /b 0
exit /b 71
:install_cline
if "%FAIL_STEP%"=="cline-install" exit /b 72
if not exist "%FAKE_NPM_PREFIX%" mkdir "%FAKE_NPM_PREFIX%"
copy /y "%FAKE_FIXTURES%\cline-command.cmd" "%FAKE_NPM_PREFIX%\cline.cmd" >nul
exit /b 0
:install_dsh
if "%FAIL_STEP%"=="dsh-install" exit /b 73
if not exist "%FAKE_NPM_PREFIX%" mkdir "%FAKE_NPM_PREFIX%"
copy /y "%FAKE_FIXTURES%\dsh-command.cmd" "%FAKE_NPM_PREFIX%\dsh.cmd" >nul
exit /b 0
"""


def _batch_uv(version: str) -> str:
    return rf"""@echo off
set "UV_BIN_DIR=%FAKE_TOOL_BIN%"
if defined UV_TOOL_BIN_DIR set "UV_BIN_DIR=%UV_TOOL_BIN_DIR%"
echo uv:%*>>"%CALL_LOG%"
if "%1"=="--version" goto version
if "%1"=="tool" if "%2"=="install" goto install
if "%1"=="tool" if "%2"=="update-shell" goto update_shell
if "%1"=="tool" if "%2"=="dir" if "%3"=="--bin" goto tool_bin
exit /b 59
:version
if "%FCC_RUNNING_PHASE%"=="late" type nul > "%FCC_PROCESS_MARKER%"
if "%FAIL_STEP%"=="uv-verify" exit /b 52
echo uv {version}
exit /b 0
:install
if "%5"=="python3.12" goto install_aider
if "%5"=="headroom-ai[mcp]==0.40.0" goto install_headroom
if "%5"=="headroom-ai[mcp]" goto install_headroom
if "%FAIL_STEP%"=="fcc-install" exit /b 53
if not exist "%UV_BIN_DIR%" mkdir "%UV_BIN_DIR%"
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-server.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-desktop.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-claude.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-pi.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-opencode.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-cline.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-hermes.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-dsh.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-grok.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-muse.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-aider.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-doctor.cmd" >nul
copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-update.cmd" >nul
if not "%FAIL_STEP%"=="fcc-missing" copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%UV_BIN_DIR%\fcc-codex.cmd" >nul
exit /b 0
:install_aider
if "%FAIL_STEP%"=="aider-install" exit /b 57
if not exist "%UV_BIN_DIR%" mkdir "%UV_BIN_DIR%"
copy /y "%FAKE_FIXTURES%\aider-command.cmd" "%UV_BIN_DIR%\aider.cmd" >nul
exit /b 0
:install_headroom
if "%FAIL_STEP%"=="headroom-install" exit /b 78
if not exist "%UV_BIN_DIR%" mkdir "%UV_BIN_DIR%"
copy /y "%FAKE_FIXTURES%\headroom-command.cmd" "%UV_BIN_DIR%\headroom.cmd" >nul
exit /b 0
:update_shell
if "%FAIL_STEP%"=="path-update" exit /b 54
exit /b 0
:tool_bin
echo %UV_BIN_DIR%
exit /b 0
"""


def _batch_rtk() -> str:
    return r"""@echo off
>>"%CALL_LOG%" echo rtk:%*:telemetry=%RTK_TELEMETRY_DISABLED%
if "%*"=="init --global --auto-patch" if defined CLAUDE_CONFIG_DIR if not exist "%CLAUDE_CONFIG_DIR%" exit /b 77
if "%*"=="init --global --auto-patch" if not defined CLAUDE_CONFIG_DIR if not exist "%USERPROFILE%\.claude" exit /b 77
if "%FAIL_STEP%"=="rtk-verify" if "%1"=="--version" exit /b 72
if "%FAIL_STEP%"=="rtk-verify" if "%1"=="gain" exit /b 72
if "%FAIL_STEP%"=="rtk-init-claude" if "%*"=="init --global --auto-patch" exit /b 73
if "%FAIL_STEP%"=="rtk-init-codex" if "%*"=="init --global --codex" exit /b 74
if "%FAIL_STEP%"=="rtk-init-pi" if "%*"=="init --global --agent pi" exit /b 75
if "%FAIL_STEP%"=="rtk-init-opencode" if "%*"=="init --global --opencode" exit /b 76
if "%1"=="--version" echo rtk 0.44.2
exit /b 0
"""


@dataclass
class PowerShellHarness:
    root: Path
    bin_dir: Path
    fixtures: Path
    tool_bin: Path
    log: Path
    env: dict[str, str]
    powershell: str
    wrapper: Path

    def add_client(self, name: str) -> None:
        _write_executable(self.bin_dir / f"{name}.cmd", _batch_client(name))

    def add_installed_clients(self, *, except_for: tuple[str, ...] = ()) -> None:
        for name in CODING_AGENTS:
            if name not in except_for:
                self.add_client(name)

    def add_unrelated_pi(self) -> None:
        _write_executable(self.bin_dir / "pi.cmd", _batch_client("unrelated-pi"))

    def add_npm_prefix(self, prefix: Path) -> None:
        prefix.mkdir(parents=True)
        self.env["FAKE_NPM_PREFIX"] = str(prefix)
        _write_executable(self.bin_dir / "npm.cmd", _batch_npm())

    def add_uv(self, version: str) -> None:
        _write_executable(self.bin_dir / "uv.cmd", _batch_uv(version))

    def add_rtk(self) -> None:
        _write_executable(self.bin_dir / "rtk.cmd", _batch_rtk())

    def add_unrelated_rtk(self) -> None:
        _write_executable(
            self.bin_dir / "rtk.cmd",
            r"""@echo off
echo unrelated-rtk:%*>>"%CALL_LOG%"
if "%1"=="--version" (
    echo rtk 1.0.0
    exit /b 0
)
exit /b 76
""",
        )

    def run(self, *args: str, fail_step: str = "") -> subprocess.CompletedProcess[str]:
        env = self.env | {"FAIL_STEP": fail_step}
        return subprocess.run(
            [
                self.powershell,
                "-NoProfile",
                "-ExecutionPolicy",
                "Bypass",
                "-File",
                str(self.wrapper),
                *args,
            ],
            check=False,
            capture_output=True,
            text=True,
            env=env,
        )

    def run_functions(
        self, body: str, *args: str, fail_step: str = ""
    ) -> subprocess.CompletedProcess[str]:
        """Exercise real installer functions without running the full workflow."""
        scenario = self.root / "scenario.ps1"
        scenario.write_text(
            body + '\nWrite-Output "Installer scenario completed."\n', encoding="utf-8"
        )
        self.env["FCC_INSTALLER_SCENARIO"] = str(scenario)
        try:
            return self.run(*args, fail_step=fail_step)
        finally:
            self.env["FCC_INSTALLER_SCENARIO"] = ""

    def run_interactive(
        self, answers: list[str], *args: str, fail_step: str = ""
    ) -> subprocess.CompletedProcess[str]:
        self.env["FCC_INSTALLER_ANSWERS"] = json.dumps({"answers": answers})
        return self.run(*args, fail_step=fail_step)

    def calls(self) -> list[str]:
        if not self.log.exists():
            return []
        return self.log.read_text(encoding="utf-8").splitlines()


@pytest.fixture(
    params=_powershells() or (None,),
    ids=lambda path: Path(path).name if path is not None else "unavailable",
)
def powershell_harness(
    tmp_path: Path,
    request: pytest.FixtureRequest,
    powershell_module_paths,
) -> PowerShellHarness:
    powershell = request.param
    if powershell is None or os.name != "nt":
        pytest.skip("PowerShell installer scenarios run on Windows hosts")

    bin_dir = tmp_path / "bin"
    fixtures = tmp_path / "fixtures"
    tool_bin = tmp_path / "tool-bin"
    home = tmp_path / "home"
    local_app_data = tmp_path / "local-app-data"
    app_data = tmp_path / "app-data"
    log = tmp_path / "calls.log"
    for path in (bin_dir, fixtures, tool_bin, home, local_app_data, app_data):
        path.mkdir(parents=True)

    (fixtures / "claude-command.cmd").write_text(
        _batch_client("claude"), encoding="utf-8"
    )
    (fixtures / "codex-command.cmd").write_text(
        _batch_client("codex"), encoding="utf-8"
    )
    (fixtures / "pi-command.cmd").write_text(_batch_client("pi"), encoding="utf-8")
    (fixtures / "opencode-command.cmd").write_text(
        _batch_client("opencode"), encoding="utf-8"
    )
    (fixtures / "cline-command.cmd").write_text(
        _batch_client("cline"), encoding="utf-8"
    )
    (fixtures / "hermes-command.cmd").write_text(
        _batch_client("hermes"), encoding="utf-8"
    )
    (fixtures / "dsh-command.cmd").write_text(_batch_client("dsh"), encoding="utf-8")
    (fixtures / "grok-command.cmd").write_text(_batch_client("grok"), encoding="utf-8")
    (fixtures / "muse-command.cmd").write_text(_batch_client("muse"), encoding="utf-8")
    (fixtures / "aider-command.cmd").write_text(
        _batch_client("aider"), encoding="utf-8"
    )
    (fixtures / "rtk-command.cmd").write_text(_batch_rtk(), encoding="utf-8")
    (fixtures / "uv-command.cmd").write_text(_batch_uv("0.13.4"), encoding="utf-8")
    (fixtures / "headroom-command.cmd").write_text(
        _batch_client("headroom"), encoding="utf-8"
    )
    (fixtures / "fcc-command.cmd").write_text(
        """@echo off
for %%I in ("%~f0") do set "FCC_NAME=%%~nI"
echo %FCC_NAME%:%*>>"%CALL_LOG%"
if "%FAIL_STEP%"=="fcc-verify" exit /b 55
if "%FCC_NAME%"=="fcc-desktop" if "%1"=="--export-icon" if "%FAIL_STEP%"=="desktop-icon-export" exit /b 56
if "%FCC_NAME%"=="fcc-desktop" if "%1"=="--export-icon" (
    if not exist "%~dp2" mkdir "%~dp2"
    echo fake icon>"%~2"
)
if "%FCC_NAME%"=="fcc-server" if "%1"=="--version" echo free-claude-code 3.5.18
exit /b 0
""",
        encoding="utf-8",
    )
    (fixtures / "claude-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "claude-install") { exit 61 }
$bin = Join-Path $env:USERPROFILE ".local\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "claude-command.cmd") (Join-Path $bin "claude.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "claude-install"
""",
        encoding="utf-8",
    )
    (fixtures / "codex-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "codex-install") { exit 62 }
$bin = Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "codex-command.cmd") (Join-Path $bin "codex.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "codex-install:$env:CODEX_NON_INTERACTIVE"
""",
        encoding="utf-8",
    )
    (fixtures / "pi-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "pi-install") { exit 64 }
if ($env:FAIL_STEP -eq "pi-skip") {
    Add-Content -LiteralPath $env:CALL_LOG -Value "pi-install"
    return
}
$bin = if ($env:FAKE_NPM_PREFIX) { $env:FAKE_NPM_PREFIX } else { Join-Path $env:APPDATA "npm" }
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "pi-command.cmd") (Join-Path $bin "pi.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "pi-install"
""",
        encoding="utf-8",
    )
    (fixtures / "hermes-installer.ps1").write_text(
        r"""[CmdletBinding(PositionalBinding=$false)]
param(
    [switch] $NonInteractive
)
if ($env:FAIL_STEP -eq "hermes-install") { exit 65 }
$bin = Join-Path $env:LOCALAPPDATA "hermes\hermes-agent\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "hermes-command.cmd") (Join-Path $bin "hermes.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "hermes-install:${NonInteractive}"
""",
        encoding="utf-8",
    )
    (fixtures / "grok-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "grok-install") { exit 66 }
$bin = if ($env:GROK_BIN_DIR) { $env:GROK_BIN_DIR } else { Join-Path $env:USERPROFILE ".grok\bin" }
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "grok-command.cmd") (Join-Path $bin "grok.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "grok-install"
""",
        encoding="utf-8",
    )
    (fixtures / "muse-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "muse-install") { exit 68 }
$originalPath = $env:Path
if ($env:FCC_TEST_USER_PATH) {
    $env:Path = "$originalPath$([IO.Path]::PathSeparator)$env:FCC_TEST_USER_PATH"
}
$existing = Get-Command "muse" -CommandType Application -ErrorAction SilentlyContinue
$env:Path = $originalPath
if ($existing) {
    Add-Content -LiteralPath $env:CALL_LOG -Value "muse-install:external"
    return
}
$bin = Join-Path $env:LOCALAPPDATA "Programs\Muse Code\bin"
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "muse-command.cmd") (Join-Path $bin "muse.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "muse-install"
""",
        encoding="utf-8",
    )
    (fixtures / "uv-installer.ps1").write_text(
        r"""if ($env:FAIL_STEP -eq "uv-install") { exit 63 }
$forceInstallDir = if ($env:UV_INSTALL_DIR) {
    $env:UV_INSTALL_DIR
}
elseif ($env:UV_UNMANAGED_INSTALL) {
    $env:UV_UNMANAGED_INSTALL
}
else {
    $null
}
$bin = if ($forceInstallDir) {
    if ($forceInstallDir -eq $(if ($env:CARGO_HOME) { $env:CARGO_HOME } else { Join-Path $env:USERPROFILE ".cargo" })) {
        Join-Path $forceInstallDir "bin"
    }
    else {
        $forceInstallDir
    }
}
elseif ($env:XDG_BIN_HOME) {
    $env:XDG_BIN_HOME
}
elseif ($env:XDG_DATA_HOME) {
    Join-Path $env:XDG_DATA_HOME "..\bin"
}
else {
    Join-Path $env:USERPROFILE ".local\bin"
}
New-Item -ItemType Directory -Force -Path $bin | Out-Null
Copy-Item (Join-Path $env:FAKE_FIXTURES "uv-command.cmd") (Join-Path $bin "uv.cmd") -Force
Add-Content -LiteralPath $env:CALL_LOG -Value "uv-install"
""",
        encoding="utf-8",
    )
    rtk_archive = fixtures / "rtk-x86_64-pc-windows-msvc.zip"
    with zipfile.ZipFile(rtk_archive, "w") as archive:
        archive.writestr("rtk.exe", b"fake RTK executable")
    for asset_name in (
        "opencode-windows-x64-baseline.zip",
        "opencode-windows-arm64.zip",
    ):
        with zipfile.ZipFile(
            fixtures / asset_name, "w", zipfile.ZIP_DEFLATED
        ) as archive:
            archive.write(
                Path(sys.executable).with_name("fcc-server.exe"),
                arcname="opencode.exe",
            )
    (bin_dir / "opencode.cmd").write_text(_batch_client("opencode"), encoding="utf-8")
    (bin_dir / "node.cmd").write_text(_batch_client("node"), encoding="utf-8")
    npm_prefix = tmp_path / "npm-prefix"
    npm_prefix.mkdir()
    (bin_dir / "npm.cmd").write_text(_batch_npm(), encoding="utf-8")

    wrapper = tmp_path / "run-installer.ps1"
    wrapper.write_text(
        """Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
function Invoke-RestMethod {
    [CmdletBinding()]
    param([string] $Uri, [string] $OutFile, [int] $TimeoutSec)

    Add-Content -LiteralPath $env:CALL_LOG -Value "download:$Uri"
    if (
        ($env:FAIL_STEP -eq "claude-download" -and $Uri.Contains("claude.ai")) -or
        ($env:FAIL_STEP -eq "codex-download" -and $Uri.Contains("chatgpt.com")) -or
        ($env:FAIL_STEP -eq "pi-download" -and $Uri.Contains("pi.dev")) -or
        ($env:FAIL_STEP -eq "opencode-download" -and $Uri.Contains("opencode.ai/files/bin/")) -or
        ($env:FAIL_STEP -eq "hermes-download" -and $Uri.Contains("hermes-agent.nousresearch.com")) -or
        ($env:FAIL_STEP -eq "grok-download" -and $Uri.Contains("x.ai/cli")) -or
        ($env:FAIL_STEP -eq "muse-download" -and $Uri.Contains("scripts/install-muse.ps1")) -or
        ($env:FAIL_STEP -eq "rtk-download" -and $Uri.Contains("rtk-ai/rtk")) -or
        ($env:FAIL_STEP -eq "uv-download" -and $Uri.Contains("astral.sh"))
    ) {
        throw "simulated download failure"
    }
    if ($Uri.Contains("opencode.ai/update/api/latest/cli/npm")) {
        return @{ version = $(if ($env:FAKE_OPENCODE_RELEASE) { $env:FAKE_OPENCODE_RELEASE } else { "2.0.10" }) }
    }
    if ($Uri.Contains("claude.ai")) {
        $source = Join-Path $env:FAKE_FIXTURES "claude-installer.ps1"
    }
    elseif ($Uri.Contains("chatgpt.com")) {
        $source = Join-Path $env:FAKE_FIXTURES "codex-installer.ps1"
    }
    elseif ($Uri.Contains("pi.dev")) {
        $source = Join-Path $env:FAKE_FIXTURES "pi-installer.ps1"
    }
    elseif ($Uri.Contains("hermes-agent.nousresearch.com")) {
        $source = Join-Path $env:FAKE_FIXTURES "hermes-installer.ps1"
    }
    elseif ($Uri.Contains("x.ai/cli")) {
        $source = Join-Path $env:FAKE_FIXTURES "grok-installer.ps1"
    }
    elseif ($Uri.Contains("scripts/install-muse.ps1")) {
        $source = Join-Path $env:FAKE_FIXTURES "muse-installer.ps1"
    }
    elseif ($Uri.Contains("opencode-windows-")) {
        if ($env:FAIL_STEP -eq "opencode-archive") {
            Set-Content -LiteralPath $OutFile -Value "not a zip"
            return
        }
        $source = Join-Path $env:FAKE_FIXTURES ([IO.Path]::GetFileName($Uri))
    }
    elseif ($Uri.EndsWith("rtk-x86_64-pc-windows-msvc.zip")) {
        $source = Join-Path $env:FAKE_FIXTURES "rtk-x86_64-pc-windows-msvc.zip"
    }
    elseif ($Uri.Contains("astral.sh")) {
        $source = Join-Path $env:FAKE_FIXTURES "uv-installer.ps1"
    }
    else {
        throw "unexpected installer URL: $Uri"
    }
    Copy-Item -LiteralPath $source -Destination $OutFile -Force
    if ($env:FCC_RUNNING_PHASE -eq "opencode-download" -and $Uri.Contains("opencode.ai/files/bin/")) {
        New-Item -ItemType File -Path $env:FCC_PROCESS_MARKER -Force | Out-Null
    }
}
function Get-Process {
    [CmdletBinding()]
    param([string[]] $Name)

    if ([string]::IsNullOrWhiteSpace($env:FCC_RUNNING_COMMAND)) {
        return
    }
    if (
        $env:FCC_RUNNING_PHASE -ne "early" -and
        -not (Test-Path -LiteralPath $env:FCC_PROCESS_MARKER)
    ) {
        return
    }
    foreach ($requestedName in $Name) {
        if ($requestedName -eq $env:FCC_RUNNING_COMMAND) {
            [pscustomobject] @{ Id = 4242; ProcessName = $requestedName }
        }
    }
}
$installerSource = [IO.File]::ReadAllText($env:FCC_INSTALLER)
$installerSource = $installerSource.Replace(
    '[Environment]::GetEnvironmentVariable("Path", "User")',
    '$env:FCC_TEST_USER_PATH'
)
if ($env:FCC_INSTALLER_ANSWERS) {
    $script:InstallerAnswers = (ConvertFrom-Json $env:FCC_INSTALLER_ANSWERS).answers
    $script:InstallerAnswerIndex = 0
    function Read-Host {
        param([string] $Prompt)
        Write-Host $Prompt
        if ($script:InstallerAnswerIndex -ge $script:InstallerAnswers.Count) {
            throw "Unexpected extra installer question: $Prompt"
        }
        $answer = $script:InstallerAnswers[$script:InstallerAnswerIndex]
        $script:InstallerAnswerIndex += 1
        return $answer
    }
    $installerSource = $installerSource.Replace(
        'return (-not [Console]::IsInputRedirected) -and (-not [Console]::IsOutputRedirected)',
        'return $true'
    )
    $installerSource = $installerSource.Replace(
        '    Write-Step "Choosing coding agents"',
        @'
    $selectionPathBefore = $env:Path
    $selectionOpenCodeBefore = $script:OriginalOpenCode
    Write-Step "Choosing coding agents"
'@
    ).Replace(
        '    Select-CodingAgents',
        @'
    Select-CodingAgents
    if ($env:Path -cne $selectionPathBefore) { throw "Selection changed PATH" }
    if ($script:OriginalOpenCode -ne $selectionOpenCodeBefore) { throw "Selection changed original OpenCode" }
'@
    )
}
$nativeVersionProbe = '    $output = Read-OpenCodeVersionOutput $OpenCodePath'
$fakeArchiveVersionProbe = @'
    $output = if ([IO.Path]::GetExtension($OpenCodePath) -eq ".exe") {
        Add-Content -LiteralPath $env:CALL_LOG -Value "opencode:--version"
        if ($env:FCC_RUNNING_PHASE -eq "opencode-publish" -and [IO.File]::ReadAllText($OpenCodePath) -ne "old-opencode-v1") {
            New-Item -ItemType File -Path $env:FCC_PROCESS_MARKER -Force | Out-Null
        }
        if ($env:FAIL_STEP -eq "opencode-verify") { throw "simulated version failure" }
        if ([IO.File]::ReadAllText($OpenCodePath) -eq "old-opencode-v1") {
            "opencode v1.18.31"
        } elseif ($env:FAKE_OPENCODE_ARCHIVE_VERSION) {
            $env:FAKE_OPENCODE_ARCHIVE_VERSION
        } else {
            "opencode v2.0.10"
        }
    }
    else {
        Invoke-Utf8NativeCapture -FilePath $OpenCodePath -Arguments @("--version")
    }
'@
$installerSource = $installerSource.Replace($nativeVersionProbe, $fakeArchiveVersionProbe.TrimEnd())
if ($env:FCC_INSTALLER_SCENARIO) {
    $tokens = $null
    $parseErrors = $null
    $ast = [System.Management.Automation.Language.Parser]::ParseInput(
        $installerSource, [ref] $tokens, [ref] $parseErrors
    )
    if ($parseErrors.Count) { throw "Invalid installer source: $parseErrors" }
    $definitions = @($ast.EndBlock.Statements | Where-Object {
        $_ -is [System.Management.Automation.Language.FunctionDefinitionAst]
    })
    if (-not $definitions.Count) { throw "Installer function definitions missing" }
    $installerSource = $installerSource.Substring(0, $definitions[-1].Extent.EndOffset) +
        [Environment]::NewLine + [IO.File]::ReadAllText($env:FCC_INSTALLER_SCENARIO)
}
$installer = [scriptblock]::Create($installerSource)
& $installer @args
""",
        encoding="utf-8",
    )

    system_root = os.environ["SYSTEMROOT"]
    env = os.environ.copy()
    env.update(
        {
            "PATH": os.pathsep.join(
                [str(bin_dir), str(Path(system_root) / "System32"), system_root]
            ),
            "PATHEXT": ".COM;.EXE;.BAT;.CMD",
            "PSMODULEPATH": powershell_module_paths[powershell],
            "USERPROFILE": str(home),
            "LOCALAPPDATA": str(local_app_data),
            "APPDATA": str(app_data),
            "CALL_LOG": str(log),
            "CLAUDE_CONFIG_DIR": "",
            "FAKE_FIXTURES": str(fixtures),
            "FAKE_TOOL_BIN": str(tool_bin),
            "FAKE_NPM_PREFIX": str(npm_prefix),
            "FCC_INSTALLER": str(_repo_root() / "scripts" / "install.ps1"),
            "FCC_PROCESS_MARKER": str(tmp_path / "fcc-process-ready"),
            "FCC_RUNNING_COMMAND": "",
            "FCC_RUNNING_PHASE": "early",
            "PROCESSOR_ARCHITECTURE": "AMD64",
            "PROCESSOR_ARCHITEW6432": "",
            "FAIL_STEP": "",
            "FAKE_OPENCODE_RELEASE": "",
            "FAKE_OPENCODE_ARCHIVE_VERSION": "",
            "FCC_INSTALLER_ANSWERS": "",
            "FCC_INSTALLER_SCENARIO": "",
            "FCC_TEST_USER_PATH": "",
        }
    )
    env.pop("XDG_BIN_HOME", None)
    env.pop("XDG_DATA_HOME", None)
    env.pop("UV_INSTALL_DIR", None)
    env.pop("UV_UNMANAGED_INSTALL", None)
    env.pop("UV_TOOL_BIN_DIR", None)
    env.pop("CARGO_HOME", None)
    env.pop("GROK_BIN_DIR", None)
    return PowerShellHarness(
        tmp_path, bin_dir, fixtures, tool_bin, log, env, powershell, wrapper
    )


class TestPowerShellModuleIsolation:
    @pytest.fixture(autouse=True)
    def unrelated_host_module(self, tmp_path, monkeypatch):
        modules = tmp_path / "host-modules"
        module = modules / "FccUnrelated"
        module.mkdir(parents=True)
        (module / "FccUnrelated.psd1").write_text(
            "@{RootModule='FccUnrelated.psm1'; ModuleVersion='1.0.0'; "
            "FunctionsToExport=@('Get-FccUnrelatedProbe')}",
            encoding="utf-8",
        )
        (module / "FccUnrelated.psm1").write_text(
            "Add-Content -LiteralPath $env:CALL_LOG -Value 'unrelated-module-import'\n"
            "function Get-FccUnrelatedProbe { 'unrelated' }\n"
            "Export-ModuleMember -Function Get-FccUnrelatedProbe\n",
            encoding="utf-8",
        )
        monkeypatch.setenv(
            "PSMODULEPATH",
            str(modules) + os.pathsep + os.environ.get("PSMODULEPATH", ""),
        )

    def test_missing_commands_do_not_load_host_modules(self, powershell_harness):
        result = powershell_harness.run_functions(
            """$null = Get-ApplicationCommand 'FccUnrelatedProbe'
$child = Get-PowerShellExecutable
& $child -NoProfile -Command 'Get-Command FccUnrelatedProbe -CommandType Application -ErrorAction SilentlyContinue; Get-Item -LiteralPath $env:FAKE_FIXTURES | Out-Null; exit 0'
if ($LASTEXITCODE -ne 0) { throw 'Child command lookup failed' }
"""
        )
        assert result.returncode == 0, result.stderr
        assert "unrelated-module-import" not in powershell_harness.calls()


@pytest.mark.parametrize("rtk", (False, True, None))
def test_install_ps1_auto_selects_installed_harnesses(
    powershell_harness: PowerShellHarness,
    rtk: bool | None,
) -> None:
    if rtk is not None:
        powershell_harness.add_rtk()
    for command in CODING_AGENTS:
        powershell_harness.add_client(command)

    result = powershell_harness.run_interactive(
        [] if rtk else [""], *(("-RtkHeadroom",) if rtk else ())
    )

    assert result.returncode == 0, result.stderr
    assert "Install or verify" not in result.stdout
    assert "for fcc-" not in result.stdout
    assert ("Enable RTK + Headroom token optimization" in result.stdout) is (
        rtk is not True
    )
    for command in CODING_AGENTS:
        assert f"{command}:--version" in powershell_harness.calls()
    assert "muse-install:external" in powershell_harness.calls()
    assert ("rtk:--version:telemetry=1" in powershell_harness.calls()) is (rtk is True)
    assert ("rtk:init --global --codex:telemetry=1" in powershell_harness.calls()) is (
        rtk is True
    )


@pytest.mark.parametrize("install_codex", (False, True))
@pytest.mark.parametrize("rtk", (False, True))
def test_install_ps1_asks_only_about_missing_harnesses(
    powershell_harness: PowerShellHarness, install_codex: bool, rtk: bool
) -> None:
    powershell_harness.add_client("claude")
    if rtk:
        powershell_harness.add_rtk()

    result = powershell_harness.run_interactive(
        ["y" if install_codex else ""] + [""] * 8
    )

    assert result.returncode == 0, result.stderr
    assert re.findall(r"for fcc-(\w+)\?", result.stdout) == [
        "codex",
        "pi",
        "cline",
        "hermes",
        "dsh",
        "grok",
        "muse",
        "aider",
    ]
    calls = powershell_harness.calls()
    assert "claude:--version" in calls
    assert "opencode:--version" in calls
    assert ("codex-install:1" in calls) is install_codex
    assert not any(f"{command}:--version" in calls for command in CODING_AGENTS[4:])
    assert "Enable RTK + Headroom token optimization" in result.stdout
    assert not any(call.startswith("rtk:init") for call in calls)


def test_install_ps1_discovers_installed_npm_harnesses_before_questions(
    powershell_harness: PowerShellHarness,
) -> None:
    prefix = powershell_harness.root / "custom npm"
    powershell_harness.add_npm_prefix(prefix)
    for command in ("pi", "cline", "dsh"):
        _write_executable(prefix / f"{command}.cmd", _batch_client(command))

    result = powershell_harness.run_interactive(["n"] * 7)

    assert result.returncode == 0, result.stderr
    assert re.findall(r"for fcc-(\w+)\?", result.stdout) == [
        "claude",
        "codex",
        "hermes",
        "grok",
        "muse",
        "aider",
    ]
    calls = powershell_harness.calls()
    assert "pi-install" not in calls
    assert not any(call.startswith("npm:install") for call in calls)
    for command in ("pi", "cline", "dsh"):
        assert f"{command}:--version" in calls


def _prepare_discovery_collision(
    harness: PosixHarness | PowerShellHarness, discovery: str, command: str
) -> str:
    windows = isinstance(harness, PowerShellHarness)
    suffix = ".cmd" if windows else ""
    make_command = _batch_client if windows else _posix_command
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    harness.add_uv("0.13.4")
    for name in ("claude", "codex"):
        _write_executable(
            home / ".local" / "bin" / f"{name}{suffix}", make_command(name)
        )
    extra_bin = harness.root / "extra bin"
    if discovery == "npm":
        harness.add_npm_prefix(extra_bin)
        if not windows:
            extra_bin /= "bin"
        candidate = "cline"
    else:
        harness.env["UV_TOOL_BIN_DIR"] = str(extra_bin)
        candidate = "aider"
    _write_executable(extra_bin / f"{candidate}{suffix}", make_command(candidate))
    _write_executable(
        extra_bin / f"{command}{suffix}", make_command(f"stale-{command}")
    )
    return candidate


@pytest.mark.parametrize("discovery", ("npm", "uv"))
@pytest.mark.parametrize("command", ("claude", "codex"))
def test_install_sh_discovery_preserves_existing_command_priority(
    posix_harness: PosixHarness, discovery: str, command: str
) -> None:
    candidate = _prepare_discovery_collision(posix_harness, discovery, command)

    result = posix_harness.run_interactive(
        "n\n" * 7, fail_step=f"stale-{command}-verify"
    )

    assert result.returncode == 0, result.stdout
    assert f"for fcc-{candidate}?" not in result.stdout
    calls = posix_harness.calls()
    assert "claude:--version" in calls
    assert "codex:--version" in calls
    assert f"{candidate}:--version" in calls
    assert "uv-install" not in calls
    assert not any(call.startswith(f"stale-{command}:") for call in calls)


@pytest.mark.parametrize("discovery", ("npm", "uv"))
@pytest.mark.parametrize("command", ("claude", "codex"))
def test_install_ps1_discovery_preserves_existing_command_priority(
    powershell_harness: PowerShellHarness, discovery: str, command: str
) -> None:
    candidate = _prepare_discovery_collision(powershell_harness, discovery, command)

    result = powershell_harness.run_interactive(
        ["n"] * 7, fail_step=f"stale-{command}-verify"
    )

    assert result.returncode == 0, result.stderr
    assert f"for fcc-{candidate}?" not in result.stdout
    calls = powershell_harness.calls()
    assert "claude:--version" in calls
    assert "codex:--version" in calls
    assert f"{candidate}:--version" in calls
    assert "uv-install" not in calls
    assert not any(call.startswith(f"stale-{command}:") for call in calls)


def _assert_setup_preserves_other_commands(
    harness: PosixHarness | PowerShellHarness, installing: str, other: str
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    suffix = ".cmd" if windows else ""
    make_command = _batch_client if windows else _posix_command
    prefix = harness.root / "other npm"
    harness.add_npm_prefix(prefix)
    npm_bin = prefix if windows else prefix / "bin"
    npm_bin.mkdir(exist_ok=True)
    if other == "uv":
        stale_uv = (
            '@echo off\necho stale-uv:%*>>"%CALL_LOG%"\n'
            'if "%1"=="--version" (echo uv 0.11.0& exit /b 0)\nexit /b 77\n'
            if windows
            else '#!/bin/sh\necho "stale-uv:$*" >> "$CALL_LOG"\n'
            'if [ "$1" = --version ]; then echo "uv 0.11.0"; else exit 77; fi\n'
        )
        _write_executable(npm_bin / f"uv{suffix}", stale_uv)
        harness.env["PATH"] = str(npm_bin) + os.pathsep + harness.env["PATH"]
    else:
        harness.add_uv("0.13.4")
        harness.add_client(other)
        _write_executable(npm_bin / f"{other}{suffix}", make_command(f"stale-{other}"))
        harness.env["PATH"] += os.pathsep + str(npm_bin)
    installed = {"opencode", other}
    if installing == "dsh":
        _write_executable(
            npm_bin / f"dsh{suffix}",
            make_command("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),
        )
        installed.add("dsh")
    answers = [
        "y" if name == installing else "n"
        for name in CODING_AGENTS
        if name not in installed
    ] + ["n"]
    failure = "" if other == "uv" else f"stale-{other}-verify"
    result = (
        harness.run_interactive(answers, fail_step=failure)
        if windows
        else harness.run_interactive("\n".join(answers) + "\n", fail_step=failure)
    )

    assert result.returncode == 0, result.stdout + result.stderr
    calls = harness.calls()
    assert f"{installing}:--version" in calls
    assert f"{other}:--version" in calls
    if other == "uv":
        assert "uv-install" in calls
        assert not any(call.startswith("stale-uv:tool") for call in calls)
    else:
        assert not any(call.startswith(f"stale-{other}:") for call in calls)
    assert any("--refresh-package free-claude-code" in call for call in calls)


@pytest.mark.parametrize(
    ("installing", "other"),
    (("pi", "cline"), ("dsh", "grok"), ("pi", "uv"), ("dsh", "uv")),
)
def test_install_sh_setup_preserves_other_commands(
    posix_harness: PosixHarness, installing: str, other: str
) -> None:
    _assert_setup_preserves_other_commands(posix_harness, installing, other)


@pytest.mark.parametrize(
    ("installing", "other"),
    (("pi", "cline"), ("dsh", "grok"), ("pi", "uv"), ("dsh", "uv")),
)
def test_install_ps1_setup_preserves_other_commands(
    powershell_harness: PowerShellHarness, installing: str, other: str
) -> None:
    _assert_setup_preserves_other_commands(powershell_harness, installing, other)


def test_install_ps1_verifies_new_fcc_after_custom_tool_discovery(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.env["UV_TOOL_BIN_DIR"] = str(powershell_harness.tool_bin)
    _write_executable(
        powershell_harness.bin_dir / "fcc-server.cmd", _batch_client("stale-fcc")
    )

    result = powershell_harness.run_interactive(["n"] * 10)

    assert result.returncode == 0, result.stdout + result.stderr
    calls = powershell_harness.calls()
    assert "fcc-server:--version" in calls
    assert not any(call.startswith("stale-fcc:") for call in calls)


def _assert_lookup_is_isolated(
    harness: PosixHarness | PowerShellHarness, command: str, present: bool
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    suffix = ".cmd" if windows else ""
    make_command = _batch_client if windows else _posix_command
    tool_bin = harness.root / "query tool bin"
    harness.env["UV_TOOL_BIN_DIR"] = str(tool_bin)
    harness.env["FCC_TEST_USER_PATH"] = str(tool_bin)
    harness.env["QUERY_COMMAND"] = command
    harness.env["QUERY_PRESENT"] = "1" if present else "0"
    if command == "opencode":
        (harness.bin_dir / f"opencode{suffix}").unlink()
    if command in ("pi", "cline", "dsh"):
        destination = Path(harness.env["FAKE_NPM_PREFIX"])
        if not windows:
            destination /= "bin"
    elif command == "aider" or (windows and command == "muse"):
        destination = tool_bin
    else:
        destination = harness.bin_dir
    if present:
        _write_executable(destination / f"{command}{suffix}", make_command(command))

    if isinstance(harness, PowerShellHarness):
        result = harness.run_functions("""
$script:OriginalOpenCode = $null
Add-KnownBinDirectories
$pathBefore = $env:Path
$found = Find-InstalledCodingAgent $env:QUERY_COMMAND
if ($env:Path -cne $pathBefore) { throw "Lookup changed PATH" }
if ([bool] $found -ne ($env:QUERY_PRESENT -eq "1")) { throw "Wrong presence result" }
if ($found -and (-not (Test-Path -LiteralPath $found.Source -PathType Leaf))) {
    throw "Lookup did not return an application"
}
Write-Output "lookup isolated"
""")
    else:
        source = (_repo_root() / "scripts/install.sh").read_text(encoding="utf-8")
        source = (
            source.split('\nparse_args "$@"\n', 1)[0]
            + """
original_opencode_path=""
add_known_bin_directories
path_before=$PATH
command_path=keep-command
pi_npm_prefix=keep-prefix
tool_bin=keep-tool-bin
found=""
if find_installed_coding_agent "$QUERY_COMMAND" > "$HOME/query-result"; then
    IFS= read -r found < "$HOME/query-result"
    [ "$QUERY_PRESENT" = 1 ] || fail "Unexpected command"
    [ -x "$found" ] || fail "Lookup did not return an executable"
else
    [ "$QUERY_PRESENT" = 0 ] || fail "Missing command"
fi
[ "$PATH" = "$path_before" ] || fail "Lookup changed PATH"
[ "$command_path:$pi_npm_prefix:$tool_bin" = keep-command:keep-prefix:keep-tool-bin ] || fail "Lookup changed helper state"
printf 'lookup isolated\\n'
"""
        )
        installer = harness.root / "query.sh"
        installer.write_text(source, encoding="utf-8")
        result = subprocess.run(
            ["/bin/sh", str(installer)],
            env=harness.env,
            capture_output=True,
            text=True,
            check=False,
            timeout=30,
        )
    assert result.returncode == 0, result.stdout + result.stderr
    assert "lookup isolated" in result.stdout
    assert not any("install" in call or "--version" in call for call in harness.calls())


@pytest.mark.parametrize("command", (*CODING_AGENTS, "rtk"))
@pytest.mark.parametrize("present", (False, True))
def test_install_sh_lookup_is_isolated(
    posix_harness: PosixHarness, command: str, present: bool
) -> None:
    _assert_lookup_is_isolated(posix_harness, command, present)


@pytest.mark.parametrize("command", (*CODING_AGENTS, "rtk"))
@pytest.mark.parametrize("present", (False, True))
def test_install_ps1_lookup_is_isolated(
    powershell_harness: PowerShellHarness, command: str, present: bool
) -> None:
    _assert_lookup_is_isolated(powershell_harness, command, present)


def test_install_ps1_lookup_restores_path_after_exception(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run_functions("""
$script:OriginalOpenCode = $null
$env:UV_TOOL_BIN_DIR = Join-Path $env:USERPROFILE "exception lookup"
$pathBefore = $env:Path
function Get-ApplicationCommand {
    param([string] $Name)
    if ($env:Path.Contains($env:UV_TOOL_BIN_DIR)) { throw "query failed after PATH change" }
    return $null
}
$caught = $false
try {
    $null = Find-InstalledCodingAgent "aider"
}
catch {
    if ($_.Exception.Message -ne "query failed after PATH change") { throw }
    $caught = $true
}
if (-not $caught) { throw "Expected lookup exception" }
if ($env:Path -cne $pathBefore) { throw "Failed lookup changed PATH" }
Write-Output "exception isolated"
""")
    assert result.returncode == 0, result.stdout + result.stderr
    assert "exception isolated" in result.stdout
    assert powershell_harness.calls() == []


def _aider_discovery_location(root: Path, env: dict[str, str], location: str) -> Path:
    # Competing configuration must not hide the installed tool's chosen directory.
    locations = ("UV_TOOL_BIN_DIR", "XDG_BIN_HOME", "XDG_DATA_HOME", "home")
    bins = []
    for variable in locations[locations.index(location) :]:
        if variable == "home":
            directory = root / "home" / ".local" / "bin"
        elif variable == "XDG_DATA_HOME":
            data = root / "xdg" / "data"
            data.mkdir(parents=True)
            env[variable] = str(data)
            directory = data.parent / "bin"
        else:
            directory = root / f"{variable.lower()} bin"
            env[variable] = str(directory)
        directory.mkdir(parents=True)
        bins.append(directory)
    return bins[0]


@pytest.mark.parametrize(
    "location", ("UV_TOOL_BIN_DIR", "XDG_BIN_HOME", "XDG_DATA_HOME", "home")
)
def test_install_ps1_discovers_installed_aider_without_uv(
    powershell_harness: PowerShellHarness, location: str
) -> None:
    tool_bin = _aider_discovery_location(
        powershell_harness.root, powershell_harness.env, location
    )
    _write_executable(tool_bin / "aider.cmd", _batch_client("aider"))

    result = powershell_harness.run_interactive(["n"] * 9)

    assert result.returncode == 0, result.stderr
    assert "for fcc-aider?" not in result.stdout
    calls = powershell_harness.calls()
    assert "aider:--version" in calls
    assert not any("aider-chat@latest" in call for call in calls)
    assert "uv-install" in calls


def test_install_ps1_asks_about_unrelated_pi(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_unrelated_pi()

    result = powershell_harness.run_interactive(["n"] * 10)

    assert result.returncode == 0, result.stderr
    assert "Install Pi for fcc-pi?" in result.stdout
    calls = powershell_harness.calls()
    assert "unrelated-pi:--help" in calls
    assert "unrelated-pi:--version" not in calls
    assert "pi-install" not in calls


def test_install_ps1_discovers_muse_from_user_path(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("codex")
    user_bin = powershell_harness.root / "user bin"
    _write_executable(user_bin / "muse.cmd", _batch_client("muse"))
    _write_executable(user_bin / "codex.cmd", _batch_client("wrong-codex"))
    powershell_harness.env["FCC_TEST_USER_PATH"] = str(user_bin)

    result = powershell_harness.run_interactive(["n"] * 8)

    assert result.returncode == 0, result.stderr
    assert "for fcc-muse?" not in result.stdout
    calls = powershell_harness.calls()
    assert "muse:--version" in calls
    assert "muse-install:external" in calls
    assert "codex:--version" in calls
    assert "wrong-codex:--version" not in calls


def test_install_ps1_interactive_dry_run_does_not_execute_probes(
    powershell_harness: PowerShellHarness,
) -> None:
    for command in CODING_AGENTS:
        powershell_harness.add_client(command)

    result = powershell_harness.run_interactive(["n"], "-DryRun")

    assert result.returncode == 0, result.stderr
    assert "for fcc-" not in result.stdout
    assert powershell_harness.calls() == []


def test_install_ps1_failed_npm_discovery_does_not_block_selection(
    powershell_harness: PowerShellHarness,
) -> None:
    _write_executable(
        powershell_harness.bin_dir / "npm.cmd",
        '@echo off\necho npm:%*>>"%CALL_LOG%"\nexit /b 72\n',
    )

    result = powershell_harness.run_interactive(["n"] * 10)

    assert result.returncode == 0, result.stderr
    assert "opencode:--version" in powershell_harness.calls()
    assert "npm:config get prefix" in powershell_harness.calls()


@pytest.mark.parametrize("variable", ("UV_INSTALL_DIR", "UV_UNMANAGED_INSTALL"))
def test_install_ps1_does_not_use_uv_install_directory_for_aider(
    powershell_harness: PowerShellHarness, variable: str
) -> None:
    uv_bin = powershell_harness.root / "uv bin"
    powershell_harness.env[variable] = str(uv_bin)
    _write_executable(uv_bin / "aider.cmd", _batch_client("aider"))

    result = powershell_harness.run_interactive(["n"] * 10)

    assert result.returncode == 0, result.stderr
    assert "Install Aider for fcc-aider?" in result.stdout
    assert "aider:--version" not in powershell_harness.calls()


def test_install_ps1_fresh_install_is_verified(
    powershell_harness: PowerShellHarness,
) -> None:
    (powershell_harness.bin_dir / "opencode.cmd").unlink()
    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Free Claude Code is installed and verified." in result.stdout
    calls = powershell_harness.calls()
    assert calls.index("claude-install") < calls.index("claude:--version")
    assert calls.index("codex-install:1") < calls.index("codex:--version")
    assert calls.index("pi-install") < calls.index("pi:--version")
    assert (
        "download:https://opencode.ai/files/bin/2.0.10/opencode-windows-x64-baseline.zip"
        in calls
    )
    assert calls.index("npm:install -g cline") < calls.index("cline:--version")
    assert any("hermes-agent.nousresearch.com/install.ps1" in call for call in calls)
    assert "hermes-install:True" in calls
    assert calls.index("npm:install -g @deepseek-ai/dsh@latest") < calls.index(
        "dsh:--version"
    )
    assert calls.index("grok-install") < calls.index("grok:--version")
    assert calls.index("muse-install") < calls.index("muse:--version")
    assert not any("hermes:setup" in call for call in calls)
    assert calls.index("uv-install") < calls.index("uv:--version")
    aider_install = (
        "uv:tool install --force --python python3.12 --with pip aider-chat@latest"
    )
    assert calls.index("uv:--version") < calls.index("claude-install")
    assert calls.index(aider_install) < calls.index("aider:--version")
    assert any(
        call.startswith(
            "uv:tool install --force --refresh-package free-claude-code "
            "--python cpython-3.14.7-windows-x86_64-none "
            "free-claude-code"
        )
        for call in calls
    )
    assert not any(call.startswith("git:") for call in calls)
    assert calls[-4:-1] == [
        "uv:tool update-shell",
        "uv:tool dir --bin",
        "fcc-server:--version",
    ]
    home = Path(powershell_harness.env["USERPROFILE"])
    app_data = Path(powershell_harness.env["APPDATA"])
    assert (home / ".grok" / "bin" / "grok.cmd").is_file()
    assert not (home / ".local" / "bin" / "grok.cmd").exists()
    icon = home / ".fcc" / "app-icon.ico"
    assert icon.read_text(encoding="utf-8").strip() == "fake icon"
    assert calls[-1] == f'fcc-desktop:--export-icon "{icon}"'
    desktop_shortcut = home / "Desktop" / "Free Claude Code.lnk"
    assert desktop_shortcut.is_file()
    assert (
        _windows_shortcut_icon(
            powershell_harness.powershell,
            desktop_shortcut,
            powershell_harness.env,
        )
        == f"{icon},0"
    )
    assert (
        app_data
        / "Microsoft"
        / "Windows"
        / "Start Menu"
        / "Programs"
        / "Free Claude Code.lnk"
    ).is_file()


def test_install_ps1_discovers_grok_in_custom_bin_directory(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    custom_grok_bin = powershell_harness.root / "custom-grok-bin"
    powershell_harness.env["GROK_BIN_DIR"] = str(custom_grok_bin)

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Grok"
    )

    assert result.returncode == 0, result.stderr
    assert (custom_grok_bin / "grok.cmd").is_file()
    assert not (
        Path(powershell_harness.env["USERPROFILE"]) / ".grok" / "bin" / "grok.cmd"
    ).exists()
    calls = powershell_harness.calls()
    assert calls.index("grok-install") < calls.index("grok:--version")


@pytest.mark.parametrize(
    ("client", "install_call"),
    [
        ("cline", "npm:install -g cline"),
        ("hermes", "hermes-install:True"),
        ("grok", "grok-install"),
        (
            "aider",
            "uv:tool install --force --python python3.12 --with pip aider-chat@latest",
        ),
    ],
)
def test_install_ps1_preserves_upstream_managed_harness_without_parsing_version(
    powershell_harness: PowerShellHarness,
    client: str,
    install_call: str,
) -> None:
    powershell_harness.add_uv("0.13.4")
    _write_executable(
        powershell_harness.bin_dir / f"{client}.cmd",
        _batch_client(client, version_output="opaque upstream version output"),
    )

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-" + client
    )

    assert result.returncode == 0, result.stderr
    calls = powershell_harness.calls()
    assert f"{client}:--version" in calls
    assert not any(install_call in call for call in calls)


def test_install_ps1_delegates_compatible_external_muse_without_adopting_it(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.add_client("muse")

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Muse"
    )

    assert result.returncode == 0, result.stderr
    calls = powershell_harness.calls()
    assert "muse-install:external" in calls
    assert calls.index("muse-install:external") < calls.index("muse:--version")
    managed_root = (
        Path(powershell_harness.env["LOCALAPPDATA"]) / "Programs" / "Muse Code"
    )
    assert not managed_root.exists()


@pytest.mark.parametrize("failure", ["muse-download", "muse-install"])
def test_install_ps1_stops_when_muse_install_fails(
    powershell_harness: PowerShellHarness,
    failure: str,
) -> None:
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Muse", fail_step=failure
    )

    assert result.returncode != 0
    assert "Installer scenario completed." not in result.stdout
    _assert_uv_ready_without_fcc_install(powershell_harness.calls())


@pytest.mark.parametrize("failure", ["grok-download", "grok-install"])
def test_install_ps1_stops_when_grok_install_fails(
    powershell_harness: PowerShellHarness,
    failure: str,
) -> None:
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Grok", fail_step=failure
    )

    assert result.returncode != 0
    assert "Installer scenario completed." not in result.stdout
    _assert_uv_ready_without_fcc_install(powershell_harness.calls())


def test_install_ps1_stops_when_aider_install_fails(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Aider", fail_step="aider-install"
    )

    assert result.returncode != 0
    assert "Installer scenario completed." not in result.stdout
    calls = powershell_harness.calls()
    aider_install = (
        "uv:tool install --force --python python3.12 --with pip aider-chat@latest"
    )
    assert calls.index("uv:--version") < calls.index(aider_install)
    assert not any("aider.chat/install" in call for call in calls)
    assert not any("--refresh-package free-claude-code" in call for call in calls)


def test_install_ps1_discovers_aider_in_custom_uv_tool_bin(
    powershell_harness: PowerShellHarness,
) -> None:
    custom_tool_bin = powershell_harness.root / "custom-tool-bin"
    powershell_harness.env["UV_TOOL_BIN_DIR"] = str(custom_tool_bin)

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Aider"
    )

    assert result.returncode == 0, result.stderr
    assert (custom_tool_bin / "aider.cmd").is_file()
    calls = powershell_harness.calls()
    assert "uv:tool dir --bin" in calls
    assert "aider:--version" in calls


@pytest.mark.parametrize("fail_step", ("", "aider-verify"), ids=("valid", "broken"))
@pytest.mark.parametrize("interactive", (False, True))
def test_install_ps1_checks_existing_aider_in_custom_uv_tool_bin_before_installing(
    powershell_harness: PowerShellHarness,
    fail_step: str,
    interactive: bool,
) -> None:
    custom_tool_bin = powershell_harness.root / "custom-tool-bin"
    existing_aider = custom_tool_bin / "aider.cmd"
    custom_tool_bin.mkdir()
    powershell_harness.env["UV_TOOL_BIN_DIR"] = str(custom_tool_bin)
    existing_aider.write_text(
        _batch_client("aider", version_output="existing aider 1.0.0"),
        encoding="utf-8",
    )
    original = existing_aider.read_bytes()

    result = (
        powershell_harness.run_interactive(["n"] * 9, fail_step=fail_step)
        if interactive
        else powershell_harness.run_functions(
            "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Aider", fail_step=fail_step
        )
    )

    if fail_step:
        assert result.returncode != 0
    else:
        assert result.returncode == 0, result.stderr
    calls = powershell_harness.calls()
    if interactive:
        assert "for fcc-aider?" not in result.stdout
        assert "aider:--version" in calls
    else:
        assert calls.index("uv:tool dir --bin") < calls.index("aider:--version")
    assert not any("aider-chat@latest" in call for call in calls)
    assert existing_aider.read_bytes() == original


def test_install_ps1_rejects_broken_existing_aider_without_replacing_it(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.add_client("aider")

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Aider", fail_step="aider-verify"
    )

    assert result.returncode != 0
    calls = powershell_harness.calls()
    assert "aider:--version" in calls
    assert not any("aider-chat@latest" in call for call in calls)
    assert not any("aider.chat" in call for call in calls)


@pytest.mark.parametrize(
    "version", ["0.2.0-rc.2", "0.2.0-rc.10", "0.2.0", "1.0.0", "0.2.0-rc.2+build.7"]
)
def test_install_ps1_preserves_supported_dsh(
    powershell_harness: PowerShellHarness,
    version: str,
) -> None:
    powershell_harness.add_uv("0.13.4")
    (powershell_harness.bin_dir / "dsh.cmd").write_text(
        _batch_client("dsh").replace("0.2.0-rc.2", version), encoding="utf-8"
    )

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Dsh"
    )

    assert result.returncode == 0, result.stderr
    assert "already satisfies >=0.2.0-rc.2" in result.stdout
    assert "npm:install -g @deepseek-ai/dsh@latest" not in (powershell_harness.calls())


@pytest.mark.parametrize("interactive", (False, True))
def test_install_ps1_upgrades_older_dsh_to_latest(
    powershell_harness: PowerShellHarness,
    interactive: bool,
) -> None:
    powershell_harness.add_uv("0.13.4")
    (powershell_harness.bin_dir / "dsh.cmd").write_text(
        _batch_client("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),
        encoding="utf-8",
    )

    result = (
        powershell_harness.run_interactive(["n"] * 9)
        if interactive
        else powershell_harness.run_functions(
            "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Dsh"
        )
    )

    assert result.returncode == 0, result.stdout + result.stderr
    assert "requires >=0.2.0-rc.2" in result.stdout
    assert "npm:install -g @deepseek-ai/dsh@latest" in (powershell_harness.calls())


def test_install_ps1_rejects_exact_dsh_on_unsupported_node(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.add_client("dsh")
    (powershell_harness.bin_dir / "node.cmd").write_text(
        _batch_client("node").replace("node 22.19.0", "node 23.9.0"),
        encoding="utf-8",
    )

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Dsh"
    )

    assert result.returncode != 0
    assert "requires Node.js ^22.19.0 or >=24.0.0" in (
        f"{result.stdout}\n{result.stderr}"
    )
    _assert_uv_ready_without_fcc_install(powershell_harness.calls())


@pytest.mark.parametrize("node_version", ["22.18.0", "23.9.0", "not-a-version"])
def test_install_ps1_rejects_incompatible_node_for_selected_dsh(
    powershell_harness: PowerShellHarness,
    node_version: str,
) -> None:
    powershell_harness.add_uv("0.13.4")
    (powershell_harness.bin_dir / "dsh.cmd").write_text(
        _batch_client("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),
        encoding="utf-8",
    )
    (powershell_harness.bin_dir / "node.cmd").write_text(
        _batch_client("node").replace("node 22.19.0", f"node {node_version}"),
        encoding="utf-8",
    )

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Dsh"
    )

    assert result.returncode != 0
    assert "Installer scenario completed." not in result.stdout
    _assert_uv_ready_without_fcc_install(powershell_harness.calls())


def test_install_ps1_noninteractive_skips_dsh_without_node(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients(except_for=("dsh",))
    powershell_harness.add_uv("0.13.4")
    (powershell_harness.bin_dir / "node.cmd").unlink()
    (powershell_harness.bin_dir / "npm.cmd").unlink()

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    assert "Run DeepSeek Harness with: fcc-dsh" not in result.stdout
    assert not any("@deepseek-ai/dsh" in call for call in powershell_harness.calls())


def test_install_ps1_stops_when_selected_dsh_install_fails(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Dsh", fail_step="dsh-install"
    )

    assert result.returncode != 0
    assert "Installer scenario completed." not in result.stdout
    _assert_uv_ready_without_fcc_install(powershell_harness.calls())


def test_install_ps1_installs_hermes_noninteractively(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run_functions("Ensure-Hermes")

    assert result.returncode == 0, result.stderr
    calls = powershell_harness.calls()
    assert calls.index("hermes-install:True") < calls.index("hermes:--version")


def test_install_ps1_rejects_unsupported_hermes_architecture_before_download(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.env["PROCESSOR_ARCHITECTURE"] = "MIPS"
    powershell_harness.env["PROCESSOR_ARCHITEW6432"] = "MIPS"

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Hermes"
    )

    assert result.returncode != 0
    assert "does not provide a supported Windows release" in result.stderr
    assert not any(
        "hermes-agent.nousresearch.com" in call for call in powershell_harness.calls()
    )


def test_install_ps1_selects_official_opencode_arm64_archive(
    powershell_harness: PowerShellHarness,
) -> None:
    (powershell_harness.bin_dir / "opencode.cmd").unlink()
    powershell_harness.env["PROCESSOR_ARCHITEW6432"] = "ARM64"

    result = powershell_harness.run_functions(
        '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
    )

    assert result.returncode == 0, result.stderr
    assert any(
        call.endswith("opencode-windows-arm64.zip")
        for call in powershell_harness.calls()
    )


def test_install_ps1_rejects_unsupported_opencode_architecture(
    powershell_harness: PowerShellHarness,
) -> None:
    (powershell_harness.bin_dir / "opencode.cmd").unlink()
    powershell_harness.env["PROCESSOR_ARCHITEW6432"] = "X86"

    result = powershell_harness.run_functions(
        '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
    )

    assert result.returncode != 0
    assert "does not provide a supported Windows release" in result.stderr
    assert not any(
        "opencode.ai/files/bin/" in call for call in powershell_harness.calls()
    )


def test_install_ps1_preserves_existing_rtk_and_configures_selected_agents(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_rtk()

    result = powershell_harness.run("-RtkHeadroom")

    assert result.returncode == 0, result.stderr
    assert "verifying it without updating it" in result.stdout
    calls = powershell_harness.calls()
    assert not any("rtk-ai/rtk" in call for call in calls)
    assert "rtk:--version:telemetry=1" in calls
    assert "rtk:gain:telemetry=1" in calls
    assert [call for call in calls if call.startswith("rtk:init")] == [
        "rtk:init --global --auto-patch:telemetry=1",
        "rtk:init --global --codex:telemetry=1",
        "rtk:init --global --agent pi:telemetry=1",
    ]
    assert (Path(powershell_harness.env["USERPROFILE"]) / ".claude").is_dir()


def test_install_ps1_prepares_custom_claude_config_directory_for_rtk(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.add_rtk()
    custom_config = powershell_harness.root / "custom-claude"
    powershell_harness.env["CLAUDE_CONFIG_DIR"] = str(custom_config)

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-RtkClaudeConfigDirectory",
        "-RtkHeadroom",
    )

    assert result.returncode == 0, result.stderr
    assert custom_config.is_dir()
    assert not (Path(powershell_harness.env["USERPROFILE"]) / ".claude").exists()


def test_install_ps1_rejects_conflicting_rtk_command(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.add_unrelated_rtk()

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Rtk", "-RtkHeadroom"
    )

    assert result.returncode != 0
    assert "not a compatible Rust Token Killer installation" in result.stderr
    assert not any("rtk-ai/rtk" in call for call in powershell_harness.calls())
    _assert_uv_ready_without_fcc_install(powershell_harness.calls())


def test_install_ps1_rtk_dry_run_prints_install_and_agent_setup(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run("-RtkHeadroom", "-DryRun")

    assert result.returncode == 0, result.stderr
    assert powershell_harness.calls() == []
    assert "releases/download/v0.44.2/rtk-x86_64-pc-windows-msvc.zip" in result.stdout
    assert "RTK_TELEMETRY_DISABLED=1 rtk init --global --auto-patch" in result.stdout
    assert "RTK_TELEMETRY_DISABLED=1 rtk init --global --codex" in result.stdout
    assert "RTK_TELEMETRY_DISABLED=1 rtk init --global --agent pi" in result.stdout


@pytest.mark.parametrize("valid_checksum", [True, False])
def test_install_ps1_installs_only_checksum_verified_rtk_archive(
    powershell_harness: PowerShellHarness,
    valid_checksum: bool,
) -> None:
    tmp_path = powershell_harness.root
    asset_name = "rtk-x86_64-pc-windows-msvc.zip"
    archive_path = tmp_path / asset_name
    with zipfile.ZipFile(archive_path, "w") as archive:
        archive.writestr("rtk.exe", b"verified RTK executable")
    checksum = hashlib.sha256(archive_path.read_bytes()).hexdigest()
    if not valid_checksum:
        checksum = "0" * 64

    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$DryRun = $false
$RtkReleaseBaseUrl = "https://example.test/releases/download/v0.44.2"
$RtkWindowsAssetName = "{asset_name}"
$RtkWindowsAssetSha256 = "{checksum}"
function Invoke-RestMethod {{
    [CmdletBinding()]
    param([string] $Uri, [string] $OutFile, [int] $TimeoutSec)
    Copy-Item -LiteralPath $env:RTK_TEST_ARCHIVE -Destination $OutFile
}}
Install-Rtk
"""
    home = Path(powershell_harness.env["USERPROFILE"])
    powershell_harness.env["RTK_TEST_ARCHIVE"] = str(archive_path)
    result = powershell_harness.run_functions(script)

    installed = home / ".local" / "bin" / "rtk.exe"
    if valid_checksum:
        assert result.returncode == 0, result.stderr
        assert installed.read_bytes() == b"verified RTK executable"
    else:
        assert result.returncode != 0
        assert "checksum verification failed" in result.stderr
        assert not installed.exists()


def test_install_ps1_stops_if_windows_icon_export_fails(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients()
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run(fail_step="desktop-icon-export")

    assert result.returncode != 0
    assert "Command failed with exit code 56" in result.stderr
    assert "Free Claude Code is installed and verified." in result.stdout
    assert "start the proxy with: fcc-server" in result.stdout
    assert "Open the Free Claude Code desktop shortcut" not in result.stdout
    home = Path(powershell_harness.env["USERPROFILE"])
    assert not (home / "Desktop" / "Free Claude Code.lnk").exists()


def test_install_ps1_preserves_unowned_desktop_shortcut(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    desktop_shortcut = (
        Path(powershell_harness.env["USERPROFILE"]) / "Desktop" / "Free Claude Code.lnk"
    )
    unrelated_target = powershell_harness.root / "unrelated.cmd"
    unrelated_target.write_text("@echo off\n", encoding="utf-8")
    _create_windows_shortcut(
        powershell_harness.powershell,
        desktop_shortcut,
        unrelated_target,
    )
    original_shortcut = desktop_shortcut.read_bytes()

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nInstall-FreeClaudeCode\nConfigure-AndConfirmFreeClaudeCode\nShow-InstallerNextSteps"
    )

    assert result.returncode == 0, result.stderr
    assert "not managed by Free Claude Code" in result.stdout
    assert desktop_shortcut.read_bytes() == original_shortcut
    assert "Open the Free Claude Code desktop shortcut" not in result.stdout
    assert "start the proxy with: fcc-server" in result.stdout


@pytest.mark.parametrize("uv_version", ("0.13.4", "0.13.4+build.1", "0.13.5"))
def test_install_ps1_preserves_valid_existing_tools(
    powershell_harness: PowerShellHarness,
    uv_version: str,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_client("cline")
    powershell_harness.add_client("hermes")
    powershell_harness.add_client("grok")
    powershell_harness.add_client("muse")
    powershell_harness.add_client("aider")
    powershell_harness.add_uv(uv_version)

    result = powershell_harness.run()

    assert result.returncode == 0, result.stderr
    download_calls = [
        call for call in powershell_harness.calls() if call.startswith("download:")
    ]
    assert download_calls == [
        "download:https://raw.githubusercontent.com/Alishahryar1/"
        "free-claude-code/main/scripts/install-muse.ps1"
    ]
    assert "muse-install:external" in powershell_harness.calls()
    assert "leaving it unchanged" in result.stdout


@pytest.mark.parametrize("interactive", (False, True))
def test_install_ps1_replaces_unrelated_pi_command(
    powershell_harness: PowerShellHarness,
    interactive: bool,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_unrelated_pi()
    powershell_harness.add_uv("0.13.4")

    result = (
        powershell_harness.run_interactive(["y"] + ["n"] * 7)
        if interactive
        else powershell_harness.run_functions(
            "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Pi"
        )
    )

    assert result.returncode == 0, result.stdout + result.stderr
    assert "is not Pi Coding Agent; installing Pi" in result.stdout
    assert "pi-install" in powershell_harness.calls()
    assert "pi:--version" in powershell_harness.calls()


def test_install_ps1_discovers_custom_pi_npm_prefix(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_npm_prefix(powershell_harness.root / "custom-npm")
    powershell_harness.add_uv("0.13.4")

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Pi"
    )

    assert result.returncode == 0, result.stderr
    calls = powershell_harness.calls()
    assert "npm:prefix -g" in calls
    assert "pi:--help" in calls
    assert "pi:--version" in calls


def test_install_ps1_continues_when_pi_is_not_installed(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients(except_for=("pi",))
    result = powershell_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = powershell_harness.calls()
    assert "pi-install" in calls
    assert not any(call.startswith("pi:") for call in calls)
    assert "uv-install" in calls
    assert "fcc-server:--version" in calls


def test_install_ps1_continues_when_unrelated_pi_is_unchanged(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients(except_for=("pi",))
    powershell_harness.add_unrelated_pi()

    result = powershell_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = powershell_harness.calls()
    assert "unrelated-pi:--help" in calls
    assert "unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


def test_install_ps1_continues_when_pi_resolution_changes_to_unrelated_command(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients(except_for=("pi",))
    powershell_harness.add_unrelated_pi()
    npm_prefix = powershell_harness.root / "custom-npm"
    powershell_harness.add_npm_prefix(npm_prefix)
    _write_executable(
        npm_prefix / "pi.cmd",
        _batch_client("other-unrelated-pi"),
    )

    result = powershell_harness.run(fail_step="pi-skip")

    assert result.returncode == 0, result.stderr
    assert "Pi was not installed; continuing without it." in result.stdout
    assert "Run Pi with: fcc-pi" not in result.stdout
    calls = powershell_harness.calls()
    assert "other-unrelated-pi:--help" in calls
    assert "other-unrelated-pi:--version" not in calls
    assert "fcc-server:--version" in calls


@pytest.mark.parametrize(
    "uv_version", ("0.5.9", "0.11.16", "0.12.9", "0.12.12", "0.12.13", "0.13.3")
)
def test_install_ps1_replaces_obsolete_uv(
    powershell_harness: PowerShellHarness,
    uv_version: str,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv(uv_version)

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode == 0, result.stderr
    assert powershell_harness.calls() == [
        "uv:--version",
        "download:https://astral.sh/uv/install.ps1",
        "uv-install",
        "uv:--version",
    ]
    assert f"uv {uv_version} does not satisfy stable >=0.13.4" in result.stdout


def test_install_ps1_prioritizes_replacement_uv_from_custom_install_directory(
    powershell_harness: PowerShellHarness,
) -> None:
    custom_install_dir = powershell_harness.root / "custom-uv-bin"
    powershell_harness.env["UV_INSTALL_DIR"] = str(custom_install_dir)
    powershell_harness.add_uv("0.5.9")

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode == 0, result.stderr
    assert "Verified uv 0.13.4." in result.stdout
    assert "uv-install" in powershell_harness.calls()


@pytest.mark.parametrize("install_variable", ("UV_INSTALL_DIR", "UV_UNMANAGED_INSTALL"))
def test_install_ps1_prioritizes_forced_cargo_home_uv_install_layout(
    powershell_harness: PowerShellHarness,
    install_variable: str,
) -> None:
    cargo_home = Path(powershell_harness.env["USERPROFILE"]) / ".cargo"
    cargo_bin = cargo_home / "bin"
    powershell_harness.env["CARGO_HOME"] = str(cargo_home)
    powershell_harness.env[install_variable] = str(cargo_home)
    powershell_harness.env["PATH"] = (
        f"{powershell_harness.env['PATH']}{os.pathsep}{cargo_bin}"
    )
    powershell_harness.add_uv("0.5.9")

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode == 0, result.stderr
    assert "Verified uv 0.13.4." in result.stdout
    assert "uv-install" in powershell_harness.calls()


def test_install_ps1_uv_install_dir_takes_precedence_over_unmanaged_install(
    powershell_harness: PowerShellHarness,
) -> None:
    install_bin = powershell_harness.root / "uv-install-bin"
    unmanaged_bin = powershell_harness.root / "unmanaged-uv-bin"
    powershell_harness.env["UV_INSTALL_DIR"] = str(install_bin)
    powershell_harness.env["UV_UNMANAGED_INSTALL"] = str(unmanaged_bin)
    powershell_harness.add_uv("0.5.9")

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode == 0, result.stderr
    assert (install_bin / "uv.cmd").is_file()
    assert not (unmanaged_bin / "uv.cmd").exists()


def test_install_ps1_prioritizes_replacement_uv_from_unmanaged_install_directory(
    powershell_harness: PowerShellHarness,
) -> None:
    unmanaged_bin = powershell_harness.root / "unmanaged-uv-bin"
    powershell_harness.env["UV_UNMANAGED_INSTALL"] = str(unmanaged_bin)
    powershell_harness.add_uv("0.5.9")

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode == 0, result.stderr
    assert "Verified uv 0.13.4." in result.stdout
    assert "uv-install" in powershell_harness.calls()


@pytest.mark.parametrize("version", ("0.13.4-alpha.1", "0.14.0-rc.1"))
def test_install_ps1_replaces_prerelease_uv(
    powershell_harness: PowerShellHarness,
    version: str,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv(version)

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode == 0, result.stderr
    assert f"uv {version} does not satisfy stable >=0.13.4" in result.stdout
    assert "uv-install" in powershell_harness.calls()


@pytest.mark.parametrize(
    "failure",
    [
        "claude-download",
        "claude-install",
        "claude-verify",
        "codex-download",
        "codex-install",
        "codex-verify",
        "pi-download",
        "pi-install",
        "pi-verify",
        "opencode-download",
        "opencode-archive",
        "opencode-verify",
        "cline-install",
        "cline-verify",
        "uv-download",
        "uv-install",
        "uv-verify",
        "fcc-install",
        "path-update",
        "fcc-missing",
        "fcc-verify",
    ],
)
def test_install_ps1_stops_without_success_on_each_failure(
    powershell_harness: PowerShellHarness,
    failure: str,
) -> None:
    if failure in {"fcc-install", "path-update", "fcc-missing", "fcc-verify"}:
        powershell_harness.add_installed_clients()
        powershell_harness.add_uv("0.13.4")
    if failure in {"opencode-download", "opencode-archive"}:
        (powershell_harness.bin_dir / "opencode.cmd").unlink()
    # Full workflows cover each phase's abort; component cases cover its details.
    if failure in {
        "uv-install",
        "claude-verify",
        "fcc-install",
        "path-update",
        "fcc-missing",
        "fcc-verify",
    }:
        result = powershell_harness.run(fail_step=failure)
    else:
        component = {
            "uv": "Ensure-Uv",
            "claude": "Ensure-ClaudeCode",
            "codex": "Ensure-Codex",
            "pi": "Ensure-Pi",
            "opencode": "Ensure-OpenCode",
            "cline": "Ensure-Cline",
        }[failure.split("-", 1)[0]]
        setup = '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\n'
        if component != "Ensure-Uv":
            powershell_harness.add_uv("0.13.4")
            setup += "Ensure-Uv\n"
        result = powershell_harness.run_functions(setup + component, fail_step=failure)
        assert "Installer scenario completed." not in result.stdout

    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." not in result.stdout
    calls = powershell_harness.calls()
    if failure == "path-update":
        failure_index = calls.index("uv:tool update-shell")
        assert "uv:tool dir --bin" not in calls[failure_index + 1 :]

    forbidden = {
        "claude-download": "claude-install",
        "claude-install": "claude:--version",
        "claude-verify": "chatgpt.com",
        "codex-download": "codex-install",
        "codex-install": "codex:--version",
        "codex-verify": "pi.dev",
        "pi-download": "pi-install",
        "pi-install": "pi:--version",
        "pi-verify": "opencode:--version",
        "opencode-download": "opencode:--version",
        "opencode-archive": "opencode:--version",
        "opencode-verify": "npm:install -g cline",
        "cline-install": "cline:--version",
        "cline-verify": "hermes-agent.nousresearch.com",
        "uv-download": "uv-install",
        "uv-install": "uv:--version",
        "uv-verify": "uv:tool install",
        "fcc-install": "uv:tool update-shell",
        "fcc-missing": "fcc-server:--version",
    }.get(failure)
    if forbidden is not None:
        assert not any(forbidden in call for call in calls)


def test_install_ps1_dry_run_never_executes_commands(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run("-DryRun")

    assert result.returncode == 0, result.stderr
    assert powershell_harness.calls() == []
    assert "Dry run complete. No changes were made." in result.stdout
    assert "Free Claude Code is installed and verified." not in result.stdout


def test_install_ps1_rejects_broken_existing_client_without_replacing_it(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_uv("0.13.4")
    powershell_harness.add_client("claude")

    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nEnsure-ClaudeCode",
        fail_step="claude-verify",
    )

    assert result.returncode != 0
    calls = powershell_harness.calls()
    _assert_uv_ready_without_fcc_install(calls)
    assert not any("claude.ai" in call for call in calls)


def test_install_ps1_rejects_unparseable_existing_uv(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv("not-a-version")

    result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv")

    assert result.returncode != 0
    assert not any("astral.sh" in call for call in powershell_harness.calls())


@pytest.mark.parametrize(
    ("args", "package"),
    [
        ((), "free-claude-code"),
        (("-VoiceLocal",), "free-claude-code[voice_local]"),
        (
            ("-VoiceLocal", "-TorchBackend", "cu130"),
            "free-claude-code[voice_local]",
        ),
    ],
)
def test_install_ps1_voice_flags_only_change_fcc_spec(
    powershell_harness: PowerShellHarness,
    args: tuple[str, ...],
    package: str,
) -> None:
    powershell_harness.add_uv("0.13.4")
    result = powershell_harness.run_functions(
        "Add-KnownBinDirectories\nEnsure-Uv\nInstall-FreeClaudeCode", *args
    )

    assert result.returncode == 0, result.stderr
    install_calls = [
        call
        for call in powershell_harness.calls()
        if "tool install" in call and "--refresh-package free-claude-code" in call
    ]
    assert len(install_calls) == 1
    assert package in install_calls[0]
    assert ("--torch-backend cu130" in install_calls[0]) == ("cu130" in args)


@pytest.mark.parametrize("flag", ("-VoiceNim", "-VoiceAll"))
def test_install_ps1_rejects_retired_voice_flags_before_mutation(
    powershell_harness: PowerShellHarness,
    flag: str,
) -> None:
    result = powershell_harness.run(flag)

    assert result.returncode != 0
    assert powershell_harness.calls() == []


def test_install_ps1_rejects_torch_backend_without_local_voice(
    powershell_harness: PowerShellHarness,
) -> None:
    result = powershell_harness.run("-TorchBackend", "cu130")

    assert result.returncode != 0
    assert powershell_harness.calls() == []


@pytest.mark.parametrize("command_name", FCC_COMMANDS)
def test_install_ps1_rejects_running_fcc_before_mutation(
    powershell_harness: PowerShellHarness,
    command_name: str,
) -> None:
    powershell_harness.env["FCC_RUNNING_COMMAND"] = command_name

    # One full workflow checks placement before mutation; the other names test
    # the same guard's exact process matching without repeating startup.
    result = (
        powershell_harness.run()
        if command_name == "fcc-server"
        else powershell_harness.run_functions("Assert-NoFccProcessesRunning")
    )

    assert result.returncode != 0
    assert powershell_harness.calls() == []
    assert f"{command_name} (PID 4242)" in result.stderr


def test_install_ps1_rechecks_for_fcc_process_before_tool_replacement(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_client("claude")
    powershell_harness.add_client("codex")
    powershell_harness.add_client("pi")
    powershell_harness.add_uv("0.13.4")
    powershell_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server"
    powershell_harness.env["FCC_RUNNING_PHASE"] = "late"

    result = powershell_harness.run()

    assert result.returncode != 0
    assert "fcc-server (PID 4242)" in result.stderr
    assert not any(
        "--refresh-package free-claude-code" in call
        for call in powershell_harness.calls()
    )


def test_install_ps1_ignores_similarly_named_process(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.env["FCC_RUNNING_COMMAND"] = "fcc-server-helper"

    result = powershell_harness.run_functions("Assert-NoFccProcessesRunning")

    assert result.returncode == 0, result.stderr


def test_installers_use_native_clients_and_single_python_selection() -> None:
    shell = (_repo_root() / "scripts" / "install.sh").read_text(encoding="utf-8")
    powershell = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")

    for text in (shell, powershell):
        for command_name in FCC_COMMANDS:
            assert command_name in text
        assert "@anthropic-ai/claude-code" not in text
        assert "@openai/codex" not in text
        assert "@earendil-works/pi-coding-agent" not in text
        assert "git+" not in text
        assert "git --version" not in text
        assert (
            "https://github.com/Alishahryar1/free-claude-code/archive/refs/heads/main.zip"
            not in text
        )
        assert "python install" not in text
        assert "--refresh-package" in text
        assert "tool update-shell" in text
        assert "--python" in text

    assert "https://pi.dev/install.sh" in shell
    assert "https://pi.dev/install.ps1" in powershell
    assert "https://x.ai/cli/install.sh" in shell
    assert "https://x.ai/cli/install.ps1" in powershell
    assert "https://dev.meta.ai/install.sh" in shell
    assert (
        "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/"
        "main/scripts/install-muse.ps1"
    ) in powershell


def test_install_ps1_uses_x64_python_for_windows_arm_compatibility() -> None:
    powershell = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")

    assert '$PythonRequest = "cpython-3.14.7-windows-x86_64-none"' in powershell


def test_install_ps1_rejects_invalid_download_before_execution(
    powershell_harness: PowerShellHarness,
) -> None:
    (powershell_harness.fixtures / "claude-installer.ps1").write_text(
        "<style>div#box {", encoding="utf-8"
    )
    result = powershell_harness.run_functions(
        "Invoke-DownloadedPowerShellInstaller -Url $ClaudeInstallUrl -Name 'Claude Code'"
    )
    assert result.returncode != 0
    assert "is not valid PowerShell" in result.stderr
    assert "network proxy or filter" in result.stderr
    assert "claude-install" not in powershell_harness.calls()


def test_install_ps1_installs_then_updates_only_selected_agent(
    powershell_harness: PowerShellHarness,
) -> None:
    (powershell_harness.bin_dir / "opencode.cmd").unlink()

    result = powershell_harness.run_interactive([""] * 11 + ["y"] + [""] * 9)

    assert result.returncode == 0, result.stderr
    assert "Select at least one coding agent." in result.stdout
    assert "Run Codex with: fcc-codex" in result.stdout
    calls = powershell_harness.calls()
    assert "codex-install:1" in calls
    assert not any(
        f"{command}:--version" in calls
        for command in CODING_AGENTS
        if command != "codex"
    )
    assert not any("rtk-ai/rtk" in call for call in calls)
    assert "[Y/n]" not in result.stdout

    update = powershell_harness.run_interactive([""] * 10)

    assert update.returncode == 0, update.stderr
    assert "for fcc-codex?" not in update.stdout
    update_calls = powershell_harness.calls()[len(calls) :]
    assert "codex:--version" in update_calls
    assert not any(call.startswith("download:") for call in update_calls)
    assert any("--refresh-package free-claude-code" in call for call in update_calls)


@pytest.mark.parametrize("powershell", _powershells())
@pytest.mark.parametrize(
    ("answers", "expected", "expected_messages"),
    [
        (
            ("",) * 11 + ("y",) + ("",) * 9,
            "False,True,False,False,False,False,False,False,False,False,False",
            ("Select at least one coding agent.",),
        ),
        (
            (
                "maybe",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "y",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "n",
                "y",
            ),
            "False,True,False,False,False,False,False,False,False,False,True",
            ("Please answer Y or N.", "Select at least one coding agent."),
        ),
    ],
)
def test_install_ps1_selects_at_least_one_coding_agent(
    powershell: str,
    answers: tuple[str, ...],
    expected: str,
    expected_messages: tuple[str, ...],
) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    read_yes_no = _braced_body(text, "function Read-YesNo")
    read_selection = _braced_body(text, "function Read-CodingAgentSelection")
    select_agents = _braced_body(text, "function Select-CodingAgents")
    answer_array = ", ".join(repr(answer) for answer in answers)
    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:Answers = @({answer_array})
$script:OriginalOpenCode = $null
$DryRun = $false
function Get-ApplicationCommand {{ param([string] $Name) return $null }}
function Find-InstalledCodingAgent {{ param([string] $CommandName) return $null }}
$script:AnswerIndex = 0
$script:InstallClaudeCode = $true
$script:InstallCodex = $true
$script:InstallPi = $true
$script:InstallOpenCode = $true
$script:InstallCline = $false
$script:InstallHermes = $true
$script:InstallDsh = $true
$script:InstallGrok = $true
$script:InstallMuse = $true
$script:InstallAider = $true
$script:EnableRtkHeadroom = $false
function Read-Host {{
    param([string] $Prompt)
    $answer = $script:Answers[$script:AnswerIndex]
    $script:AnswerIndex += 1
    return $answer
}}
function Read-YesNo {{{read_yes_no}}}
function Read-CodingAgentSelection {{{read_selection}}}
function Select-CodingAgents {{{select_agents}}}
Select-CodingAgents
Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi),$($script:InstallOpenCode),$($script:InstallCline),$($script:InstallHermes),$($script:InstallDsh),$($script:InstallGrok),$($script:InstallMuse),$($script:InstallAider),$($script:EnableRtkHeadroom)"
"""

    result = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr
    assert f"selection:{expected}" in result.stdout
    for message in expected_messages:
        assert message in result.stdout


def test_install_ps1_runs_only_selected_coding_agents(
    powershell_harness: PowerShellHarness,
) -> None:
    script = """Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:InstallClaudeCode = $false
$script:InstallCodex = $true
$script:InstallPi = $false
$script:InstallOpenCode = $false
$script:InstallCline = $false
$script:InstallHermes = $false
$script:InstallDsh = $false
$script:InstallGrok = $false
$script:InstallMuse = $false
$script:InstallAider = $false
$script:PiAvailable = $false
$script:MuseAvailable = $false
$script:Calls = @()
function Write-Step { param([string] $Message) }
function Ensure-ClaudeCode { $script:Calls += "claude" }
function Ensure-Codex { $script:Calls += "codex" }
function Ensure-Pi { $script:Calls += "pi"; $script:PiAvailable = $true }
function Ensure-OpenCode { $script:Calls += "opencode" }
function Ensure-Cline { $script:Calls += "cline" }
function Ensure-Hermes { $script:Calls += "hermes" }
function Ensure-Dsh { $script:Calls += "dsh" }
function Ensure-Grok { $script:Calls += "grok" }
function Ensure-Muse { $script:Calls += "muse"; $script:MuseAvailable = $true }
function Ensure-Aider { $script:Calls += "aider" }
Ensure-SelectedCodingAgents
Write-Output "calls:$($script:Calls -join ',')"
"""
    result = powershell_harness.run_functions(script)

    assert result.returncode == 0, result.stderr
    assert "calls:codex" in result.stdout


@pytest.mark.parametrize("powershell", _powershells())
def test_install_ps1_configures_rtk_only_for_available_selected_agents(
    powershell: str,
) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(text, "function Configure-RtkForSelectedAgents")
    script = f"""Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:EnableRtkHeadroom = $true
$script:InstallClaudeCode = $false
$script:InstallCodex = $true
$script:InstallPi = $true
$script:InstallOpenCode = $false
$script:InstallCline = $false
$script:InstallHermes = $false
$script:InstallDsh = $false
$script:InstallGrok = $false
$script:InstallMuse = $false
$script:InstallAider = $false
$script:PiAvailable = $false
$script:MuseAvailable = $false
$script:Calls = @()
function Write-Step {{ param([string] $Message) }}
function Ensure-Rtk {{ $script:Calls += "ensure" }}
function Invoke-RtkCommand {{
    param([string[]] $Arguments)
    $script:Calls += ($Arguments -join " ")
}}
function Configure-RtkForSelectedAgents {{{body}}}
Configure-RtkForSelectedAgents
Write-Output "calls:$($script:Calls -join ',')"
"""

    result = subprocess.run(
        [powershell, "-NoProfile", "-Command", script],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr
    assert "calls:ensure,init --global --codex" in result.stdout


def test_install_ps1_rejects_uninstalled_only_selection(
    powershell_harness: PowerShellHarness,
) -> None:
    script = """Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:InstallClaudeCode = $false
$script:InstallCodex = $false
$script:InstallPi = $true
$script:InstallOpenCode = $false
$script:InstallCline = $false
$script:InstallHermes = $false
$script:InstallDsh = $false
$script:InstallGrok = $false
$script:InstallMuse = $false
$script:InstallAider = $false
$script:PiAvailable = $false
$script:MuseAvailable = $false
function Write-Step { param([string] $Message) }
function Ensure-ClaudeCode { }
function Ensure-Codex { }
function Ensure-Pi { }
function Ensure-OpenCode { }
function Ensure-Cline { }
function Ensure-Hermes { }
function Ensure-Dsh { }
function Ensure-Grok { }
function Ensure-Muse { }
function Ensure-Aider { }
Ensure-SelectedCodingAgents
"""
    result = powershell_harness.run_functions(script)

    assert result.returncode != 0
    assert "No selected coding agent was installed." in result.stderr


def _prepare_native_opencode_v1(harness: PosixHarness | PowerShellHarness) -> Path:
    windows = isinstance(harness, PowerShellHarness)
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    (harness.bin_dir / ("opencode.cmd" if windows else "opencode")).unlink()
    binary = home / ".opencode" / "bin" / ("opencode.exe" if windows else "opencode")
    _write_executable(
        binary,
        "old-opencode-v1"
        if windows
        else _posix_command("opencode", version_output="opencode v1.18.31"),
    )
    return binary


def _assert_native_opencode_migration(
    harness: PosixHarness | PowerShellHarness,
) -> None:
    binary = _prepare_native_opencode_v1(harness)
    original = binary.read_bytes()
    if isinstance(harness, PowerShellHarness):
        harness.add_installed_clients(except_for=("opencode",))
        harness.add_uv("0.13.4")
    result = harness.run()
    assert result.returncode == 0, result.stderr
    assert binary.read_bytes() != original
    assert any(
        "opencode.ai/v2/install" in call or "opencode.ai/files/bin/2.0.10/" in call
        for call in harness.calls()
    )
    assert not any(
        "anomalyco/opencode" in call or "npm:uninstall" in call
        for call in harness.calls()
    )
    harness.log.unlink()
    result = (
        harness.run_functions(
            '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
        )
        if isinstance(harness, PowerShellHarness)
        else harness.run()
    )
    assert result.returncode == 0, result.stderr
    assert not any("opencode.ai" in call for call in harness.calls())


def test_install_sh_opencode_v2_migrates_native_v1(posix_harness: PosixHarness) -> None:
    _assert_native_opencode_migration(posix_harness)


def test_install_ps1_opencode_v2_migrates_native_v1(
    powershell_harness: PowerShellHarness,
) -> None:
    _assert_native_opencode_migration(powershell_harness)


@pytest.mark.parametrize(
    "version",
    ["opencode v1.18.31", "opencode v2.0.10-beta", "opencode v3.0.0", "opaque output"],
)
def test_install_sh_opencode_rejects_external_incompatible_version(
    posix_harness: PosixHarness, version: str
) -> None:
    path = posix_harness.bin_dir / "opencode"
    _write_executable(path, _posix_command("opencode", version_output=version))
    original = path.read_bytes()
    result = posix_harness.run()
    assert result.returncode != 0
    assert str(path) in result.stderr
    assert path.read_bytes() == original
    assert not any("opencode-install" in call for call in posix_harness.calls())


@pytest.mark.parametrize(
    "version",
    ["opencode v1.18.31", "opencode v2.0.10-beta", "opencode v3.0.0", "opaque output"],
)
def test_install_ps1_opencode_rejects_external_incompatible_version(
    powershell_harness: PowerShellHarness, version: str
) -> None:
    path = powershell_harness.bin_dir / "opencode.cmd"
    _write_executable(path, _batch_client("opencode", version_output=version))
    original = path.read_bytes()
    result = powershell_harness.run_functions(
        '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
    )
    assert result.returncode != 0
    assert str(path) in "".join(result.stderr.split())
    assert path.read_bytes() == original
    assert not any("opencode.ai" in call for call in powershell_harness.calls())


def _assert_opencode_rtk_cleanup(
    harness: PosixHarness | PowerShellHarness, modified: bool
) -> None:
    native = _prepare_native_opencode_v1(harness) if modified else None
    original = native.read_bytes() if native else None
    windows = isinstance(harness, PowerShellHarness)
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    config = home / ".config" / "opencode"
    plugin = config / "plugins" / "rtk.ts"
    plugin.parent.mkdir(parents=True)
    contents = (
        Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()
    )
    assert (
        hashlib.sha256(contents).hexdigest()
        == "6530c131946c84892f9522abd68d4e513e1e658d8ddbad1f59388c86ebbcb6bb"
    )
    if modified:
        contents += b"\n// user customization\n"
    plugin.write_bytes(contents)
    previous_backup = config / "rtk-v1-existing.bak"
    previous_backup.write_bytes(b"prior backup")
    database = home / ".local" / "share" / "opencode" / "opencode.db"
    database.parent.mkdir(parents=True)
    database.write_bytes(b"user-owned database sentinel")
    result = (
        harness.run_functions(
            '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
        )
        if isinstance(harness, PowerShellHarness)
        else harness.run()
    )
    assert database.read_bytes() == b"user-owned database sentinel"
    assert list(database.parent.iterdir()) == [database]
    assert previous_backup.read_bytes() == b"prior backup"
    if modified:
        assert result.returncode != 0
        assert "rtk.ts" in result.stderr
        assert plugin.read_bytes() == contents
        assert native is not None and native.read_bytes() == original
        assert not any("opencode.ai" in call for call in harness.calls())
    else:
        assert result.returncode == 0, result.stderr
        assert not plugin.exists()
        backups = [path for path in config.glob("rtk-v1-*") if path != previous_backup]
        assert len(backups) == 1
        assert backups[0].read_bytes() == contents
        assert str(backups[0]) in result.stdout
    assert not any("rtk:init --global --opencode" in call for call in harness.calls())


@pytest.mark.parametrize("modified", [False, True])
def test_install_sh_opencode_rtk_cleanup_without_rtk_option(
    posix_harness: PosixHarness, modified: bool
) -> None:
    _assert_opencode_rtk_cleanup(posix_harness, modified)


@pytest.mark.parametrize("modified", [False, True])
def test_install_ps1_opencode_rtk_cleanup_without_rtk_option(
    powershell_harness: PowerShellHarness, modified: bool
) -> None:
    _assert_opencode_rtk_cleanup(powershell_harness, modified)


def _assert_opencode_linked_rtk_parent_is_preserved(
    harness: PosixHarness | PowerShellHarness, parent: str
) -> None:
    native = _prepare_native_opencode_v1(harness)
    original = native.read_bytes()
    home = native.parents[2]
    plugin = home / ".config/opencode/plugins/rtk.ts"
    plugin.parent.mkdir(parents=True)
    contents = (
        Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()
    )
    plugin.write_bytes(contents)
    linked = home / parent
    shared = harness.root / "shared-config"
    linked.rename(shared)
    if isinstance(harness, PowerShellHarness):
        subprocess.run(
            [
                harness.powershell,
                "-NoProfile",
                "-Command",
                "New-Item -ItemType Junction -Path $env:FCC_TEST_LINK -Target $env:FCC_TEST_TARGET -ErrorAction Stop | Out-Null",
            ],
            env=harness.env
            | {"FCC_TEST_LINK": str(linked), "FCC_TEST_TARGET": str(shared)},
            capture_output=True,
            text=True,
            check=True,
        )
    else:
        linked.symlink_to(shared, target_is_directory=True)
    try:
        result = (
            harness.run_functions(
                '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
            )
            if isinstance(harness, PowerShellHarness)
            else harness.run()
        )
        assert result.returncode != 0
        assert "manually" in result.stderr
        assert plugin.read_bytes() == contents
        assert not list((home / ".config/opencode").glob("rtk-v1-*"))
        assert native.read_bytes() == original
        assert not any("opencode.ai" in call for call in harness.calls())
    finally:
        if isinstance(harness, PowerShellHarness):
            linked.rmdir()
        else:
            linked.unlink()


@pytest.mark.parametrize(
    "parent", [".config", ".config/opencode", ".config/opencode/plugins"]
)
def test_install_sh_opencode_linked_rtk_parent_is_preserved(
    posix_harness: PosixHarness, parent: str
) -> None:
    _assert_opencode_linked_rtk_parent_is_preserved(posix_harness, parent)


@pytest.mark.parametrize(
    "parent", [".config", ".config/opencode", ".config/opencode/plugins"]
)
def test_install_ps1_opencode_linked_rtk_parent_is_preserved(
    powershell_harness: PowerShellHarness, parent: str
) -> None:
    _assert_opencode_linked_rtk_parent_is_preserved(powershell_harness, parent)


def _assert_opencode_starting_late_blocks_mutation(
    harness: PosixHarness | PowerShellHarness, phase: str, command: str
) -> None:
    plugin_only = phase == "opencode-plugin"
    windows = isinstance(harness, PowerShellHarness)
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    native = None if plugin_only else _prepare_native_opencode_v1(harness)
    original = native.read_bytes() if native else None
    plugin = home / ".config/opencode/plugins/rtk.ts"
    plugin.parent.mkdir(parents=True)
    contents = (
        Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()
    )
    plugin.write_bytes(contents)
    harness.env["FCC_RUNNING_COMMAND"] = command
    harness.env["FCC_RUNNING_PHASE"] = phase
    result = (
        harness.run_functions(
            '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
        )
        if isinstance(harness, PowerShellHarness)
        else harness.run()
    )
    assert Path(harness.env["FCC_PROCESS_MARKER"]).exists()
    assert result.returncode != 0
    assert "Close OpenCode" in result.stderr
    assert plugin.read_bytes() == contents
    assert not list(plugin.parents[1].glob("rtk-v1-*"))
    if native:
        assert native.read_bytes() == original
        assert not list(native.parent.glob(".opencode-*"))


@pytest.mark.parametrize("phase", ["opencode-download", "opencode-plugin"])
@pytest.mark.parametrize("command", ["opencode", "opencode2"])
def test_install_sh_opencode_starting_late_blocks_mutation(
    posix_harness: PosixHarness, phase: str, command: str
) -> None:
    _assert_opencode_starting_late_blocks_mutation(posix_harness, phase, command)


@pytest.mark.parametrize(
    "phase", ["opencode-download", "opencode-publish", "opencode-plugin"]
)
@pytest.mark.parametrize("command", ["opencode", "opencode2"])
def test_install_ps1_opencode_starting_late_blocks_mutation(
    powershell_harness: PowerShellHarness, phase: str, command: str
) -> None:
    _assert_opencode_starting_late_blocks_mutation(powershell_harness, phase, command)


def test_install_sh_opencode_running_blocks_native_migration(
    posix_harness: PosixHarness,
) -> None:
    binary = _prepare_native_opencode_v1(posix_harness)
    original = binary.read_bytes()
    posix_harness.env["FCC_RUNNING_COMMAND"] = "opencode"
    result = posix_harness.run()
    assert result.returncode != 0
    assert "Close OpenCode" in result.stderr
    assert binary.read_bytes() == original


def test_install_ps1_opencode_running_blocks_native_migration(
    powershell_harness: PowerShellHarness,
) -> None:
    binary = _prepare_native_opencode_v1(powershell_harness)
    original = binary.read_bytes()
    powershell_harness.env["FCC_RUNNING_COMMAND"] = "opencode"
    result = powershell_harness.run()
    assert result.returncode != 0
    assert "Close OpenCode" in result.stderr
    assert binary.read_bytes() == original


def _assert_external_opencode_is_not_shadowed(
    harness: PosixHarness | PowerShellHarness,
    interactive: bool,
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    external = harness.bin_dir / ("opencode.cmd" if windows else "opencode")
    _write_executable(
        external,
        (_batch_client if windows else _posix_command)(
            "opencode", version_output="opencode v1.18.31"
        ),
    )
    native_bin = home / ".opencode" / "bin"
    if interactive:
        native_bin = harness.root / "custom-tool-bin"
        harness.env["UV_TOOL_BIN_DIR"] = str(native_bin)
    native = native_bin / ("opencode.exe" if windows else "opencode")
    _write_executable(native, "native-v2" if windows else _posix_command("opencode"))
    original = native.read_bytes()
    if interactive:
        result = (
            harness.run_interactive(["n"] * 10)
            if isinstance(harness, PowerShellHarness)
            else harness.run_interactive("n\n" * 10)
        )
        assert "for fcc-opencode?" not in result.stdout
    else:
        result = harness.run()
    assert result.returncode != 0
    assert str(external) in "".join((result.stdout + result.stderr).split())
    assert native.read_bytes() == original
    assert not any("opencode.ai" in call for call in harness.calls())


@pytest.mark.parametrize("interactive", (False, True))
def test_install_sh_opencode_does_not_shadow_external_v1(
    posix_harness: PosixHarness,
    interactive: bool,
) -> None:
    _assert_external_opencode_is_not_shadowed(posix_harness, interactive)


@pytest.mark.parametrize("interactive", (False, True))
def test_install_ps1_opencode_does_not_shadow_external_v1(
    powershell_harness: PowerShellHarness,
    interactive: bool,
) -> None:
    _assert_external_opencode_is_not_shadowed(powershell_harness, interactive)


def _assert_opencode_validates_current_path(
    harness: PosixHarness | PowerShellHarness, native_version: str
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    native = home / ".opencode/bin" / ("opencode.exe" if windows else "opencode")
    _write_executable(
        native,
        ("old-opencode-v1" if native_version.startswith("1.") else "native-v2")
        if windows
        else _posix_command("opencode", version_output=f"opencode v{native_version}"),
    )
    original = native.read_bytes()
    plugin = home / ".config/opencode/plugins/rtk.ts"
    plugin.parent.mkdir(parents=True)
    contents = (
        Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()
    )
    plugin.write_bytes(contents)

    # The external v2 wins initially; adding the native directory puts it first.
    result = (
        harness.run_functions(
            '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
        )
        if isinstance(harness, PowerShellHarness)
        else harness.run()
    )
    assert native.read_bytes() == original
    assert not any("opencode.ai" in call for call in harness.calls())
    if native_version.startswith("1."):
        assert result.returncode != 0
        assert str(native) in "".join(result.stderr.split())
        assert "Correct PATH" in result.stderr
        assert plugin.read_bytes() == contents
        assert not list(plugin.parents[1].glob("rtk-v1-*"))
    else:
        assert result.returncode == 0, result.stderr
        assert f"Verified OpenCode {native_version} at " in result.stdout
        assert str(native) in result.stdout


@pytest.mark.parametrize("native_version", ["1.18.31", "2.0.10"])
def test_install_sh_opencode_validates_current_path(
    posix_harness: PosixHarness, native_version: str
) -> None:
    _assert_opencode_validates_current_path(posix_harness, native_version)


@pytest.mark.parametrize("native_version", ["1.18.31", "2.0.10"])
def test_install_ps1_opencode_validates_current_path(
    powershell_harness: PowerShellHarness, native_version: str
) -> None:
    _assert_opencode_validates_current_path(powershell_harness, native_version)


@pytest.mark.parametrize("version_pin", ["1.18.31", "0.0.0-dev-19882", "2.0.9"])
def test_install_sh_opencode_ignores_version_pin_only_for_upstream_installer(
    posix_harness: PosixHarness, version_pin: str
) -> None:
    native = _prepare_native_opencode_v1(posix_harness)
    posix_harness.env["VERSION"] = version_pin
    next_installer = posix_harness.fixtures / "hermes-installer.sh"
    with next_installer.open("a", encoding="utf-8") as script:
        script.write(
            '\nprintf "version-after-opencode:%s\\n" "${VERSION:-unset}" >> "$CALL_LOG"\n'
        )
    result = posix_harness.run()
    assert result.returncode == 0, result.stderr
    installed = subprocess.run(
        [str(native), "--version"],
        env=posix_harness.env | {"FAIL_STEP": ""},
        capture_output=True,
        text=True,
        check=True,
    )
    assert installed.stdout.strip() == "opencode v2.0.10"
    assert f"version-after-opencode:{version_pin}" in posix_harness.calls()


def _assert_opencode_dry_run_preserves_migration_files(
    harness: PosixHarness | PowerShellHarness,
) -> None:
    native = _prepare_native_opencode_v1(harness)
    original = native.read_bytes()
    home = native.parents[2]
    plugin = home / ".config" / "opencode" / "plugins" / "rtk.ts"
    plugin.parent.mkdir(parents=True)
    contents = (
        Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()
    )
    plugin.write_bytes(contents)
    result = harness.run(
        "-DryRun" if isinstance(harness, PowerShellHarness) else "--dry-run"
    )
    assert result.returncode == 0, result.stderr
    assert native.read_bytes() == original
    assert plugin.read_bytes() == contents
    assert not list(plugin.parents[1].glob("rtk-v1-*"))
    assert harness.calls() == []


def test_install_sh_opencode_dry_run_preserves_v1_and_plugin(
    posix_harness: PosixHarness,
) -> None:
    _assert_opencode_dry_run_preserves_migration_files(posix_harness)


def test_install_ps1_opencode_dry_run_preserves_v1_and_plugin(
    powershell_harness: PowerShellHarness,
) -> None:
    _assert_opencode_dry_run_preserves_migration_files(powershell_harness)


def _assert_opencode_link_requires_manual_migration(
    harness: PosixHarness | PowerShellHarness,
) -> None:
    native = _prepare_native_opencode_v1(harness)
    target = native.with_name("user-managed" + native.suffix)
    native.rename(target)
    original = target.read_bytes()
    try:
        native.symlink_to(target)
    except OSError as exc:
        pytest.skip(f"symlink creation unavailable: {exc}")
    result = (
        harness.run_functions(
            '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
        )
        if isinstance(harness, PowerShellHarness)
        else harness.run()
    )
    assert result.returncode != 0
    assert "linked" in result.stderr
    assert target.read_bytes() == original
    assert native.is_symlink()
    assert not any("opencode.ai" in call for call in harness.calls())


def test_install_sh_opencode_link_requires_manual_migration(
    posix_harness: PosixHarness,
) -> None:
    _assert_opencode_link_requires_manual_migration(posix_harness)


def test_install_ps1_opencode_link_requires_manual_migration(
    powershell_harness: PowerShellHarness,
) -> None:
    _assert_opencode_link_requires_manual_migration(powershell_harness)


@pytest.mark.parametrize("version", ["1.18.31", "2.0.11-beta", "3.0.0", "bad/version"])
def test_install_ps1_opencode_rejects_invalid_release_before_replacement(
    powershell_harness: PowerShellHarness, version: str
) -> None:
    binary = _prepare_native_opencode_v1(powershell_harness)
    original = binary.read_bytes()
    powershell_harness.env["FAKE_OPENCODE_RELEASE"] = version
    result = powershell_harness.run_functions(
        '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
    )
    assert result.returncode != 0
    assert binary.read_bytes() == original
    assert not any(
        "opencode.ai/files/bin/" in call for call in powershell_harness.calls()
    )


def test_install_ps1_opencode_rejects_mismatched_archive_before_replacement(
    powershell_harness: PowerShellHarness,
) -> None:
    binary = _prepare_native_opencode_v1(powershell_harness)
    original = binary.read_bytes()
    powershell_harness.env["FAKE_OPENCODE_ARCHIVE_VERSION"] = "opencode v1.18.31"
    result = powershell_harness.run_functions(
        '$script:OriginalOpenCode = Get-ApplicationCommand "opencode"\nAdd-KnownBinDirectories\nEnsure-OpenCode'
    )
    assert result.returncode != 0
    assert binary.read_bytes() == original


@pytest.mark.parametrize("exit_code", [0, 31])
def test_install_ps1_opencode_version_probe_runs_native_command(
    powershell_harness: PowerShellHarness, exit_code: int
) -> None:
    binary = powershell_harness.root / "path with spaces" / "opencode.cmd"
    _write_executable(
        binary, f"@echo off\necho opencode v2.0.10\nexit /b {exit_code}\n"
    )
    powershell_harness.env["TEST_OPENCODE"] = str(binary)
    result = powershell_harness.run_functions(
        "Read-OpenCodeVersionOutput $env:TEST_OPENCODE"
    )
    if exit_code:
        assert result.returncode != 0
        assert f"exit code {exit_code}" in result.stderr
    else:
        assert result.returncode == 0, result.stderr
        assert "opencode v2.0.10" in result.stdout.splitlines()


@pytest.mark.parametrize("powershell", _powershells())
def test_install_ps1_falls_back_when_pshome_executable_is_unavailable(
    tmp_path: Path,
    powershell: str,
) -> None:
    text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")
    body = _braced_body(text, "function Get-PowerShellExecutable")
    fallback = tmp_path / "fallback" / "powershell.exe"
    script = tmp_path / "test-powershell-resolution.ps1"
    script.write_text(
        f"""Set-StrictMode -Version Latest
function Get-ApplicationCommand {{
    param([string] $Name)
    return [pscustomobject] @{{ Source = {str(fallback)!r} }}
}}
function Get-PowerShellExecutable {{
{body}
}}
$resolved = Get-PowerShellExecutable -PowerShellHome {str(tmp_path / "missing")!r}
if ($resolved -ne {str(fallback)!r}) {{
    throw "Unexpected fallback: $resolved"
}}
""",
        encoding="utf-8",
    )

    result = subprocess.run(
        [powershell, "-NoProfile", "-File", str(script)],
        check=False,
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr


def _assert_installer_recovers_after_verification_failure(
    harness: PosixHarness | PowerShellHarness,
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    for command in CODING_AGENTS:
        harness.add_client(command)
    harness.add_uv("0.13.4")
    harness.add_rtk()
    home = Path(harness.env["USERPROFILE" if windows else "HOME"])
    options = (
        ("-RtkHeadroom", "-VoiceLocal", "-TorchBackend", "cu130")
        if windows
        else ("--rtk-headroom", "--voice-local", "--torch-backend", "cu130")
    )

    failed = harness.run(*options, fail_step="fcc-verify")

    assert failed.returncode != 0
    assert not any(call.startswith("rtk:init") for call in harness.calls())
    assert not (home / "Desktop" / "Free Claude Code.lnk").exists()
    assert "Free Claude Code is installed and verified." not in failed.stdout
    assert re.search(r"completed.*FCC package", failed.stdout, re.IGNORECASE)
    assert re.search(r"failed.*FCC verification", failed.stdout, re.IGNORECASE)
    assert re.search(r"not attempted.*RTK", failed.stdout, re.IGNORECASE)
    retry = next(
        line for line in failed.stdout.splitlines() if line.startswith("Retry:")
    )
    assert all(option in retry for option in options)
    logs = list((home / ".fcc" / "logs").glob("install-*.log"))
    assert len(logs) == 1
    first_log = logs[0].read_text(encoding="utf-8-sig")
    assert "fcc-server" in first_log
    assert re.search(r"failed.*FCC verification", first_log, re.IGNORECASE)
    calls_before_retry = len(harness.calls())

    recovered = harness.run(*options)

    assert recovered.returncode == 0, recovered.stderr
    assert "Free Claude Code is installed and verified." in recovered.stdout
    retry_calls = harness.calls()[calls_before_retry:]
    assert "claude-install" not in retry_calls
    assert "codex-install:1" not in retry_calls
    verification = retry_calls.index("fcc-server:--version")
    assert all(
        index > verification
        for index, call in enumerate(retry_calls)
        if call.startswith("rtk:init")
    )
    assert len(list((home / ".fcc" / "logs").glob("install-*.log"))) == 2
    assert logs[0].read_text(encoding="utf-8-sig") == first_log


def test_install_sh_reports_and_recovers_after_verification_failure(
    posix_harness: PosixHarness,
) -> None:
    _assert_installer_recovers_after_verification_failure(posix_harness)


def test_install_ps1_reports_and_recovers_after_verification_failure(
    powershell_harness: PowerShellHarness,
) -> None:
    _assert_installer_recovers_after_verification_failure(powershell_harness)


def test_install_ps1_explains_child_policy_failure_without_doctor(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients()
    powershell_harness.add_uv("0.13.4")
    fixture = powershell_harness.fixtures / "fcc-command.cmd"
    fixture.write_text(
        "@echo off\n"
        'echo %~n0:%*>>"%CALL_LOG%"\n'
        'if "%~n0"=="fcc-server" (\n'
        "    echo error: uv trampoline failed to spawn Python child process 1>&2\n"
        "    echo Caused by: uncategorized error ^(os error 4551^) 1>&2\n"
        "    exit /b 1\n"
        ")\n",
        encoding="utf-8",
    )

    result = powershell_harness.run()

    assert result.returncode != 0
    output = result.stdout + result.stderr
    assert "Windows" in output and "policy" in output.lower()
    assert "Get-WinEvent" in output
    assert "CodeIntegrity/Operational" in output
    assert "3077" in output
    assert not any(
        call.startswith("fcc-doctor:") for call in powershell_harness.calls()
    )
    home = Path(powershell_harness.env["USERPROFILE"])
    logs = list((home / ".fcc" / "logs").glob("install-*.log"))
    assert len(logs) == 1
    assert "os error 4551" in logs[0].read_text(encoding="utf-8-sig")


def test_install_ps1_log_failure_preserves_installation_failure(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients()
    powershell_harness.add_uv("0.13.4")
    home = Path(powershell_harness.env["USERPROFILE"])
    (home / ".fcc").mkdir()
    (home / ".fcc" / "logs").write_text("not a directory", encoding="utf-8")

    result = powershell_harness.run(fail_step="fcc-install")

    assert result.returncode != 0
    output = result.stdout + result.stderr
    assert "53" in output
    assert re.search(r"failed.*FCC package", output, re.IGNORECASE)
    assert (home / ".fcc" / "logs").read_text(encoding="utf-8") == "not a directory"


@pytest.mark.parametrize("code", [4551, 1260, 5])
@pytest.mark.parametrize(
    "invoker", ["Invoke-NativeCommand", "Invoke-Utf8NativeCapture"]
)
def test_install_ps1_identifies_native_policy_launch_errors(
    powershell_harness: PowerShellHarness, code: int, invoker: str
) -> None:
    result = powershell_harness.run_functions(
        f"""function blocked.exe {{
    throw [ComponentModel.Win32Exception]::new({code})
}}
{invoker} -FilePath 'blocked.exe'
"""
    )
    assert result.returncode != 0
    assert ("Get-WinEvent" in result.stdout + result.stderr) == (code != 5)
    assert "blocked.exe" in result.stdout + result.stderr


def test_install_ps1_checks_selected_prerequisites_before_installing_uv(
    powershell_harness: PowerShellHarness,
) -> None:
    powershell_harness.add_installed_clients()
    (powershell_harness.bin_dir / "node.cmd").unlink()

    result = powershell_harness.run()

    assert result.returncode != 0
    assert "requires Node.js" in result.stdout + result.stderr
    assert not any(call.startswith("download:") for call in powershell_harness.calls())
    assert re.search(r"failed.*Preflight", result.stdout, re.IGNORECASE)


def test_install_sh_log_failure_preserves_installation_failure(
    posix_harness: PosixHarness,
) -> None:
    for command in CODING_AGENTS:
        posix_harness.add_client(command)
    posix_harness.add_uv("0.13.4")
    home = Path(posix_harness.env["HOME"])
    (home / ".fcc").mkdir()
    (home / ".fcc/logs").write_text("not a directory", encoding="utf-8")
    result = posix_harness.run(fail_step="fcc-install")
    assert result.returncode != 0
    assert "33" in result.stdout + result.stderr
    assert re.search(r"failed.*FCC package", result.stdout, re.IGNORECASE)
    assert (home / ".fcc/logs").read_text(encoding="utf-8") == "not a directory"


def test_install_ps1_retry_command_preserves_literal_options_and_path(
    powershell_harness: PowerShellHarness,
) -> None:
    script = powershell_harness.root / "install ' & café.ps1"
    output = powershell_harness.root / "retry-options.json"
    script.write_text(
        "param([switch] $VoiceLocal, [string] $TorchBackend, [switch] $RtkHeadroom)\n"
        "[IO.File]::WriteAllText($env:TEST_RETRY_OUTPUT, "
        "(ConvertTo-Json @($VoiceLocal.IsPresent, $TorchBackend, $RtkHeadroom.IsPresent)), [Text.Encoding]::UTF8)\n",
        encoding="utf-8-sig",
    )
    backend = "cu'130 $literal; &(literal)"
    powershell_harness.env.update(
        TEST_RETRY_PATH=str(script), TEST_RETRY_OUTPUT=str(output)
    )
    result = powershell_harness.run_functions(
        "$script:InstallerPath = $env:TEST_RETRY_PATH\n"
        "& ([scriptblock]::Create((Get-InstallerRetryCommand)))",
        "-VoiceLocal",
        "-TorchBackend",
        backend,
        "-RtkHeadroom",
    )
    assert result.returncode == 0, result.stderr
    assert json.loads(output.read_text(encoding="utf-8-sig")) == [True, backend, True]


def test_install_sh_retry_command_preserves_literal_options_and_path(
    posix_harness: PosixHarness,
) -> None:
    script = posix_harness.root / "install ' & café.sh"
    output = posix_harness.root / "retry-options"
    script.write_text('printf "%s\\n" "$@" >"$TEST_RETRY_OUTPUT"\n', encoding="utf-8")
    backend = "cu'130 $literal; &(literal)"
    posix_harness.env.update(
        TEST_RETRY_PATH=str(script),
        TEST_RETRY_OUTPUT=str(output),
        TEST_BACKEND=backend,
    )
    result = posix_harness.run_functions(
        "installer_path=$TEST_RETRY_PATH\nvoice_local=1\nenable_rtk_headroom=1\ntorch_backend=$TEST_BACKEND\n"
        'retry=$(print_installer_retry)\neval "${retry#Retry: }"'
    )
    assert result.returncode == 0, result.stderr
    assert output.read_text(encoding="utf-8").splitlines() == [
        "--voice-local",
        "--torch-backend",
        backend,
        "--rtk-headroom",
    ]


@pytest.mark.parametrize("option", ["-Help", "-DryRun"])
def test_install_ps1_preview_creates_no_log_or_probe(
    powershell_harness: PowerShellHarness,
    option: str,
) -> None:
    result = powershell_harness.run(option)
    assert result.returncode == 0, result.stderr
    assert powershell_harness.calls() == []
    assert not (Path(powershell_harness.env["USERPROFILE"]) / ".fcc/logs").exists()


@pytest.mark.parametrize("option", ["--help", "--dry-run"])
def test_install_sh_preview_creates_no_log_or_probe(
    posix_harness: PosixHarness,
    option: str,
) -> None:
    result = posix_harness.run(option)
    assert result.returncode == 0, result.stderr
    assert posix_harness.calls() == []
    assert not (Path(posix_harness.env["HOME"]) / ".fcc/logs").exists()


def _assert_pi_supplies_selected_agent_toolchain(
    harness: PosixHarness | PowerShellHarness, dependent: str
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    suffix = ".cmd" if windows else ""
    harness.add_uv("0.13.4")
    (harness.bin_dir / f"opencode{suffix}").unlink()
    for command in ("node", "npm"):
        source = harness.bin_dir / f"{command}{suffix}"
        (harness.fixtures / f"{command}-command{suffix}").write_bytes(
            source.read_bytes()
        )
        source.unlink()
    installer = harness.fixtures / (
        "pi-installer.ps1" if windows else "pi-installer.sh"
    )
    bootstrap = (
        r"""$nodeBin = Join-Path $env:LOCALAPPDATA 'pi-node\current'
New-Item -ItemType Directory -Force -Path $nodeBin | Out-Null
foreach ($command in @('node', 'npm')) {
    Copy-Item (Join-Path $env:FAKE_FIXTURES "$command-command.cmd") (Join-Path $nodeBin "$command.cmd")
}
"""
        if windows
        else """node_bin="$HOME/.local/share/pi-node/current/bin"
mkdir -p "$node_bin"
for command in node npm; do
    cp "$FAKE_FIXTURES/$command-command" "$node_bin/$command"
    chmod +x "$node_bin/$command"
done
"""
    )
    installer.write_text(
        bootstrap + installer.read_text(encoding="utf-8"), encoding="utf-8"
    )
    answers = [
        "y" if command in ("pi", dependent) else "n" for command in CODING_AGENTS
    ]
    answers.append("n")
    result = (
        harness.run_interactive(answers)
        if windows
        else harness.run_interactive("\n".join(answers) + "\n")
    )
    assert result.returncode == 0, result.stdout + result.stderr
    calls = harness.calls()
    assert "pi-install" in calls
    assert any(call.startswith("npm:install -g ") for call in calls)
    assert f"{dependent}:--version" in calls


@pytest.mark.parametrize("dependent", ["cline", "dsh"])
def test_install_ps1_pi_supplies_selected_agent_toolchain(
    powershell_harness: PowerShellHarness, dependent: str
) -> None:
    _assert_pi_supplies_selected_agent_toolchain(powershell_harness, dependent)


@pytest.mark.parametrize("dependent", ["cline", "dsh"])
def test_install_sh_pi_supplies_selected_agent_toolchain(
    posix_harness: PosixHarness, dependent: str
) -> None:
    _assert_pi_supplies_selected_agent_toolchain(posix_harness, dependent)


def test_install_sh_piped_failure_retries_downloaded_installer(
    posix_harness: PosixHarness,
) -> None:
    for command in CODING_AGENTS:
        posix_harness.add_client(command)
    posix_harness.add_uv("0.13.4")
    result = posix_harness.run_interactive("n\n", fail_step="fcc-install")
    assert result.returncode != 0
    retry = next(
        line for line in result.stdout.splitlines() if line.startswith("Retry:")
    )
    assert (
        "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install.sh"
        in retry
    )
    assert "| sh -s --" in retry


def _assert_installer_shows_selected_plan_and_next_steps(
    harness: PosixHarness | PowerShellHarness,
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    harness.add_client("claude")
    harness.add_uv("0.13.4")
    (harness.bin_dir / ("opencode.cmd" if windows else "opencode")).unlink()
    answers = ["n"] * len(CODING_AGENTS)
    result = (
        harness.run_interactive(answers)
        if windows
        else harness.run_interactive("\n".join(answers) + "\n")
    )
    assert result.returncode == 0, result.stdout + result.stderr
    assert "Installation plan:" in result.stdout
    plan = result.stdout.split("Installation plan:", 1)[1].split("Press Ctrl+C", 1)[0]
    assert "Claude Code" in plan
    assert "Codex" not in plan
    assert "RTK" not in plan
    stages = re.findall(r"\[(\d+)/(\d+)\]", result.stdout)
    assert stages
    assert [int(number) for number, _ in stages] == list(range(1, len(stages) + 1))
    assert {int(total) for _, total in stages} == {len(stages)}
    assert re.findall(r"Run .* with: (fcc-\S+)", result.stdout) == ["fcc-claude"]
    assert "wrapper is ready after" not in result.stdout
    assert "Skipped:" not in result.stdout


def test_install_ps1_shows_selected_plan_and_next_steps(
    powershell_harness: PowerShellHarness,
) -> None:
    _assert_installer_shows_selected_plan_and_next_steps(powershell_harness)


def test_install_sh_shows_selected_plan_and_next_steps(
    posix_harness: PosixHarness,
) -> None:
    _assert_installer_shows_selected_plan_and_next_steps(posix_harness)


def _assert_installer_keeps_launch_instructions_after_rtk_failure(
    harness: PosixHarness | PowerShellHarness,
) -> None:
    windows = isinstance(harness, PowerShellHarness)
    for command in CODING_AGENTS:
        harness.add_client(command)
    harness.add_uv("0.13.4")
    harness.add_rtk()
    result = harness.run(
        "-RtkHeadroom" if windows else "--rtk-headroom", fail_step="rtk-init-claude"
    )
    assert result.returncode != 0
    assert "Free Claude Code is installed and verified." in result.stdout
    assert "Run Claude Code with: fcc-claude" in result.stdout
    assert "Failed: RTK configuration" in result.stdout
    assert "Retry:" in result.stdout


def test_install_ps1_keeps_launch_instructions_after_rtk_failure(
    powershell_harness: PowerShellHarness,
) -> None:
    _assert_installer_keeps_launch_instructions_after_rtk_failure(powershell_harness)


def test_install_sh_keeps_launch_instructions_after_rtk_failure(
    posix_harness: PosixHarness,
) -> None:
    _assert_installer_keeps_launch_instructions_after_rtk_failure(posix_harness)


def test_install_sh_keeps_package_output_attached_to_terminal(
    posix_harness: PosixHarness,
) -> None:
    for command in CODING_AGENTS:
        posix_harness.add_client(command)
    posix_harness.add_uv("0.13.4")
    uv = posix_harness.bin_dir / "uv"
    source = uv.read_text(encoding="utf-8")
    uv.write_text(
        source.replace(
            "#!/bin/sh\n",
            '#!/bin/sh\nif [ "$1" = tool ] && [ "$2" = install ]; then [ -t 1 ] || exit 99; fi\n',
            1,
        ),
        encoding="utf-8",
    )
    result = posix_harness.run_interactive("n\n")
    assert result.returncode == 0, result.stdout + result.stderr