"""ssh 引数とサーバ上で実行するコマンドの組み立てのテスト（SPEC_03「接続」「取得」「run」）.

接続先は `host`（ssh の Host 名）だけ・probe は `@@labremote-user` で自分の利用者名を出す・
書式の検証は `fullmatch`．シェルの特殊文字を含む引数の引用も確かめる．

シェルでの解釈は `shlex.split`（POSIX）で確かめる（リモートの bash を起動しない）．
例外として kill のコマンドだけは，`tmp_path` の中で偽の tmux を置いた手元の bash で実際に動かす
（本物の tmux は呼ばない．bash が無い・手元のパスを扱えない環境では飛ばす）．
ls のコマンドも同じ仕組みで，`tmp_path` の中の偽のフォルダと偽の tmux で実際に動かす．
"""

from __future__ import annotations

import hashlib
import os
import re
import shlex
import shutil
import subprocess
import sys
from collections.abc import Callable, Iterator
from pathlib import Path

import pytest
from clean_helpers import CLEAN_RESULTS
from link_helpers import LinkFactory

import labremote.commands as commands_module
from labremote.cleanup import (
    LocalFile,
    RemoteListing,
    RemoteRunListing,
    RunDirEntry,
    build_clean_expected_input,
    classify_clean,
    local_paths_to_check,
    parse_clean_output,
    parse_ls_output,
)
from labremote.commands import (
    CLEAN_DELETED_MARKER,
    CLEAN_EXPECT_END_RECORD,
    CLEAN_FILE_PREFIX,
    CLEAN_FIND_FAILED_RECORD,
    CLEAN_FIND_RC_PREFIX,
    CLEAN_NOHASH_PREFIX,
    CLEAN_OTHER_PREFIX,
    CLEAN_RUN_PREFIX,
    CLEAN_STATE_LINK,
    CLEAN_STATE_MISSING,
    CLEAN_STATE_NOT_DIR,
    CLEAN_STATE_PRESENT,
    CLEAN_STATE_RESULTS_LINK,
    CLEAN_STATE_UNREADABLE,
    EXIT_CLEAN_MISMATCH,
    EXIT_CLEAN_REMAINS,
    EXIT_NO_SESSION,
    EXIT_NOT_FOUND,
    EXIT_NOT_JOB,
    EXIT_REMOTE_DIR_MISSING,
    EXIT_UNSAFE_PATH,
    GIT_COMMIT_ENV_VAR,
    NO_GPU_LABEL,
    PROBE_END_MARKER,
    PROBE_SESSIONS_MARKER,
    PROBE_USER_PREFIX,
    build_clean_delete_command,
    build_clean_list_command,
    build_job_env,
    build_job_script,
    build_kill_command,
    build_log_exists_command,
    build_logs_command,
    build_ls_command,
    build_probe_command,
    build_pull_list_command,
    build_pull_tar_command,
    build_pull_tar_input,
    build_push_command,
    build_run_command,
    build_ssh_argv,
    format_git_commit,
    job_log_path,
    parse_env_assignment,
    quote_remote_path,
    validate_env_key,
    validate_job_name,
    validate_ssh_token,
)

# シェルが特別に解釈する文字を含む引数（空白・引用符・; ・$()・バッククォート・改行・グロブ等）
NASTY_ARGS = [
    "a b",
    "it's",
    'say "hi"',
    "x; rm -rf ~",
    "$(id)",
    "`id`",
    "$HOME",
    "a\nb",
    "*",
    "a|b&c>d<e",
    "--",
    "",
    "日本語 の 引数",
    "\\",
    "!event",
]


def _argv(jump: str | None, timeout: int = 15) -> list[str]:
    return build_ssh_argv(
        "ssh",
        host="Newton",
        jump_host=jump,
        connect_timeout_sec=timeout,
        remote_command="echo hi",
    )


def _has_option(argv: list[str], value: str) -> bool:
    return any(argv[i] == "-o" and argv[i + 1] == value for i in range(len(argv) - 1))


class TestBuildSshArgv:
    def test_with_jump_host(self) -> None:
        argv = _argv("labpc")
        assert argv[0] == "ssh"
        j = argv.index("-J")
        assert argv[j + 1] == "labpc"
        assert argv[-2] == "Newton"
        assert argv[-1] == "echo hi"
        # 接続先より前にオプションがある
        assert j < argv.index("Newton")

    def test_without_jump_host(self) -> None:
        argv = _argv(None)
        assert "-J" not in argv
        assert argv[-2] == "Newton"

    @pytest.mark.parametrize("jump", ["labpc", None])
    def test_batch_mode_and_timeout_always(self, jump: str | None) -> None:
        argv = _argv(jump, timeout=7)
        assert _has_option(argv, "BatchMode=yes")
        assert _has_option(argv, "ConnectTimeout=7")

    def test_destination_is_host_name_only(self) -> None:
        # ~/.ssh/config の Host 名だけを渡す（アドレス・ユーザー名・鍵は手元の ssh の設定）
        argv = build_ssh_argv(
            "ssh",
            host="Newton",
            jump_host="labpc",
            connect_timeout_sec=15,
            remote_command="true",
        )
        assert argv[-2:] == ["Newton", "true"]
        assert not any("@" in arg for arg in argv[:-1])

    def test_no_stdin_adds_n_and_stdin_omits_it(self) -> None:
        kwargs = {
            "host": "Newton",
            "jump_host": None,
            "connect_timeout_sec": 5,
            "remote_command": "true",
        }
        assert "-n" in build_ssh_argv("ssh", **kwargs)
        assert "-n" not in build_ssh_argv("ssh", stdin=True, **kwargs)

    def test_remote_command_is_single_argument(self) -> None:
        argv = build_ssh_argv(
            "ssh",
            host="h",
            jump_host=None,
            connect_timeout_sec=5,
            remote_command="cd ~/x; echo a b",
        )
        assert argv[-1] == "cd ~/x; echo a b"

    @pytest.mark.parametrize(
        "bad", ["-oProxyCommand=evil", "a b", "", "h\n", "h;id", "$(id)", "h'", "h/x"]
    )
    @pytest.mark.parametrize("field", ["host", "jump_host"])
    def test_rejects_option_like_or_unsafe_destination(self, bad: str, field: str) -> None:
        kwargs = {"host": "h", "jump_host": None}
        kwargs[field] = bad
        with pytest.raises(ValueError):
            build_ssh_argv("ssh", connect_timeout_sec=5, remote_command="true", **kwargs)

    def test_timeout_must_be_positive(self) -> None:
        with pytest.raises(ValueError):
            _argv(None, timeout=0)


class TestValidateSshToken:
    @pytest.mark.parametrize("value", ["Newton", "labpc", "Host_1", "a.b-c", "fe80::1%eth0"])
    def test_valid(self, value: str) -> None:
        assert validate_ssh_token(value, what="x") == value

    @pytest.mark.parametrize("value", ["", "-J", "a b", "a\n", "a\tb", "a;b", "a$b", "a'b"])
    def test_invalid(self, value: str) -> None:
        with pytest.raises(ValueError):
            validate_ssh_token(value, what="x")


class TestQuoteRemotePath:
    def test_tilde_is_expanded_by_remote_shell(self) -> None:
        assert quote_remote_path("~/work/DemoProject") == '"$HOME"/work/DemoProject'
        assert quote_remote_path("~") == '"$HOME"'

    def test_special_characters_are_quoted(self) -> None:
        quoted = quote_remote_path("~/a b;$(id)")
        assert quoted.startswith('"$HOME"/')
        assert shlex.split(quoted) == ["$HOME/a b;$(id)"]

    def test_absolute_path(self) -> None:
        assert shlex.split(quote_remote_path("/srv/x y")) == ["/srv/x y"]

    @pytest.mark.parametrize("bad", ["", "  ", "~root/x"])
    def test_rejects_empty_and_other_users_home(self, bad: str) -> None:
        with pytest.raises(ValueError):
            quote_remote_path(bad)


class TestBuildProbeCommand:
    def test_queries_listed_in_spec(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500
        )
        assert "--query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu" in command
        assert "--query-compute-apps=gpu_uuid,pid,used_memory" in command
        assert "--format=csv,noheader,nounits" in command

    def test_observation_uses_interval_and_duration(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500
        )
        assert "-lms 500" in command
        assert "timeout 10" in command
        assert "pmon -s u" in command

    def test_observe_zero_does_not_observe(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=0, sample_interval_ms=500
        )
        assert "-lms" not in command
        assert "pmon" not in command
        assert "--query-gpu=index,uuid,name" in command

    def test_is_single_line(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500
        )
        assert "\n" not in command

    def test_reports_own_user_before_sessions(self) -> None:
        # 自分の利用者名を id -un で取る（設定にユーザー名を書かないため）
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=0, sample_interval_ms=500
        )
        assert f"{PROBE_USER_PREFIX}$(id -un" in command
        assert command.index(PROBE_USER_PREFIX) < command.index(PROBE_SESSIONS_MARKER)
        assert command.rstrip().endswith(f"echo '{PROBE_END_MARKER}'")

    def test_markers_use_labremote_prefix(self) -> None:
        command = build_probe_command(
            "~/work/x", results_dir="runs", observe_sec=3, sample_interval_ms=500
        )
        assert "@@tias" not in command
        assert "@@labremote-" in command

    @pytest.mark.parametrize(("observe", "interval"), [(-1, 500), (0, 0)])
    def test_rejects_bad_observation(self, observe: int, interval: int) -> None:
        with pytest.raises(ValueError):
            build_probe_command(
                "~/work/x", results_dir="runs", observe_sec=observe, sample_interval_ms=interval
            )


class TestJobSettings:
    @pytest.mark.parametrize("name", ["a", "exp1", "Exp_1-b", "x" * 64, "0"])
    def test_valid_job_names(self, name: str) -> None:
        assert validate_job_name(name) == name

    @pytest.mark.parametrize(
        "name",
        [
            "",
            "_a",
            "-a",
            "a b",
            "a.b",
            "a:b",
            "x" * 65,
            "a/b",
            # 末尾の改行（match と $ の組み合わせでは通ってしまう）
            "exp1\n",
            "..",
            "a..b",
            "a\\b",
            "a'b",
            'a"b',
            "a;b",
            "a$b",
            "$(id)",
            "a\tb",
            "ジョブ",
        ],
    )
    def test_invalid_job_names(self, name: str) -> None:
        with pytest.raises(ValueError):
            validate_job_name(name)

    def test_job_env_contains_selected_gpu_and_extra(self) -> None:
        env = build_job_env(2, ["FOO=bar", "EMPTY="])
        assert env["CUDA_VISIBLE_DEVICES"] == "2"
        assert env["FOO"] == "bar"
        assert env["EMPTY"] == ""

    def test_job_env_value_may_contain_equals_and_specials(self) -> None:
        env = build_job_env(0, ["A=x=y", "B=$(id); rm -rf ~"])
        assert env["A"] == "x=y"
        assert env["B"] == "$(id); rm -rf ~"

    def test_negative_gpu_index_is_rejected(self) -> None:
        with pytest.raises(ValueError):
            build_job_env(-1, [])

    @pytest.mark.parametrize("item", ["NOEQUALS", "=x", "1A=x", "A B=x", "A\n=x", "A-B=x", "$A=x"])
    def test_bad_env_assignment_is_rejected(self, item: str) -> None:
        with pytest.raises(ValueError):
            build_job_env(0, [item])

    @pytest.mark.parametrize("key", ["A", "_x", "DEMO_DATA_DIR", "a1_B"])
    def test_valid_env_keys(self, key: str) -> None:
        assert validate_env_key(key) == key
        assert parse_env_assignment(f"{key}=v") == (key, "v")

    @pytest.mark.parametrize(
        "key", ["", "1A", "A\n", "A B", "A-B", "A;B", "A$", "A'", "A.B", "A=B", "ＡＢ"]
    )
    def test_invalid_env_keys(self, key: str) -> None:
        with pytest.raises(ValueError):
            validate_env_key(key)

    @pytest.mark.parametrize("item", ["A=x\x00y", "A=\x00", "A=x\x00", "DEMO_DATA_DIR=a\x00b"])
    def test_nul_in_env_value_is_rejected(self, item: str) -> None:
        with pytest.raises(ValueError):
            parse_env_assignment(item)
        with pytest.raises(ValueError):
            build_job_env(0, [item])

    def test_nul_error_message_names_key(self) -> None:
        with pytest.raises(ValueError, match="NUL"):
            parse_env_assignment("FOO=x\x00y")

    @pytest.mark.parametrize(
        ("item", "expected"),
        [
            ("A=x\ny", ("A", "x\ny")),
            ("A=x\r\ny", ("A", "x\r\ny")),
            ("A=\t", ("A", "\t")),
            ("A=\x01", ("A", "\x01")),
        ],
    )
    def test_newline_and_other_controls_in_value_pass(
        self, item: str, expected: tuple[str, str]
    ) -> None:
        """改行は通る（`python -c` のコードを渡すため．引用して渡す仕様）."""
        assert parse_env_assignment(item) == expected
        assert build_job_env(0, [item])[expected[0]] == expected[1]


class TestGitCommit:
    """`LABREMOTE_GIT_COMMIT`（SPEC_03「run」・SPEC_01「環境変数」）."""

    def test_env_var_name(self) -> None:
        assert GIT_COMMIT_ENV_VAR == "LABREMOTE_GIT_COMMIT"

    def test_clean_tree_passes_short_hash(self) -> None:
        # git rev-parse --short HEAD の出力（末尾改行付き）
        assert format_git_commit("abc1234\n", dirty=False) == "abc1234"

    def test_dirty_tree_appends_suffix(self) -> None:
        assert format_git_commit("abc1234\n", dirty=True) == "abc1234-dirty"

    @pytest.mark.parametrize(
        "bad",
        [
            "",
            "abc",  # 短すぎる
            "ABC1234",  # 大文字は git の出力ではない
            "abc1234;id",
            "abc 1234",
            "abc1234\nxyz",
            "$(id)",
            "abc1234..",
            "fatal: not a git repository",
            "a" * 41,
        ],
    )
    def test_unexpected_git_output_is_not_passed(self, bad: str) -> None:
        assert format_git_commit(bad, dirty=False) is None
        assert format_git_commit(bad, dirty=True) is None

    def test_job_env_contains_git_commit(self) -> None:
        env = build_job_env(0, [], git_commit="abc1234-dirty")
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234-dirty"

    def test_job_env_without_git_commit_does_not_set_it(self) -> None:
        env = build_job_env(0, [])
        assert "LABREMOTE_GIT_COMMIT" not in env

    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_env_option_cannot_override_git_commit(self, git_commit: str | None) -> None:
        # git が使えず渡さないときも --env で指定させない（実験の記録を迂回させないため）
        with pytest.raises(ValueError):
            build_job_env(0, ["LABREMOTE_GIT_COMMIT=fake"], git_commit=git_commit)


class TestReservedEnv:
    @pytest.mark.parametrize(
        "key",
        [
            "CUDA_VISIBLE_DEVICES",
            "CUDA_DEVICE_ORDER",
            "PYTHONUNBUFFERED",
            "LABREMOTE_GIT_COMMIT",
        ],
    )
    @pytest.mark.parametrize("gpu_index", [0, None])
    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_reserved_keys_cannot_be_overridden(
        self, key: str, gpu_index: int | None, git_commit: str | None
    ) -> None:
        with pytest.raises(ValueError):
            build_job_env(gpu_index, [f"{key}=x"], git_commit=git_commit)

    def test_reserved_key_rejected_even_after_other_keys(self) -> None:
        with pytest.raises(ValueError):
            build_job_env(0, ["FOO=1", "CUDA_VISIBLE_DEVICES=0,1"])

    def test_old_data_root_env_is_not_added(self) -> None:
        # 古いデータの場所の変数（TIAS_DATA_ROOT）は足さない．データの場所は --env・設定の env で
        # 渡したものがそのまま渡る
        env = build_job_env(0, ["DEMO_DATA_DIR=data/synthetic"])
        assert env["DEMO_DATA_DIR"] == "data/synthetic"
        assert "TIAS_DATA_ROOT" not in env

    def test_fixed_values(self) -> None:
        env = build_job_env(3, [], git_commit="abc1234")
        assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"
        assert env["PYTHONUNBUFFERED"] == "1"
        assert env["CUDA_VISIBLE_DEVICES"] == "3"


def _script(
    gpu_index: int | None, command: list[str] | None = None, extra: list[str] | None = None
) -> str:
    return build_job_script(
        "~/work/DemoProject",
        "train1",
        command or ["demo-train", "--config", "configs/synthetic-gpu.yaml"],
        uv_path="~/.local/bin/uv",
        server_name="Newton",
        gpu_index=gpu_index,
        env=build_job_env(gpu_index, extra or [], git_commit="abc1234"),
        path_env={},
        results_dir="runs",
    )


class TestCpuJob:
    """`run --cpu`（SPEC_03「run」）.

    CUDA_VISIBLE_DEVICES を空文字で渡し，ログの開始行の GPU は「なし（CPU）」とする．
    """

    def test_cpu_job_env_hides_gpus(self) -> None:
        env = build_job_env(None, ["FOO=bar"], git_commit="abc1234")
        assert "CUDA_VISIBLE_DEVICES" in env
        assert env["CUDA_VISIBLE_DEVICES"] == ""
        assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert env["FOO"] == "bar"

    def test_cpu_job_log_header_says_no_gpu(self) -> None:
        script = _script(None)
        assert f"gpu={NO_GPU_LABEL}" in script
        assert "gpu=なし（CPU）" in script
        assert "gpu=None" not in script
        # 空文字として export する（未設定ではなく空にして GPU を見えなくする）
        assert "export CUDA_VISIBLE_DEVICES=''" in script

    def test_gpu_job_log_header_has_index(self) -> None:
        script = _script(1)
        assert "gpu=1" in script
        assert "なし（CPU）" not in script
        assert "export CUDA_VISIBLE_DEVICES=1" in script
        assert "export LABREMOTE_GIT_COMMIT=abc1234" in script


def _uv_run_args(script: str) -> list[str]:
    """ジョブ本体のスクリプトから，`uv run` に渡る引数（シェルが解釈した後）を取り出す."""
    tokens = shlex.split(script)
    start = tokens.index("$HOME/.local/bin/uv") + 1
    assert tokens[start] == "run"
    end = tokens.index("<", start)
    return tokens[start + 1 : end]


class TestJobScriptQuoting:
    """シェルの特殊文字を含む引数が，そのまま 1 つの引数として `uv run` に渡ること."""

    def test_plain_command(self) -> None:
        script = _script(0)
        assert _uv_run_args(script) == ["demo-train", "--config", "configs/synthetic-gpu.yaml"]

    @pytest.mark.parametrize("arg", NASTY_ARGS)
    def test_each_nasty_argument_is_one_word(self, arg: str) -> None:
        command = ["demo-train", "--config", arg]
        assert _uv_run_args(_script(0, command)) == command

    def test_all_nasty_arguments_together(self) -> None:
        command = ["demo-train", *NASTY_ARGS]
        assert _uv_run_args(_script(0, command)) == command

    def test_env_values_are_quoted(self) -> None:
        value = "x'; touch /tmp/pwned; echo '$(id)"
        tokens = shlex.split(_script(0, extra=[f"FOO={value}"]))
        assert f"FOO={value};" in tokens or f"FOO={value}" in tokens

    def test_script_runs_in_remote_dir_and_logs(self) -> None:
        script = _script(0)
        assert script.startswith('cd "$HOME"/work/DemoProject || ')
        assert "runs/_remote_logs/train1.log" in script
        assert "rc=${PIPESTATUS[0]}" in script
        assert "< /dev/null" in script
        assert "\n" not in script

    def test_path_is_extended_with_uv_dir(self) -> None:
        script = _script(0)
        assert 'export PATH="$(dirname -- "$HOME"/.local/bin/uv)":"$HOME/.local/bin:$PATH"' in (
            script
        )

    def test_exports_required_env(self) -> None:
        script = _script(2)
        for statement in [
            "export CUDA_DEVICE_ORDER=PCI_BUS_ID",
            "export CUDA_VISIBLE_DEVICES=2",
            "export PYTHONUNBUFFERED=1",
            "export LABREMOTE_GIT_COMMIT=abc1234",
        ]:
            assert statement in script

    def test_empty_command_is_rejected(self) -> None:
        with pytest.raises(ValueError):
            build_job_script(
                "~/w",
                "j",
                [],
                uv_path="~/.local/bin/uv",
                server_name="Newton",
                gpu_index=0,
                env={},
                path_env={},
                results_dir="runs",
            )

    @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", "-j"])
    def test_bad_job_name_is_rejected(self, name: str) -> None:
        with pytest.raises(ValueError):
            build_job_script(
                "~/w",
                name,
                ["true"],
                uv_path="~/.local/bin/uv",
                server_name="Newton",
                gpu_index=0,
                env={},
                path_env={},
                results_dir="runs",
            )

    @pytest.mark.parametrize("key", ["A B", "A;id", "1A", "A\n"])
    def test_bad_env_key_in_mapping_is_rejected(self, key: str) -> None:
        with pytest.raises(ValueError):
            build_job_script(
                "~/w",
                "j",
                ["true"],
                uv_path="~/.local/bin/uv",
                server_name="Newton",
                gpu_index=0,
                env={key: "v"},
                path_env={},
                results_dir="runs",
            )


class TestRunCommand:
    def test_job_script_round_trips_through_tmux_and_bash_c(self) -> None:
        """tmux → `bash -c` の 2 段の引用を外すと，元のジョブ本体に戻る."""
        script = _script(0, ["demo-train", *NASTY_ARGS])
        command = build_run_command("~/work/DemoProject", "train1", script, results_dir="runs")
        tokens = shlex.split(command)
        i = tokens.index("new-session")
        assert tokens[i : i + 7] == [
            "new-session",
            "-d",
            "-s",
            "train1",
            "-c",
            "$PWD",
            tokens[i + 6],
        ]
        inner = shlex.split(tokens[i + 6])
        assert inner == ["bash", "-c", script]

    def test_refuses_existing_session_with_exact_match(self) -> None:
        command = build_run_command("~/w", "train1", "true", results_dir="runs")
        # = を前置して完全一致（前方一致で別のジョブを選ばない）
        assert "tmux has-session -t =train1 " in command
        assert "exit 91" in command

    @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", ""])
    def test_bad_name_is_rejected(self, name: str) -> None:
        with pytest.raises(ValueError):
            build_run_command("~/w", name, "true", results_dir="runs")


class TestOtherCommands:
    def test_push_extracts_into_remote_dir(self) -> None:
        assert build_push_command("~/work/DemoProject") == (
            'mkdir -p "$HOME"/work/DemoProject && tar -xf - -C "$HOME"/work/DemoProject'
        )

    def test_push_quotes_remote_dir(self) -> None:
        tokens = shlex.split(build_push_command("/srv/a b;id"))
        assert tokens == [
            "mkdir",
            "-p",
            "/srv/a b;id",
            "&&",
            "tar",
            "-xf",
            "-",
            "-C",
            "/srv/a b;id",
        ]

    def test_logs_command(self) -> None:
        command = build_logs_command("~/w", "train1", results_dir="runs", lines=50, follow=False)
        assert "tail -n 50 runs/_remote_logs/train1.log" in command
        follow = build_logs_command("~/w", "train1", results_dir="runs", lines=10, follow=True)
        assert "-F" in follow and "cat >/dev/null" in follow

    def test_logs_rejects_negative_lines_and_bad_name(self) -> None:
        with pytest.raises(ValueError):
            build_logs_command("~/w", "train1", results_dir="runs", lines=-1, follow=False)
        with pytest.raises(ValueError):
            build_logs_command("~/w", "a;b", results_dir="runs", lines=1, follow=False)

    def test_log_exists_and_kill_validate_name(self) -> None:
        for build in (build_log_exists_command, build_kill_command):
            with pytest.raises(ValueError):
                build("~/w", "x$(id)", results_dir="runs")
        assert "tmux kill-session -t =train1" in build_kill_command(
            "~/w", "train1", results_dir="runs"
        )
        assert job_log_path("train1", results_dir="runs") == "runs/_remote_logs/train1.log"

    def test_pull_list_command_quotes_run_id_and_refuses_links(self) -> None:
        command = build_pull_list_command(
            "~/work/DemoProject", "20261119-120000_x_abc1234", results_dir="runs"
        )
        assert 'cd "$HOME"/work/DemoProject/runs' in command
        assert "[ -L 20261119-120000_x_abc1234 ]" in command
        assert "exit 94" in command
        assert "! -type d -printf '%y %p\\0'" in command

    def test_pull_tar_reads_only_given_names(self) -> None:
        command = build_pull_tar_command("~/work/DemoProject", results_dir="runs")
        assert "tar --null --no-recursion -T - -cf -" in command


# ---------------------------------------------------------------------------
# 名前（SPEC_01「環境変数」・SPEC_03「サブコマンド」）
# ---------------------------------------------------------------------------

# 移す元（tsm-remote）の名前．組み立てた結果に残っていないことを確かめる
OLD_NAMES = ["tsm-remote", "tsm_remote", "@@tsm-", "TSM_"]


def _built_commands() -> dict[str, str]:
    """サーバで実行するコマンドを一通り組み立てる（ジョブのコマンドは古い名前を含まないもの）."""
    remote_dir = "~/work/proj"
    script = build_job_script(
        remote_dir,
        "train1",
        ["python", "-m", "train"],
        uv_path="~/.local/bin/uv",
        server_name="Newton",
        gpu_index=0,
        env=build_job_env(0, [], git_commit="abc1234"),
        path_env={},
        results_dir="runs",
    )
    return {
        "probe": build_probe_command(
            remote_dir, results_dir="runs", observe_sec=3, sample_interval_ms=500
        ),
        "push": build_push_command(remote_dir),
        "job_script": script,
        "run": build_run_command(remote_dir, "train1", script, results_dir="runs"),
        "log_exists": build_log_exists_command(remote_dir, "train1", results_dir="runs"),
        "logs": build_logs_command(remote_dir, "train1", results_dir="runs", lines=50, follow=True),
        "kill": build_kill_command(remote_dir, "train1", results_dir="runs"),
        "pull_list": build_pull_list_command(
            remote_dir, "20261119-120000_x_abc1234", results_dir="runs"
        ),
        "pull_tar": build_pull_tar_command(remote_dir, results_dir="runs"),
    }


class TestNaming:
    @pytest.mark.parametrize("kind", list(_built_commands()))
    def test_built_commands_have_no_old_names(self, kind: str) -> None:
        # SPEC_01「全体像」: コマンドの名前は labremote（サーバの目印・エラーの接頭辞も含む）
        command = _built_commands()[kind]
        for old in OLD_NAMES:
            assert old not in command, f"{kind} に {old!r} が残っている"

    @pytest.mark.parametrize("kind", ["run", "logs", "kill"])
    def test_remote_error_messages_use_labremote_prefix(self, kind: str) -> None:
        # SPEC_01「全体像」: サーバ側のエラーメッセージの接頭辞も labremote
        assert "'labremote: " in _built_commands()[kind]

    def test_probe_markers_all_use_labremote_prefix(self) -> None:
        # SPEC_01「全体像」: サーバの出力の目印は @@labremote-
        markers = {
            name: value
            for name, value in vars(commands_module).items()
            if name.startswith("PROBE_") and isinstance(value, str) and value.startswith("@@")
        }
        assert len(markers) >= 10
        for name, marker in markers.items():
            assert marker.startswith("@@labremote-"), name

    def test_job_env_has_no_old_git_commit_name(self) -> None:
        # SPEC_01「環境変数」: ジョブへ渡す git のハッシュは LABREMOTE_GIT_COMMIT
        env = build_job_env(0, [], git_commit="abc1234")
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert "TSM_GIT_COMMIT" not in env
        assert not [key for key in env if key.startswith("TSM_")]

    def test_job_script_exports_new_git_commit_name_only(self) -> None:
        # SPEC_01「環境変数」: ジョブへ渡す git のハッシュは LABREMOTE_GIT_COMMIT
        script = _built_commands()["job_script"]
        assert "export LABREMOTE_GIT_COMMIT=abc1234" in script
        assert "TSM_GIT_COMMIT" not in script

    def test_old_git_commit_name_is_not_reserved(self) -> None:
        # SPEC_01「環境変数」: 予約は CUDA_VISIBLE_DEVICES・CUDA_DEVICE_ORDER・PYTHONUNBUFFERED・
        # LABREMOTE_GIT_COMMIT の 4 つだけ．古い名前は普通の変数としてそのまま渡る
        env = build_job_env(0, ["TSM_GIT_COMMIT=x"], git_commit="abc1234")
        assert env["TSM_GIT_COMMIT"] == "x"
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"


# ---------------------------------------------------------------------------
# git_commit_env と設定由来の環境変数（SPEC_01「環境変数」「名前と値の検証」，SPEC_02「`run`」）
# ---------------------------------------------------------------------------

RESERVED_NAMES = [
    "CUDA_VISIBLE_DEVICES",
    "CUDA_DEVICE_ORDER",
    "PYTHONUNBUFFERED",
    "LABREMOTE_GIT_COMMIT",
]


def _exports(script: str) -> dict[str, str]:
    """ジョブ本体のスクリプトを POSIX シェルの規則で区切り，`export K=V` の K と V を取り出す.

    `;` を区切りとして扱うため，値が引用されていなければ `;` で別のコマンドに割れて
    元の値と一致しない．
    """
    lexer = shlex.shlex(script, posix=True, punctuation_chars=True)
    lexer.whitespace_split = True
    tokens = list(lexer)
    found: dict[str, str] = {}
    for i, token in enumerate(tokens[:-1]):
        if token == "export" and "=" in tokens[i + 1]:
            key, _, value = tokens[i + 1].partition("=")
            found[key] = value
            # export の直後は区切り（;）でなければならない（値の一部が別の語として残らない）
            assert tokens[i + 2] == ";"
    return found


class TestGitCommitEnvName:
    def test_same_value_is_passed_under_both_names(self) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前で LABREMOTE_GIT_COMMIT と同じ値を渡す."""
        env = build_job_env(0, [], git_commit="abc1234-dirty", git_commit_env="DEMO_GIT_COMMIT")
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234-dirty"
        assert env["DEMO_GIT_COMMIT"] == "abc1234-dirty"

    def test_without_git_commit_env_only_labremote_name(self) -> None:
        """SPEC_02「`project`」: git_commit_env を指定しなければ LABREMOTE_GIT_COMMIT だけ."""
        env = build_job_env(0, [], git_commit="abc1234")
        assert [k for k, v in env.items() if v == "abc1234"] == ["LABREMOTE_GIT_COMMIT"]

    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_env_option_cannot_override_git_commit_env(self, git_commit: str | None) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前は予約で，`--env` では指定できない."""
        with pytest.raises(ValueError):
            build_job_env(
                0,
                ["FOO=1", "DEMO_GIT_COMMIT=fake"],
                git_commit=git_commit,
                git_commit_env="DEMO_GIT_COMMIT",
            )

    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_base_env_cannot_override_git_commit_env(self, git_commit: str | None) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前は予約で，設定でも指定できない."""
        with pytest.raises(ValueError):
            build_job_env(
                0,
                [],
                git_commit=git_commit,
                git_commit_env="DEMO_GIT_COMMIT",
                base_env={"DEMO_GIT_COMMIT": "fake"},
            )

    @pytest.mark.parametrize("name", RESERVED_NAMES)
    def test_reserved_name_as_git_commit_env_is_rejected(self, name: str) -> None:
        """SPEC_01「環境変数」: 予約の名前は git_commit_env にできない."""
        with pytest.raises(ValueError):
            build_job_env(0, [], git_commit="abc1234", git_commit_env=name)

    @pytest.mark.parametrize("name", ["", "A B", "A=B", "1A", "A\n", "A;B", "$(id)"])
    def test_invalid_git_commit_env_is_rejected(self, name: str) -> None:
        """SPEC_01「名前と値の検証」: 環境変数の名前は全体一致で確かめる."""
        with pytest.raises(ValueError):
            build_job_env(0, [], git_commit="abc1234", git_commit_env=name)

    def test_script_exports_both_names(self) -> None:
        """SPEC_01「環境変数」: 両方の名前がジョブのスクリプトで export される."""
        env = build_job_env(1, [], git_commit="abc1234", git_commit_env="DEMO_GIT_COMMIT")
        script = build_job_script(
            "~/work/x",
            "train1",
            ["python"],
            uv_path="~/.local/bin/uv",
            server_name="Newton",
            gpu_index=1,
            env=env,
            path_env={},
            results_dir="runs",
        )
        exports = _exports(script)
        assert exports["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert exports["DEMO_GIT_COMMIT"] == "abc1234"


class TestBaseEnv:
    def test_base_env_is_passed(self) -> None:
        """SPEC_02「`run`」: 設定の環境変数がジョブに渡る."""
        env = build_job_env(0, [], base_env={"A": "1", "B": "~/data"})
        assert env["A"] == "1"
        assert env["B"] == "~/data"

    def test_env_option_wins_over_base_env(self) -> None:
        """SPEC_02「`run`」: `--env` で同じ名前を指定すると `--env` が優先される."""
        env = build_job_env(0, ["A=cli"], base_env={"A": "config", "B": "config"})
        assert env["A"] == "cli"
        assert env["B"] == "config"

    def test_fixed_values_are_not_changed_by_base_env(self) -> None:
        """SPEC_01「環境変数」: 予約の値は設定の環境変数があっても変わらない."""
        env = build_job_env(2, [], git_commit="abc1234", base_env={"A": "1"})
        assert env["CUDA_VISIBLE_DEVICES"] == "2"
        assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"
        assert env["PYTHONUNBUFFERED"] == "1"
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"

    @pytest.mark.parametrize("name", RESERVED_NAMES)
    @pytest.mark.parametrize("gpu_index", [0, None])
    @pytest.mark.parametrize("git_commit", ["abc1234", None])
    def test_reserved_name_in_base_env_is_rejected(
        self, name: str, gpu_index: int | None, git_commit: str | None
    ) -> None:
        """SPEC_01「名前と値の検証」: 予約の環境変数は設定でも上書きできない."""
        with pytest.raises(ValueError):
            build_job_env(gpu_index, [], git_commit=git_commit, base_env={"A": "1", name: "x"})

    @pytest.mark.parametrize("name", ["", "A B", "A=B", "1A", "A\n", "A-B", "$(id)"])
    def test_invalid_name_in_base_env_is_rejected(self, name: str) -> None:
        """SPEC_01「名前と値の検証」: 環境変数の名前は全体一致で確かめる."""
        with pytest.raises(ValueError):
            build_job_env(0, [], base_env={name: "x"})

    @pytest.mark.parametrize("value", ["\x00", "a\x00b"])
    def test_nul_in_base_env_value_is_rejected(self, value: str) -> None:
        """SPEC_01「名前と値の検証」: 値の NUL を拒否する."""
        with pytest.raises(ValueError):
            build_job_env(0, [], base_env={"A": value})


# 値として渡すシェルの特殊文字（空白・;・$()・引用符・改行等）
NASTY_VALUES = {
    "SPACE": "a b",
    "SEMI": "x; touch pwned",
    "SUBST": "$(id)",
    "BACKTICK": "`id`",
    "SQUOTE": "it's",
    "DQUOTE": 'say "hi"',
    "NEWLINE": "a\nrm -rf ~",
    "VAR": "$HOME",
    "TILDE": "~/data",
    "PIPE": "a|b&c>d<e",
    "EMPTY": "",
    "MIXED": "x'; touch pwned; echo '$(id)",
}


class TestBaseEnvQuoting:
    def _script(self, env: dict[str, str]) -> str:
        return build_job_script(
            "~/work/x",
            "train1",
            ["python"],
            uv_path="~/.local/bin/uv",
            server_name="Newton",
            gpu_index=0,
            env=env,
            path_env={},
            results_dir="runs",
        )

    @pytest.mark.parametrize(("key", "value"), list(NASTY_VALUES.items()))
    def test_each_value_is_one_word(self, key: str, value: str) -> None:
        """SPEC_01「名前と値の検証」: 設定の値は引用して渡し，別のコマンドとして解釈されない."""
        env = build_job_env(0, [], git_commit="abc1234", base_env={key: value})
        assert _exports(self._script(env))[key] == value

    def test_all_values_together_survive_tmux_and_bash(self) -> None:
        """SPEC_01「名前と値の検証」: tmux → bash -c の 2 段を経ても値が 1 語のまま戻る."""
        env = build_job_env(0, ["CLI=$(id); x"], git_commit="abc1234", base_env=NASTY_VALUES)
        script = self._script(env)
        command = build_run_command("~/work/x", "train1", script, results_dir="runs")
        tokens = shlex.split(command)
        inner = shlex.split(tokens[tokens.index("new-session") + 6])
        assert inner[:2] == ["bash", "-c"]
        exports = _exports(inner[2])
        for key, value in NASTY_VALUES.items():
            assert exports[key] == value
        assert exports["CLI"] == "$(id); x"
        # 特殊文字が値の外に漏れて，余分なコマンドが増えていない
        assert "touch" not in shlex.split(inner[2])


# ---------------------------------------------------------------------------
# 結果の置き場（SPEC_02「`results`」の `dir`・SPEC_03「pull」「run」のログの置き場）
# ---------------------------------------------------------------------------


def _builders_with_results_dir(results_dir: str) -> dict[str, Callable[[], str]]:
    """結果の置き場を results_dir にして，その場所を使うコマンドを組み立てる関数を返す."""
    remote_dir = "~/work/proj"

    def job_script() -> str:
        return build_job_script(
            remote_dir,
            "train1",
            ["python", "-m", "train"],
            uv_path="~/.local/bin/uv",
            server_name="Newton",
            gpu_index=0,
            env=build_job_env(0, [], git_commit="abc1234"),
            path_env={},
            results_dir=results_dir,
        )

    return {
        "probe": lambda: build_probe_command(
            remote_dir, results_dir=results_dir, observe_sec=3, sample_interval_ms=500
        ),
        "job_script": job_script,
        # run には検証済みのスクリプトを渡す（結果の置き場は run の側でも確かめる）
        "run": lambda: build_run_command(remote_dir, "train1", "true", results_dir=results_dir),
        "log_exists": lambda: build_log_exists_command(
            remote_dir, "train1", results_dir=results_dir
        ),
        "logs": lambda: build_logs_command(
            remote_dir, "train1", results_dir=results_dir, lines=50, follow=False
        ),
        "kill": lambda: build_kill_command(remote_dir, "train1", results_dir=results_dir),
        "pull_list": lambda: build_pull_list_command(
            remote_dir, "20261119-120000_x_abc1234", results_dir=results_dir
        ),
        "pull_tar": lambda: build_pull_tar_command(remote_dir, results_dir=results_dir),
    }


def _commands_with_results_dir(results_dir: str) -> dict[str, str]:
    """結果の置き場を results_dir にして，その場所を使うコマンドを一通り組み立てる."""
    return {kind: build() for kind, build in _builders_with_results_dir(results_dir).items()}


# ログの場所を含むコマンドと，結果の置き場（の下の実験 ID）へ移動するコマンド
_LOG_KINDS = ["probe", "job_script", "run", "log_exists", "logs", "kill"]
_PULL_KINDS = ["pull_list", "pull_tar"]


class TestResultsDirInCommands:
    @pytest.mark.parametrize("kind", _LOG_KINDS + _PULL_KINDS)
    def test_changed_results_dir_leaves_no_runs(self, kind: str) -> None:
        """SPEC_02「`results`」: dir を変えると，サーバのコマンドに runs の決め打ちが残らない."""
        command = _commands_with_results_dir("zzout/store")[kind]
        assert "runs" not in command
        assert "zzout/store" in command

    @pytest.mark.parametrize("kind", _LOG_KINDS)
    def test_log_dir_is_under_results_dir(self, kind: str) -> None:
        """SPEC_03「run」: ログは <remote_dir>/<結果の置き場>/_remote_logs/ に置く."""
        command = _commands_with_results_dir("output/runs")[kind]
        assert "output/runs/_remote_logs" in command

    def test_job_log_path_follows_results_dir(self) -> None:
        """SPEC_02「`results`」: ジョブのログは <dir>/_remote_logs/<ジョブ名>.log."""
        assert (
            job_log_path("train1", results_dir="output/runs")
            == "output/runs/_remote_logs/train1.log"
        )

    def test_pull_commands_cd_into_results_dir(self) -> None:
        """SPEC_03「pull」: 対象はサーバの <remote_dir>/<結果の置き場>/<RUN_ID>/ の下."""
        commands = _commands_with_results_dir("output/runs")
        for kind in _PULL_KINDS:
            tokens = shlex.split(commands[kind])
            assert tokens[:2] == ["cd", "$HOME/work/proj/output/runs"], kind

    @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`", "o|p&q"])
    def test_results_dir_is_one_word_in_pull_commands(self, results_dir: str) -> None:
        """SPEC_01「名前と値の検証」.

        結果の置き場は引用され，空白や特殊文字を含んでも 1 語で渡る.
        """
        commands = _commands_with_results_dir(results_dir)
        for kind in _PULL_KINDS:
            tokens = shlex.split(commands[kind])
            assert tokens[:2] == ["cd", f"$HOME/work/proj/{results_dir}"], kind

    @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`"])
    def test_results_dir_is_one_word_in_log_commands(self, results_dir: str) -> None:
        """SPEC_01「名前と値の検証」: ログの場所も引用され，1 語のまま渡る."""
        commands = _commands_with_results_dir(results_dir)
        log = f"{results_dir}/_remote_logs/train1.log"
        run_tokens = shlex.split(commands["run"])
        mkdir = run_tokens.index("mkdir")
        assert run_tokens[mkdir : mkdir + 3] == ["mkdir", "-p", f"{results_dir}/_remote_logs"]
        assert log in shlex.split(commands["log_exists"])
        assert log in shlex.split(commands["logs"])
        # kill は probe と同じ式（remote_dir 基準の絶対の形）でログを確かめる・書く
        assert f"$HOME/work/proj/{log}" in shlex.split(commands["kill"])
        # ジョブのスクリプトは，ログの場所を 1 語の変数に入れてから使う
        # （shlex.split は区切りの ; を語に付けたまま返すため，末尾の ; を除いて比べる）
        script_tokens = [t.removesuffix(";") for t in shlex.split(commands["job_script"])]
        assert f"log={log}" in script_tokens
        probe_tokens = shlex.split(commands["probe"])
        assert any(
            t.startswith(f"$HOME/work/proj/{results_dir}/_remote_logs/") for t in probe_tokens
        )

    @pytest.mark.parametrize(
        "results_dir",
        ["", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b", "a\x00b"],
    )
    @pytest.mark.parametrize("kind", _LOG_KINDS + _PULL_KINDS)
    def test_results_dir_outside_remote_dir_is_rejected(self, results_dir: str, kind: str) -> None:
        """SPEC_01「安全の枠」.

        remote_dir の外を指す結果の置き場では，サーバのコマンドを組み立てない.
        """
        with pytest.raises(ValueError):
            _builders_with_results_dir(results_dir)[kind]()


# ---------------------------------------------------------------------------
# run.exclude_groups の組み立て（SPEC_02「`exclude_groups` の書き方」，SPEC_03「run」）
# ---------------------------------------------------------------------------


def _script_with_groups(
    groups: object, *, gpu_index: int | None = 0, command: list[str] | None = None
) -> str:
    return build_job_script(
        "~/work/DemoProject",
        "train1",
        command or ["demo-train", "--config", "c.yaml"],
        uv_path="~/.local/bin/uv",
        server_name="Newton",
        gpu_index=gpu_index,
        env=build_job_env(gpu_index, [], git_commit="abc1234"),
        path_env={},
        results_dir="runs",
        exclude_groups=groups,  # type: ignore[arg-type]
    )


def _log_display_words(script: str) -> list[str]:
    """ジョブのログの開始行に出るコマンドの表示を，語に分けて返す（`uv` 以降）."""
    tokens = shlex.split(script)
    display = tokens[tokens.index("$(hostname)") + 1]
    words = shlex.split(display)
    return words[words.index("uv") :]


class TestExcludeGroupsInJobScript:
    @pytest.mark.parametrize(
        ("groups", "options"),
        [
            (["remote"], ["--no-group", "remote"]),
            (["remote", "dev.tools"], ["--no-group", "remote", "--no-group", "dev.tools"]),
            (["dev.tools", "remote"], ["--no-group", "dev.tools", "--no-group", "remote"]),
        ],
    )
    def test_no_group_options_come_right_after_uv_run_in_order(
        self, groups: list[str], options: list[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: uv run の直後・コマンドより前に書いた順で付く."""
        command = ["demo-train", "--config", "c.yaml"]
        assert _uv_run_args(_script_with_groups(groups, command=command)) == [*options, *command]

    @pytest.mark.parametrize("groups", [(), []])
    def test_empty_list_adds_nothing(self, groups: object) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 空なら何も付かない（引数無しと同じ）."""
        assert _script_with_groups(groups) == _script(0, ["demo-train", "--config", "c.yaml"])
        assert "--no-group" not in shlex.split(_script_with_groups(groups))

    def test_no_group_in_user_command_stays_in_command(self) -> None:
        """SPEC_02「`exclude_groups` の書き方」: コマンド本体の `--no-group` は本体の側に残る."""
        command = ["demo-train", "--no-group", "x"]
        args = _uv_run_args(_script_with_groups(["remote"], command=command))
        assert args == ["--no-group", "remote", *command]

    @pytest.mark.parametrize("gpu_index", [0, None])
    def test_added_for_gpu_and_cpu_jobs(self, gpu_index: int | None) -> None:
        """SPEC_02「`exclude_groups` の書き方」: `--cpu` のジョブにも同じように付く."""
        args = _uv_run_args(_script_with_groups(["remote"], gpu_index=gpu_index))
        assert args[:2] == ["--no-group", "remote"]

    @pytest.mark.parametrize("groups", [["remote"], ["remote", "dev.tools"], []])
    def test_log_header_display_matches_actual_command(self, groups: list[str]) -> None:
        """SPEC_02「`exclude_groups` の書き方」: ログの開始行の表示も実際と同じ."""
        script = _script_with_groups(groups)
        assert _log_display_words(script) == ["uv", "run", *_uv_run_args(script)]

    @pytest.mark.parametrize("name", ["-x", "--frozen", "a b", "x;rm", "$(id)", "remote\n", "", 1])
    def test_invalid_name_is_rejected_by_builder(self, name: object) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 組み立ての側でも名前を確かめる."""
        with pytest.raises(ValueError):
            _script_with_groups(["remote", name])

    def test_single_string_instead_of_list_is_rejected(self) -> None:
        """SPEC_02「`run`」: 一覧の代わりに 1 つの文字列を渡すと組み立てない."""
        with pytest.raises(ValueError):
            _script_with_groups("remote")


# ---------------------------------------------------------------------------
# kill の対象をこのプロジェクトのジョブに限る（SPEC_03「logs・kill」）
# ---------------------------------------------------------------------------

# 偽の tmux．本物の tmux を呼ばないため，呼ばれた引数を自分の隣のファイルに記録するだけにする．
# has-session は，隣に session_exists のファイルがあれば成功する．
_FAKE_TMUX = """#!/bin/sh
here=$(dirname "$0")
echo "$*" >> "$here/calls.log"
case "$1" in
  has-session) [ -f "$here/session_exists" ] ;;
  kill-session) echo "$*" >> "$here/killed.log" ;;
  *) exit 99 ;;
esac
"""


def _bash_or_skip(tmp_path: Path) -> str:
    """偽の tmux を使える bash を返す．無い・使えない環境では飛ばす.

    Windows では Git for Windows の bash を想定する（`tmp_path.as_posix()` の `C:/...` を扱える）．
    WSL の bash 等，手元のパスを扱えないものは飛ばす（Linux の CI で実行される）．
    """
    bash = shutil.which("bash")
    if bash is None:
        pytest.skip("bash が無い環境")
    probe = subprocess.run(
        [bash, "-c", '[ -d "$1" ]', "bash", tmp_path.as_posix()],
        capture_output=True,
        timeout=30,
        check=False,
    )
    if probe.returncode != 0:
        pytest.skip(f"この bash では手元のパスを扱えない: {bash}")
    return bash


class _KillSandbox:
    """`tmp_path` の中で，偽の tmux を PATH の先頭に置いて kill のコマンドを実行する."""

    def __init__(self, tmp_path: Path) -> None:
        tmp_path.mkdir(parents=True, exist_ok=True)
        self.bash = _bash_or_skip(tmp_path)
        self.root = tmp_path
        self.bin = tmp_path / "fakebin"
        self.bin.mkdir()
        tmux = self.bin / "tmux"
        tmux.write_bytes(_FAKE_TMUX.encode())
        tmux.chmod(0o755)

    def project(self, name: str) -> Path:
        """`remote_dir` に使うフォルダのパス（作らない）."""
        return self.root / name

    def write_log(self, remote_dir: Path, results_dir: str, name: str, text: str) -> Path:
        log = remote_dir / results_dir / "_remote_logs" / f"{name}.log"
        log.parent.mkdir(parents=True, exist_ok=True)
        log.write_bytes(text.encode())
        return log

    def set_session(self, exists: bool) -> None:
        flag = self.bin / "session_exists"
        if exists:
            flag.write_bytes(b"")
        elif flag.exists():
            flag.unlink()

    def run(self, remote_dir: Path, name: str = "train1", *, results_dir: str = "runs") -> int:
        command = build_kill_command(remote_dir.as_posix(), name, results_dir=results_dir)
        # PATH は子プロセスの中でだけ変える（$PWD は Windows の bash でも /c/... の形になる）
        result = subprocess.run(
            [self.bash, "-c", 'PATH="$PWD/fakebin:$PATH"; export PATH; ' + command],
            cwd=self.root,
            capture_output=True,
            timeout=60,
            check=False,
        )
        # 本物ではなく偽の tmux が呼ばれたこと（has-session は必ず最初に呼ばれる）
        calls_log = self.bin / "calls.log"
        calls = calls_log.read_text(encoding="utf-8").splitlines() if calls_log.exists() else []
        assert calls and calls[0].startswith("has-session"), result.stderr
        return result.returncode

    @property
    def killed(self) -> list[str]:
        log = self.bin / "killed.log"
        return log.read_text(encoding="utf-8").splitlines() if log.exists() else []


@pytest.fixture
def kill_sandbox(tmp_path: Path) -> _KillSandbox:
    return _KillSandbox(tmp_path)


class TestKillCommandInShell:
    """組み立てた kill のコマンドを，偽の tmux を置いた bash で実際に動かす."""

    def test_no_session_exits_nonzero_without_kill(self, kill_sandbox: _KillSandbox) -> None:
        """SPEC_03「logs・kill」: セッションが無いときは 0 以外で終わる（止めない）."""
        remote = kill_sandbox.project("proj")
        log = kill_sandbox.write_log(remote, "runs", "train1", "start\n")
        kill_sandbox.set_session(False)
        assert kill_sandbox.run(remote) == EXIT_NO_SESSION
        assert kill_sandbox.killed == []
        assert log.read_bytes() == b"start\n"

    @pytest.mark.parametrize(
        ("other_project", "other_results_dir"),
        [
            (None, None),  # ログがどこにも無い（手で作ったセッション）
            ("other", "runs"),  # 別のプロジェクトに同じ名前のログがある
            ("proj", "output/runs"),  # 同じプロジェクトの別の結果の置き場にある
        ],
    )
    def test_session_without_log_is_not_killed(
        self,
        kill_sandbox: _KillSandbox,
        other_project: str | None,
        other_results_dir: str | None,
    ) -> None:
        """SPEC_03「logs・kill」: セッションがあっても，このプロジェクトのログが無ければ止めない."""
        remote = kill_sandbox.project("proj")
        remote.mkdir()
        if other_project is not None and other_results_dir is not None:
            kill_sandbox.write_log(
                kill_sandbox.project(other_project), other_results_dir, "train1", "x\n"
            )
        kill_sandbox.set_session(True)
        assert kill_sandbox.run(remote, results_dir="runs") == EXIT_NOT_JOB
        assert kill_sandbox.killed == []
        assert not (remote / "runs" / "_remote_logs" / "train1.log").exists()

    def test_log_in_default_dir_does_not_count_for_other_results_dir(
        self, kill_sandbox: _KillSandbox
    ) -> None:
        """SPEC_03「logs・kill」: 結果の置き場が output/runs なら，runs の下のログでは止めない."""
        remote = kill_sandbox.project("proj")
        kill_sandbox.write_log(remote, "runs", "train1", "x\n")
        kill_sandbox.set_session(True)
        assert kill_sandbox.run(remote, results_dir="output/runs") == EXIT_NOT_JOB
        assert kill_sandbox.killed == []
        assert not (remote / "output").exists()

    @pytest.mark.parametrize("other_log", [False, True])
    def test_missing_remote_dir_is_not_killed(
        self, kill_sandbox: _KillSandbox, other_log: bool
    ) -> None:
        """SPEC_03「logs・kill」: remote_dir が無いときは，ログを確かめられないので止めない."""
        remote = kill_sandbox.project("proj")
        if other_log:
            kill_sandbox.write_log(kill_sandbox.project("other"), "runs", "train1", "x\n")
        kill_sandbox.set_session(True)
        assert kill_sandbox.run(remote) == EXIT_REMOTE_DIR_MISSING
        assert kill_sandbox.killed == []
        assert not remote.exists()

    def test_job_is_killed_and_log_appended(self, kill_sandbox: _KillSandbox) -> None:
        """SPEC_03「logs・kill」: ジョブ（ログのあるセッション）は止め，ログに止めた旨を追記する."""
        remote = kill_sandbox.project("proj")
        log = kill_sandbox.write_log(remote, "runs", "train1", "=== start\nepoch 1\n")
        kill_sandbox.set_session(True)
        assert kill_sandbox.run(remote) == 0
        assert kill_sandbox.killed == ["kill-session -t =train1"]
        text = log.read_text(encoding="utf-8")
        assert text.startswith("=== start\nepoch 1\n")
        added = text.removeprefix("=== start\nepoch 1\n").splitlines()
        assert len(added) == 1 and "killed" in added[0]

    def test_refusals_have_distinct_nonzero_exit_codes(self, tmp_path: Path) -> None:
        """SPEC_03「logs・kill」: 無い・置き場が無い・ログが無いを，手元で出し分けられる."""
        codes = []
        for case in ("no_session", "no_remote_dir", "no_log"):
            sandbox = _KillSandbox(tmp_path / case)
            remote = sandbox.project("proj")
            if case == "no_log":
                remote.mkdir()
            sandbox.set_session(case != "no_session")
            codes.append(sandbox.run(remote))
            assert sandbox.killed == []
        assert 0 not in codes
        assert len(set(codes)) == 3


def _file_test_expr(command: str) -> str:
    """コマンドの中の `[ -f X ]` の X を返す（1 つだけあること）."""
    found = re.findall(r"\[ -f (.+?) \]", command)
    assert len(found) == 1, command
    return found[0]


class TestKillMatchesStatus:
    @pytest.mark.parametrize("remote_dir", ["~/work/proj", "/srv/a b/proj"])
    @pytest.mark.parametrize("results_dir", ["runs", "output/runs"])
    def test_kill_checks_the_same_log_as_probe(self, remote_dir: str, results_dir: str) -> None:
        """SPEC_03「logs・kill」: kill がジョブと見なすログは，status（probe）と同じパスである."""
        probe = build_probe_command(
            remote_dir, results_dir=results_dir, observe_sec=0, sample_interval_ms=500
        )
        kill = build_kill_command(remote_dir, "train1", results_dir=results_dir)
        probe_log = _file_test_expr(probe)
        assert '"$s"' in probe_log
        assert _file_test_expr(kill) == probe_log.replace('"$s"', "train1")
        # シェルが解釈した後の 1 語としても，remote_dir・結果の置き場・名前から成る
        (kill_word,) = shlex.split(_file_test_expr(kill))
        expected_dir = remote_dir.replace("~", "$HOME", 1)
        assert kill_word == f"{expected_dir}/{results_dir}/_remote_logs/train1.log"

    @pytest.mark.parametrize("results_dir", ["runs", "output/runs"])
    def test_checks_come_before_kill_session(self, results_dir: str) -> None:
        """SPEC_03「logs・kill」: セッション → remote_dir → ログの順に確かめ，その後に止める."""
        command = build_kill_command("~/work/proj", "train1", results_dir=results_dir)
        session = command.index("tmux has-session")
        directory = command.index("[ -d ")
        log = command.index("[ -f ")
        kill = command.index("tmux kill-session")
        assert session < directory < log < kill
        assert command.count("kill-session") == 1


# ---------------------------------------------------------------------------
# pull の tar に渡すパスの一覧（build_pull_tar_input）
# ---------------------------------------------------------------------------


class TestBuildPullTarInput:
    def test_empty_list_gives_empty_bytes(self) -> None:
        assert build_pull_tar_input([]) == b""

    def test_each_path_is_followed_by_one_nul(self) -> None:
        paths = ["run1/metrics.json", "run1/figs/a.png", "run1/log.txt"]
        data = build_pull_tar_input(paths)
        assert data.count(b"\0") == len(paths)
        assert data.endswith(b"\0")
        assert data.split(b"\0")[:-1] == [p.encode() for p in paths]

    @pytest.mark.parametrize(
        "path",
        ["a b.txt", "a;rm -rf x", "$(id)", "a\nb", "'q'", '"q"', "`x`", "-flag"],
        ids=repr,
    )
    def test_special_characters_are_passed_as_is(self, path: str) -> None:
        """名前はシェルに埋め込まず，そのままのバイト列で渡す."""
        assert build_pull_tar_input([path]) == path.encode() + b"\0"

    def test_japanese_name_is_utf8(self) -> None:
        assert build_pull_tar_input(["結果/図.png"]) == "結果/図.png".encode() + b"\0"

    def test_surrogateescape_name_is_restored_to_original_bytes(self) -> None:
        """surrogateescape で読んだ（UTF-8 でない）名前は，元のバイト列に戻る."""
        raw = b"run1/\xff\xfe.bin"
        name = raw.decode("utf-8", "surrogateescape")
        assert build_pull_tar_input([name]) == raw + b"\0"

    def test_order_is_kept(self) -> None:
        data = build_pull_tar_input(["b", "a", "c"])
        assert data == b"b\0a\0c\0"


# ---------------------------------------------------------------------------
# ls: サーバに残っているものの一覧（SPEC_03「ls」）
# ---------------------------------------------------------------------------

LS_RUN_A = "20261119-120000_demo_abc1234"
LS_RUN_B = "20261120-090000_demo_def5678"


def _cd_targets(command: str) -> list[str]:
    """シェルが解釈した後の，`cd` の引数（1 語）の一覧."""
    words = shlex.split(command)
    return [words[i + 1] for i, w in enumerate(words) if w == "cd"]


class TestBuildLsCommandString:
    @pytest.mark.parametrize(
        "remote_dir",
        ["~/work/proj", "/srv/a b/proj", "/srv/x;y $(id)/p", "/srv/it's/p", "/srv/`id`|&/p"],
    )
    def test_remote_dir_is_quoted_as_one_word(self, remote_dir: str) -> None:
        """SPEC_03「ls」: remote_dir は引用して埋め込む（空白・特殊文字でも 1 語）."""
        command = build_ls_command(remote_dir, results_dir="runs")
        assert remote_dir.replace("~", "$HOME", 1) in _cd_targets(command)

    @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`", "o|p&q"])
    def test_results_dir_is_quoted_as_one_word(self, results_dir: str) -> None:
        """SPEC_01「名前と値の検証」: 結果の置き場も引用して 1 語で渡る."""
        targets = _cd_targets(build_ls_command("~/work/proj", results_dir=results_dir))
        assert results_dir in targets
        assert f"{results_dir}/_remote_logs" in targets

    @pytest.mark.parametrize(
        "results_dir",
        ["", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b", "a\x00b", ".."],
    )
    def test_results_dir_outside_remote_dir_is_rejected(self, results_dir: str) -> None:
        """SPEC_01「安全の枠」: remote_dir の外を指す結果の置き場では組み立てない."""
        with pytest.raises(ValueError):
            build_ls_command("~/work/proj", results_dir=results_dir)

    @pytest.mark.parametrize("results_dir", ["runs", "output/runs"])
    @pytest.mark.parametrize("remote_dir", ["~/work/proj", "/srv/a b/proj"])
    def test_does_not_delete_or_write(self, remote_dir: str, results_dir: str) -> None:
        """SPEC_03「ls」: 一覧と大きさの取得だけ．消す・書き込む・中身を読むコマンドを含まない."""
        command = build_ls_command(remote_dir, results_dir=results_dir)
        forbidden_words = [
            "rm", "rmdir", "mv", "cp", "touch", "mkdir", "tee", "truncate", "dd", "ln",
            "chmod", "chown", "install", "cat", "head", "tail", "less", "sha256sum", "md5sum",
            "tar", "xargs", "eval", "source", "unlink", "shred",
        ]  # fmt: skip
        for word in forbidden_words:
            assert not re.search(rf"(^|[\s;(|&]){word}(\s|$)", command), word
        # 書き込むリダイレクトは，標準エラーを捨てる 2>/dev/null だけ
        assert ">" not in command.replace("2>/dev/null", "")
        # tmux は一覧（ls）だけを呼ぶ
        assert re.findall(r"tmux\s+(\S+)", command) == ["ls"]
        assert "kill-session" not in command and "send-keys" not in command

    def test_find_and_du_do_not_follow_links_or_act(self) -> None:
        """SPEC_03「ls」: find・du はリンクをたどらない．find で消す・実行するをしない."""
        command = build_ls_command("~/work/proj", results_dir="runs")
        for option in ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-follow", "-fprint"]:
            assert option not in command
        assert not re.search(r"\bfind\s+-[LHP]\b", command)
        assert not re.search(r"\bdu\s+[^;|]*(-L\b|-D\b|--dereference)", command)
        assert re.search(r"\bfind\b", command) and re.search(r"\bdu\b", command)


# 偽の tmux（ls 用）．呼ばれた引数を隣のファイルに記録し，`ls` だけに答える．
# 隣に tmux_rc があればその値で失敗し（1: サーバが動いていない，127: tmux が無い），
# sessions があればその中身をセッションの一覧として出す．
_FAKE_TMUX_LS = """#!/bin/sh
here=$(dirname "$0")
echo "$*" >> "$here/calls.log"
case "$1" in
  ls)
    rc=0
    if [ -f "$here/tmux_rc" ]; then rc=$(cat "$here/tmux_rc"); fi
    if [ "$rc" != 0 ]; then echo "no server running" >&2; exit "$rc"; fi
    if [ -f "$here/sessions" ]; then cat "$here/sessions"; fi
    ;;
  *) exit 99 ;;
esac
"""


def _snapshot(root: Path) -> dict[str, tuple]:
    """root の下の一覧と内容（リンクはたどらない）."""
    if not os.path.lexists(root):
        return {}
    found: dict[str, tuple] = {}
    for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
        for name in [*dirnames, *filenames]:
            path = Path(dirpath) / name
            rel = path.relative_to(root).as_posix()
            st = os.lstat(path)
            if path.is_symlink():
                found[rel] = ("link", os.readlink(path))
            elif path.is_dir():
                found[rel] = ("dir", st.st_mode)
            else:
                found[rel] = ("file", path.read_bytes(), st.st_mtime_ns, st.st_mode)
    return found


class _LsSandbox:
    """`tmp_path` の中で，偽の tmux を PATH の先頭に置いて ls のコマンドを実行する."""

    def __init__(self, tmp_path: Path) -> None:
        tmp_path.mkdir(parents=True, exist_ok=True)
        self.bash = _bash_or_skip(tmp_path)
        self.root = tmp_path
        self.bin = tmp_path / "fakebin"
        self.bin.mkdir()
        tmux = self.bin / "tmux"
        tmux.write_bytes(_FAKE_TMUX_LS.encode())
        tmux.chmod(0o755)
        self.outside = tmp_path / "outside"
        self.outside.mkdir()
        self.remote = tmp_path / "srv" / "proj"
        self.last_stdout = b""

    def set_sessions(self, names: list[str]) -> None:
        (self.bin / "sessions").write_bytes("".join(f"{n}\n" for n in names).encode())

    def set_tmux_rc(self, rc: int) -> None:
        (self.bin / "tmux_rc").write_bytes(f"{rc}\n".encode())

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

    def write(self, rel: str, data: bytes = b"x", *, base: Path | None = None) -> Path:
        path = (base or self.remote) / rel if rel else (base or self.remote)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
        return path

    def run_raw(self, remote: Path | None = None, *, results_dir: str = "runs") -> bytes:
        remote = self.remote if remote is None else remote
        command = build_ls_command(remote.as_posix(), results_dir=results_dir)
        # PATH は子プロセスの中でだけ変える
        result = subprocess.run(
            [self.bash, "-c", 'PATH="$PWD/fakebin:$PATH"; export PATH; ' + command],
            cwd=self.root,
            capture_output=True,
            timeout=120,
            check=False,
        )
        # 置き場が無くても 0 で終わる（状態は出力で区別する）
        assert result.returncode == 0, result.stderr
        # 本物ではなく偽の tmux だけが，一覧（ls）だけで呼ばれたこと
        assert all(call.startswith("ls") for call in self.tmux_calls())
        self.last_stdout = result.stdout
        return result.stdout

    def run(self, remote: Path | None = None, *, results_dir: str = "runs") -> RemoteListing:
        return parse_ls_output(self.run_raw(remote, results_dir=results_dir))


@pytest.fixture
def ls_sandbox(tmp_path: Path) -> _LsSandbox:
    return _LsSandbox(tmp_path)


@pytest.fixture
def links() -> Iterator[LinkFactory]:
    factory = LinkFactory()
    yield factory
    factory.cleanup()


def _run_names(listing: RemoteListing) -> list[str]:
    return [entry.run_id for entry in listing.run_dirs]


def _entry(listing: RemoteListing, run_id: str) -> RunDirEntry:
    (found,) = [entry for entry in listing.run_dirs if entry.run_id == run_id]
    return found


class TestLsCommandInShell:
    """組み立てた ls のコマンドを，偽のフォルダと偽の tmux を置いた bash で実際に動かす."""

    def test_missing_remote_dir_means_nothing_left(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: remote_dir が無いときは「何も残っていない」．何も作らない."""
        listing = ls_sandbox.run()
        assert listing == RemoteListing(remote_dir_exists=False)
        assert not os.path.lexists(ls_sandbox.remote)

    def test_empty_remote_dir(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: 結果の置き場・ログの置き場が無ければ 0 件．.venv が無ければ 0."""
        ls_sandbox.remote.mkdir(parents=True)
        listing = ls_sandbox.run()
        assert listing.remote_dir_exists
        assert not listing.results_dir_exists and not listing.logs_dir_exists
        assert listing.run_dirs == () and listing.job_logs == ()
        assert listing.venv_bytes == 0
        assert listing.complete
        assert _snapshot(ls_sandbox.remote) == {}

    def test_results_dir_without_logs_dir(self, ls_sandbox: _LsSandbox) -> None:
        ls_sandbox.write(f"runs/{LS_RUN_A}/metrics.json")
        listing = ls_sandbox.run()
        assert listing.results_dir_exists and not listing.logs_dir_exists
        assert _run_names(listing) == [LS_RUN_A]
        assert listing.job_logs == ()

    def test_logs_dir_only(self, ls_sandbox: _LsSandbox) -> None:
        """結果の置き場の中にログの置き場だけがある（実験フォルダは 0 件）."""
        ls_sandbox.write("runs/_remote_logs/train1.log", b"abc")
        listing = ls_sandbox.run()
        assert listing.results_dir_exists and listing.logs_dir_exists
        assert listing.run_dirs == ()
        assert listing.other_in_results == 0
        assert [(log.name, log.size_bytes) for log in listing.job_logs] == [("train1", 3)]

    def test_counts_nested_files_but_not_folders(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: 件数は，フォルダの下のフォルダ以外のもの（入れ子の中も数える）."""
        run = f"runs/{LS_RUN_A}"
        ls_sandbox.write(f"{run}/a.txt")
        ls_sandbox.write(f"{run}/sub/b.txt")
        ls_sandbox.write(f"{run}/sub/deep/c.txt")
        (ls_sandbox.remote / run / "sub" / "empty").mkdir()
        (ls_sandbox.remote / f"runs/{LS_RUN_B}").mkdir(parents=True)
        listing = ls_sandbox.run()
        assert _entry(listing, LS_RUN_A).file_count == 3
        assert _entry(listing, LS_RUN_B).file_count == 0
        assert listing.complete

    def test_nasty_file_names_only_change_count_and_never_appear(
        self, ls_sandbox: _LsSandbox
    ) -> None:
        """SPEC_03「ls」: 名前に空白・$(...)・引用符があっても件数だけが合う．名前は出さない."""
        names = [
            "secretalpha one.txt",
            "secretbeta$(touch pwned).txt",
            "secretgamma'q.txt",
            "secretdelta;rm -rf x.txt",
            "secretepsilon`id`.txt",
            ".secrethidden",
            "-secretdash",
        ]
        if sys.platform != "win32":
            names += ["secretzeta\nnewline.txt", 'secreteta"dq.txt', "secrettheta\\bs.txt"]
        for name in names:
            ls_sandbox.write(f"runs/{LS_RUN_A}/{name}")
            ls_sandbox.write(f"runs/{LS_RUN_A}/nested dir/{name}")
        before = _snapshot(ls_sandbox.root / "srv")
        listing = ls_sandbox.run()
        assert _entry(listing, LS_RUN_A).file_count == 2 * len(names)
        out = ls_sandbox.last_stdout
        for word in [b"secret", b"newline", b"nested", b"pwned", b".txt"]:
            assert word not in out
        assert not list(ls_sandbox.root.rglob("pwned"))
        assert _snapshot(ls_sandbox.root / "srv") == before

    def test_sizes_are_disk_usage(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: 実験フォルダ・remote_dir・.venv の大きさ（ディスクの上の量）."""
        ls_sandbox.write(f"runs/{LS_RUN_A}/big.bin", b"\1" * (300 * 1024))
        ls_sandbox.write(".venv/lib/pkg.bin", b"\2" * (200 * 1024))
        listing = ls_sandbox.run()
        run_size = _entry(listing, LS_RUN_A).size_bytes
        assert run_size >= 300 * 1024
        assert listing.venv_bytes >= 200 * 1024
        assert listing.total_bytes >= run_size + listing.venv_bytes
        assert listing.sizes_complete

    def test_non_run_entries_in_results_are_other(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: 実験 ID の形でない名前・フォルダでないものは「その他」（件数だけ）."""
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
        ls_sandbox.write("runs/notes.txt")
        # 名前は実験 ID の形でも，フォルダでない
        ls_sandbox.write(f"runs/{LS_RUN_B}", b"file with run id name")
        bad = [".hidden", "bad name", "x..y", "-dash", "$(id)", "_under"]
        if sys.platform != "win32":
            bad += ["..dots", "trail.", "ctl\x1b[31m", "nl\nname", "nul", "con.txt"]
            bad.append(b"bad\xffutf8".decode("utf-8", "surrogateescape"))
        for name in bad:
            ls_sandbox.write(f"runs/{name}/a.txt")
        ls_sandbox.write("runs/_remote_logs/train1.log")
        listing = ls_sandbox.run()
        assert _run_names(listing) == [LS_RUN_A]
        assert listing.other_in_results == 2 + len(bad)

    def test_remote_logs_is_not_a_run_dir(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: ログの置き場は実験フォルダに含めない（その他にも数えない）."""
        ls_sandbox.write("runs/_remote_logs/train1.log")
        listing = ls_sandbox.run()
        assert listing.run_dirs == ()
        assert listing.other_in_results == 0

    def test_logs(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: `<名前>.log` の通常のファイルだけがログ．それ以外は「その他」."""
        ls_sandbox.write("runs/_remote_logs/train1.log", b"a" * 123)
        ls_sandbox.write("runs/_remote_logs/old.log", b"")
        ls_sandbox.write("runs/_remote_logs/readme.txt")
        ls_sandbox.write("runs/_remote_logs/dir.log/inner.log")  # x.log という名前のフォルダ
        ls_sandbox.write("runs/_remote_logs/bad name.log")
        ls_sandbox.write("runs/_remote_logs/a.b.log")
        ls_sandbox.write("runs/_remote_logs/.hidden.log")
        listing = ls_sandbox.run()
        logs = {log.name: log.size_bytes for log in listing.job_logs}
        assert logs == {"train1": 123, "old": 0}
        assert listing.other_in_logs == 5
        assert all(not log.running for log in listing.job_logs)

    def test_running_only_when_session_and_log(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: セッションがあって，ログがあるものだけが実行中."""
        for name in ["train1", "old"]:
            ls_sandbox.write(f"runs/_remote_logs/{name}.log")
        ls_sandbox.set_sessions(["train1", "manual", "other-project"])
        listing = ls_sandbox.run()
        running = {log.name: log.running for log in listing.job_logs}
        assert running == {"train1": True, "old": False}
        assert ls_sandbox.tmux_calls() and ls_sandbox.tmux_calls()[0].startswith("ls")

    def test_session_with_log_in_other_results_dir_is_not_running(
        self, ls_sandbox: _LsSandbox
    ) -> None:
        ls_sandbox.write("runs/_remote_logs/train1.log")
        ls_sandbox.write("output/runs/_remote_logs/eval1.log")
        ls_sandbox.set_sessions(["train1"])
        listing = ls_sandbox.run(results_dir="output/runs")
        assert [(log.name, log.running) for log in listing.job_logs] == [("eval1", False)]

    @pytest.mark.parametrize("tmux_rc", [1, 127])
    def test_tmux_failure_does_not_stop_script(self, ls_sandbox: _LsSandbox, tmux_rc: int) -> None:
        """tmux が無い（127）・サーバが動いていない（1）ときも止まらず，全部が停止中."""
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
        ls_sandbox.write("runs/_remote_logs/train1.log")
        ls_sandbox.set_sessions(["train1"])
        ls_sandbox.set_tmux_rc(tmux_rc)
        listing = ls_sandbox.run()
        assert _run_names(listing) == [LS_RUN_A]
        assert [(log.name, log.running) for log in listing.job_logs] == [("train1", False)]

    def test_nothing_changes(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: 何も消さない・書き込まない（前後でフォルダの一覧と内容が同じ）."""
        ls_sandbox.write(f"runs/{LS_RUN_A}/metrics.json", b"{}")
        ls_sandbox.write(f"runs/{LS_RUN_A}/sub/x.bin", b"\0\1\2")
        ls_sandbox.write(f"runs/{LS_RUN_B}/a.txt")
        ls_sandbox.write("runs/notes.txt", b"note")
        ls_sandbox.write("runs/_remote_logs/train1.log", b"=== start\n")
        ls_sandbox.write("runs/_remote_logs/readme.txt")
        ls_sandbox.write(".venv/lib/a.py", b"pass\n")
        ls_sandbox.write("src/main.py", b"print(1)\n")
        ls_sandbox.set_sessions(["train1"])

        def outside_fakebin() -> dict[str, tuple]:
            return {k: v for k, v in _snapshot(ls_sandbox.root).items() if "fakebin" not in k}

        before = outside_fakebin()
        ls_sandbox.run()
        assert outside_fakebin() == before

    @pytest.mark.parametrize(
        "dir_name", ["a b", "x;y $(touch pwned)", "it's", "`touch pwned`", "a&b|c"]
    )
    def test_remote_dir_with_special_characters(
        self, ls_sandbox: _LsSandbox, dir_name: str
    ) -> None:
        """SPEC_03「ls」: remote_dir は引用して埋め込む（特殊文字を含んでも，その場所を見る）."""
        if sys.platform == "win32" and "|" in dir_name:
            pytest.skip("Windows のファイル名に | は使えない")
        remote = ls_sandbox.root / "srv" / dir_name
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt", base=remote)
        listing = ls_sandbox.run(remote)
        assert _run_names(listing) == [LS_RUN_A]
        assert not list(ls_sandbox.root.rglob("pwned"))

    @pytest.mark.parametrize("results_dir", ["my res", "out $(touch pwned)/runs", "it's/x"])
    def test_results_dir_with_special_characters(
        self, ls_sandbox: _LsSandbox, results_dir: str
    ) -> None:
        ls_sandbox.write(f"{results_dir}/{LS_RUN_A}/a.txt")
        ls_sandbox.write(f"{results_dir}/_remote_logs/t1.log")
        listing = ls_sandbox.run(results_dir=results_dir)
        assert _run_names(listing) == [LS_RUN_A]
        assert [log.name for log in listing.job_logs] == ["t1"]
        assert not list(ls_sandbox.root.rglob("pwned"))

    def test_other_results_dir_is_used(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_02「`results`」: 結果の置き場が別の名前なら，その下だけを見る."""
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
        ls_sandbox.write(f"output/runs/{LS_RUN_B}/a.txt")
        listing = ls_sandbox.run(results_dir="output/runs")
        assert _run_names(listing) == [LS_RUN_B]

    @pytest.mark.parametrize("what", ["remote_dir", "results_dir", "logs_dir"])
    def test_place_that_is_a_file_is_unreadable(self, ls_sandbox: _LsSandbox, what: str) -> None:
        """SPEC_03「ls」: 置き場が在るのにフォルダでないときは，0 件とせず確認できない."""
        if what == "remote_dir":
            ls_sandbox.write("", b"file")
        elif what == "results_dir":
            ls_sandbox.write("runs", b"file")
        else:
            ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
            ls_sandbox.write("runs/_remote_logs", b"file")
        with pytest.raises(ValueError):
            ls_sandbox.run()

    def test_unreadable_folder_is_incomplete(self, ls_sandbox: _LsSandbox) -> None:
        """SPEC_03「ls」: 読めない場所があれば，数え切れなかった（complete が False）."""
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
        locked = ls_sandbox.remote / "runs" / LS_RUN_A / "locked"
        ls_sandbox.write("hidden.txt", base=locked)
        locked.chmod(0)
        try:
            if os.access(locked, os.R_OK | os.X_OK):
                pytest.skip("この環境では権限で読めないフォルダを作れない（Windows・root）")
            listing = ls_sandbox.run()
        finally:
            locked.chmod(0o755)
        entry = _entry(listing, LS_RUN_A)
        assert not entry.complete
        assert not listing.complete
        assert entry.file_count >= 1

    # --- リンク（作れない環境では飛ばす．CI の Linux で実行される） ---

    def test_link_with_run_id_name_in_results_is_other(
        self, ls_sandbox: _LsSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「ls」: 名前が実験 ID の形でも，リンクは実験フォルダとして扱わない."""
        target = ls_sandbox.outside / "real"
        ls_sandbox.write("a.txt", base=target)
        (ls_sandbox.remote / "runs").mkdir(parents=True)
        links.symlink(ls_sandbox.remote / "runs" / LS_RUN_A, target, is_dir=True)
        listing = ls_sandbox.run()
        assert listing.run_dirs == ()
        assert listing.other_in_results == 1

    def test_link_inside_run_dir_is_counted_once_without_target(
        self, ls_sandbox: _LsSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「ls」: 中のリンクは 1 件と数え，先の中身を数えない・大きさに入れない."""
        big = ls_sandbox.outside / "big"
        for i in range(5):
            ls_sandbox.write(f"f{i}.bin", b"\3" * (512 * 1024), base=big)
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
        links.symlink(ls_sandbox.remote / "runs" / LS_RUN_A / "data", big, is_dir=True)
        listing = ls_sandbox.run()
        entry = _entry(listing, LS_RUN_A)
        assert entry.file_count == 2
        assert entry.size_bytes < 2 * 1024 * 1024
        assert listing.total_bytes < 2 * 1024 * 1024

    def test_junction_with_run_id_name_in_results_is_other(
        self, ls_sandbox: _LsSandbox, links: LinkFactory
    ) -> None:
        """Windows のジャンクションも，リンクとして実験フォルダに数えない（Windows だけ）."""
        target = ls_sandbox.outside / "real"
        ls_sandbox.write("a.txt", base=target)
        (ls_sandbox.remote / "runs").mkdir(parents=True)
        links.junction(ls_sandbox.remote / "runs" / LS_RUN_A, target)
        listing = ls_sandbox.run()
        assert listing.run_dirs == ()
        assert listing.other_in_results == 1

    def test_junction_inside_run_dir_is_not_followed(
        self, ls_sandbox: _LsSandbox, links: LinkFactory
    ) -> None:
        big = ls_sandbox.outside / "big"
        for i in range(5):
            ls_sandbox.write(f"f{i}.bin", b"\3" * (512 * 1024), base=big)
        ls_sandbox.write(f"runs/{LS_RUN_A}/a.txt")
        links.junction(ls_sandbox.remote / "runs" / LS_RUN_A / "data", big)
        listing = ls_sandbox.run()
        entry = _entry(listing, LS_RUN_A)
        assert entry.file_count == 2
        assert entry.size_bytes < 2 * 1024 * 1024

    def test_venv_link_is_zero(self, ls_sandbox: _LsSandbox, links: LinkFactory) -> None:
        """SPEC_03「ls」: .venv がリンクなら大きさは 0（先をたどらない）."""
        big = ls_sandbox.outside / "venv"
        ls_sandbox.write("lib.bin", b"\4" * (1024 * 1024), base=big)
        ls_sandbox.remote.mkdir(parents=True)
        links.symlink(ls_sandbox.remote / ".venv", big, is_dir=True)
        listing = ls_sandbox.run()
        assert listing.venv_bytes == 0
        assert listing.total_bytes < 1024 * 1024

    def test_linked_file_in_logs_dir_is_other(
        self, ls_sandbox: _LsSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「ls」: ログの置き場のリンクのファイルは「その他」."""
        target = ls_sandbox.write("elsewhere.log", b"x" * 50, base=ls_sandbox.outside)
        ls_sandbox.write("runs/_remote_logs/train1.log")
        links.symlink(ls_sandbox.remote / "runs" / "_remote_logs" / "linked.log", target)
        ls_sandbox.set_sessions(["linked"])
        listing = ls_sandbox.run()
        assert [log.name for log in listing.job_logs] == ["train1"]
        assert listing.other_in_logs == 1

    def test_logs_dir_that_is_a_link_is_unreadable(
        self, ls_sandbox: _LsSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「ls」: ログの置き場そのものがリンクなら，確認できない."""
        target = ls_sandbox.outside / "logs"
        ls_sandbox.write("train1.log", base=target)
        (ls_sandbox.remote / "runs").mkdir(parents=True)
        links.symlink(ls_sandbox.remote / "runs" / "_remote_logs", target, is_dir=True)
        with pytest.raises(ValueError):
            ls_sandbox.run()


# ---------------------------------------------------------------------------
# clean: 実験フォルダのファイルの一覧と大きさ・ハッシュ（SPEC_03「clean」の手順 1）
# ---------------------------------------------------------------------------

CLEAN_RUN = "20261119-120000_demo_abc1234"

BAD_CLEAN_RUN_IDS = [
    "",
    "..",
    ".",
    "a/b",
    "../x",
    "-rf",
    "a;b",
    "$(x)",
    "`x`",
    "a b",
    f"{CLEAN_RUN}\n",
    "\nx",
    "x.",
    "x..y",
    "nul",
    "CON",
    "con.txt",
    "COM1",
    "a\x00b",
    "a\\b",
    "_remote_logs",
    "x" * 201,
]


def _cd_dash_targets(command: str) -> list[str]:
    """シェルが解釈した後の，`cd -- <引数>` の引数（1 語）の一覧."""
    words = shlex.split(command)
    return [words[i + 2] for i, w in enumerate(words[:-2]) if w == "cd" and words[i + 1] == "--"]


class TestBuildCleanListCommandString:
    @pytest.mark.parametrize("run_id", BAD_CLEAN_RUN_IDS)
    def test_bad_run_id_is_rejected_before_building(self, run_id: str) -> None:
        """SPEC_03「clean」: 埋め込むのは検証済みの RUN_ID だけ（組み立ての前に ValueError）."""
        with pytest.raises(ValueError):
            build_clean_list_command("~/work/proj", results_dir="runs", run_id=run_id)

    @pytest.mark.parametrize(
        "remote_dir",
        ["~/work/proj", "/srv/a b/proj", "/srv/x;y $(id)/p", "/srv/it's/p", "/srv/`id`|&/p"],
    )
    def test_remote_dir_is_quoted_as_one_word(self, remote_dir: str) -> None:
        command = build_clean_list_command(remote_dir, results_dir="runs", run_id=CLEAN_RUN)
        assert remote_dir.replace("~", "$HOME", 1) in _cd_dash_targets(command)

    @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`", "o|p&q"])
    def test_results_dir_is_quoted_as_one_word(self, results_dir: str) -> None:
        command = build_clean_list_command("~/w/p", results_dir=results_dir, run_id=CLEAN_RUN)
        assert f"./{results_dir}" in _cd_dash_targets(command)

    @pytest.mark.parametrize(
        "results_dir",
        ["", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b", "a\x00b", ".."],
    )
    def test_results_dir_outside_remote_dir_is_rejected(self, results_dir: str) -> None:
        with pytest.raises(ValueError):
            build_clean_list_command("~/w/p", results_dir=results_dir, run_id=CLEAN_RUN)

    @pytest.mark.parametrize("run_id", [CLEAN_RUN, "r1", "A.b_c-d"])
    def test_run_id_is_one_word_under_results_dir(self, run_id: str) -> None:
        command = build_clean_list_command("~/w/p", results_dir="runs", run_id=run_id)
        words = shlex.split(command)
        assert f"./{run_id}" in words
        # find の起点は実験フォルダだけ
        starts = [words[i + 1] for i, w in enumerate(words) if w == "find"]
        assert starts == [f"./{run_id}"]

    @pytest.mark.parametrize("results_dir", ["runs", "output/runs"])
    @pytest.mark.parametrize("remote_dir", ["~/work/proj", "/srv/a b/proj"])
    def test_does_not_delete_or_write(self, remote_dir: str, results_dir: str) -> None:
        """SPEC_03「clean」: 判定の段階では，一覧とハッシュの取得だけ．書き込み・削除をしない."""
        command = build_clean_list_command(remote_dir, results_dir=results_dir, run_id=CLEAN_RUN)
        forbidden_words = [
            "rm", "rmdir", "mv", "cp", "touch", "truncate", "tee", "dd", "ln", "mkdir",
            "chmod", "chown", "install", "unlink", "shred", "eval", "source", "xargs", "tar",
        ]  # fmt: skip
        for word in forbidden_words:
            assert not re.search(rf"(^|[\s;(|&'\"]){word}(\s|$)", command), word
        for option in ["-delete", "-execdir", "-ok", "-okdir", "-fprint", "-fls", "-fprintf"]:
            assert option not in command
        # 書き込むリダイレクトは，標準エラーを捨てる 2>/dev/null だけ
        assert ">" not in command.replace("2>/dev/null", "")

    def test_find_does_not_follow_links(self) -> None:
        command = build_clean_list_command("~/w/p", results_dir="runs", run_id=CLEAN_RUN)
        assert "-follow" not in command
        assert not re.search(r"\bfind\s+-[LH]\b", command)
        assert not re.search(r"\b(stat|sha256sum)\s+-L\b", command)
        assert "--dereference" not in command

    def test_hash_is_read_from_stdin_not_from_name(self) -> None:
        """名前を sha256sum の引数にしない（出力の形が名前で変わるため）."""
        command = build_clean_list_command("~/w/p", results_dir="runs", run_id=CLEAN_RUN)
        assert re.search(r"sha256sum\s*<", command)
        assert not re.search(r"sha256sum\s+[^<\s]", command)

    @pytest.mark.parametrize(
        "build",
        [
            lambda: build_clean_list_command("~/w/p", results_dir="runs", run_id=CLEAN_RUN),
            lambda: build_ls_command("~/w/p", results_dir="runs"),
        ],
        ids=["clean", "ls"],
    )
    def test_unsets_cdpath_before_cd(self, build: Callable[[], str]) -> None:
        """SPEC_03「clean」: 相対の cd が別の場所へ行かないよう，CDPATH を外してから動かす."""
        command = build()
        assert "unset CDPATH" in command
        assert command.index("unset CDPATH") < command.index("cd ")


class _CleanSandbox:
    """`tmp_path` の中の偽のサーバのフォルダで，clean の一覧のコマンドを bash で実際に動かす."""

    def __init__(self, tmp_path: Path) -> None:
        tmp_path.mkdir(parents=True, exist_ok=True)
        self.bash = _bash_or_skip(tmp_path)
        self.root = tmp_path
        self.outside = tmp_path / "outside"
        self.outside.mkdir()
        self.remote = tmp_path / "srv" / "proj"
        self.last_stdout = b""

    def run_dir(self, run_id: str = CLEAN_RUN, results_dir: str = "runs") -> Path:
        return self.remote / results_dir / run_id

    def write(self, rel: str, data: bytes = b"x", *, base: Path | None = None) -> Path:
        path = (base or self.run_dir()) / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
        return path

    def run_raw(
        self,
        run_id: str = CLEAN_RUN,
        *,
        remote: str | None = None,
        results_dir: str = "runs",
        env: dict[str, str] | None = None,
    ) -> bytes:
        remote_dir = self.remote.as_posix() if remote is None else remote
        command = build_clean_list_command(remote_dir, results_dir=results_dir, run_id=run_id)
        result = subprocess.run(
            [self.bash, "-c", command],
            cwd=self.root,
            capture_output=True,
            # FIFO 等で止まったときに，pytest の制限時間に頼らずに失敗させる
            timeout=60,
            check=False,
            env={**os.environ, **(env or {})},
        )
        # 実験フォルダが無くても 0 で終わる（状態は出力で区別する）
        assert result.returncode == 0, result.stderr
        self.last_stdout = result.stdout
        return result.stdout

    def run(self, run_id: str = CLEAN_RUN, **kwargs: object) -> RemoteRunListing:
        return parse_clean_output(self.run_raw(run_id, **kwargs), run_id)  # type: ignore[arg-type]


@pytest.fixture
def clean_sandbox(tmp_path: Path) -> _CleanSandbox:
    return _CleanSandbox(tmp_path)


def _sha(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def _files_of(listing: RemoteRunListing) -> dict[str, tuple[bool, int, str]]:
    return {f.rel_path: (f.regular, f.size_bytes, f.sha256) for f in listing.files}


class TestCleanListCommandInShell:
    def test_lists_nested_files_with_size_and_hash(self, clean_sandbox: _CleanSandbox) -> None:
        """SPEC_03「clean」の手順 1: 全ファイルの相対パス・大きさ・SHA-256（入れ子の中も）."""
        contents = {
            "empty.bin": b"",
            "one.txt": b"a",
            "sub/two.txt": b"bc",
            "sub/deep/er/big.bin": bytes(range(256)) * (3 * 4096 + 7),
            ".hidden": b"h",
        }
        for rel, data in contents.items():
            clean_sandbox.write(rel, data)
        listing = clean_sandbox.run()
        assert listing.state == CLEAN_STATE_PRESENT
        assert _files_of(listing) == {
            rel: (True, len(data), _sha(data)) for rel, data in contents.items()
        }

    def test_empty_run_dir_and_only_empty_dirs(self, clean_sandbox: _CleanSandbox) -> None:
        """SPEC_03「clean」: フォルダは判定の対象にしない（空のフォルダだけなら 0 件）."""
        clean_sandbox.run_dir().mkdir(parents=True)
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_PRESENT, ())
        (clean_sandbox.run_dir() / "a" / "b").mkdir(parents=True)
        (clean_sandbox.run_dir() / "c").mkdir()
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_PRESENT, ())

    def test_nasty_names_are_listed_one_by_one_and_nothing_is_created(
        self, clean_sandbox: _CleanSandbox
    ) -> None:
        names = [
            "a b.txt",
            "  lead and trail  x",
            "it's.txt",
            "$(touch PWNED).txt",
            "`touch PWNED2`",
            "a;b.txt",
            "a&&touch PWNED3",
            "-rf",
            "-dash.txt",
            "--help",
        ]
        if sys.platform != "win32":
            names += ['q"d.txt', "star*.txt", "nl\nname.txt", "back\\slash.txt", "x\ty", "?"]
        contents = {}
        for i, name in enumerate(names):
            contents[name] = f"content {i}".encode()
            contents[f"nested dir/{name}"] = f"nested {i}".encode() * 3
        for rel, data in contents.items():
            clean_sandbox.write(rel, data)
        before = _snapshot(clean_sandbox.root)
        listing = clean_sandbox.run()
        assert _files_of(listing) == {
            rel: (True, len(data), _sha(data)) for rel, data in contents.items()
        }
        # 名前の中のコマンドが実行されていない（cwd を含め，どこにも何も作られていない）
        assert not [p for p in clean_sandbox.root.rglob("PWNED*") if p.name.startswith("PWNED")]
        assert _snapshot(clean_sandbox.root) == before

    def test_not_utf8_name_is_listed(self, clean_sandbox: _CleanSandbox) -> None:
        if sys.platform == "win32":
            pytest.skip("Windows では UTF-8 として読めない名前を作れない")
        run_dir = clean_sandbox.run_dir()
        run_dir.mkdir(parents=True)
        bad = os.path.join(os.fsencode(run_dir), b"bad\xff.bin")
        with open(bad, "wb") as handle:
            handle.write(b"q")
        (found,) = clean_sandbox.run().files
        assert found.regular and found.sha256 == _sha(b"q")
        assert found.rel_path == os.fsdecode(b"bad\xff.bin")

    def test_run_id_prefix_of_other_run_lists_only_its_own(
        self, clean_sandbox: _CleanSandbox
    ) -> None:
        """RUN_ID が別の実験フォルダの名前の前半と同じでも，その実験フォルダの下だけ."""
        clean_sandbox.write("a.txt", b"1", base=clean_sandbox.run_dir("r1"))
        clean_sandbox.write("b.txt", b"2", base=clean_sandbox.run_dir("r10"))
        clean_sandbox.write("c.txt", b"3", base=clean_sandbox.run_dir("r1x"))
        if sys.platform != "win32":  # Windows では大文字小文字だけが違う名前は同じフォルダ
            clean_sandbox.write("d.txt", b"4", base=clean_sandbox.run_dir("R1"))
        assert list(_files_of(clean_sandbox.run("r1"))) == ["a.txt"]
        assert list(_files_of(clean_sandbox.run("r10"))) == ["b.txt"]

    def test_missing_run_dir(self, clean_sandbox: _CleanSandbox) -> None:
        clean_sandbox.write("a.txt", base=clean_sandbox.run_dir("other1"))
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_MISSING)

    def test_missing_remote_dir(self, clean_sandbox: _CleanSandbox) -> None:
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_MISSING)
        assert not os.path.lexists(clean_sandbox.remote)

    def test_missing_results_dir(self, clean_sandbox: _CleanSandbox) -> None:
        clean_sandbox.remote.mkdir(parents=True)
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_MISSING)
        assert not os.path.lexists(clean_sandbox.remote / "runs")

    def test_run_dir_that_is_a_file(self, clean_sandbox: _CleanSandbox) -> None:
        clean_sandbox.write("", b"file", base=clean_sandbox.run_dir())
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_NOT_DIR)

    @pytest.mark.parametrize("what", ["remote_dir", "results_dir"])
    def test_place_that_is_a_file_is_not_present(
        self, clean_sandbox: _CleanSandbox, what: str
    ) -> None:
        target = clean_sandbox.remote if what == "remote_dir" else clean_sandbox.remote / "runs"
        clean_sandbox.write("", b"file", base=target)
        assert clean_sandbox.run().state != CLEAN_STATE_PRESENT

    def test_other_results_dir_is_used(self, clean_sandbox: _CleanSandbox) -> None:
        clean_sandbox.write("a.txt", b"1")
        clean_sandbox.write("b.txt", b"2", base=clean_sandbox.run_dir(results_dir="out/runs"))
        listing = clean_sandbox.run(results_dir="out/runs")
        assert list(_files_of(listing)) == ["b.txt"]

    @pytest.mark.parametrize("dir_name", ["a b", "x;y $(touch PWNED)", "it's", "`touch PWNED`"])
    def test_remote_dir_with_special_characters(
        self, clean_sandbox: _CleanSandbox, dir_name: str
    ) -> None:
        remote = clean_sandbox.root / "srv" / dir_name
        clean_sandbox.write("a.txt", b"1", base=remote / "runs" / CLEAN_RUN)
        listing = clean_sandbox.run(remote=remote.as_posix())
        assert list(_files_of(listing)) == ["a.txt"]
        assert not list(clean_sandbox.root.rglob("PWNED"))

    def test_remote_dir_under_home(self, clean_sandbox: _CleanSandbox) -> None:
        """`~/...` の remote_dir は，サーバの $HOME の下を見る."""
        home = clean_sandbox.root / "home"
        clean_sandbox.write("a.txt", b"1", base=home / "work" / "p" / "runs" / CLEAN_RUN)
        listing = clean_sandbox.run(remote="~/work/p", env={"HOME": home.as_posix()})
        assert list(_files_of(listing)) == ["a.txt"]

    def test_nothing_changes(self, clean_sandbox: _CleanSandbox) -> None:
        """SPEC_03「clean」: 判定では何も消さない・書き込まない（一覧・内容・mtime が同じ）."""
        clean_sandbox.write("metrics.json", b"{}")
        clean_sandbox.write("sub/x.bin", b"\0\1\2")
        clean_sandbox.write("checkpoints/best.pth", b"w" * 5000)
        (clean_sandbox.run_dir() / "emptydir").mkdir()
        clean_sandbox.write("a.txt", base=clean_sandbox.run_dir("20261120-090000_demo_def5678"))
        clean_sandbox.write("_remote_logs/t.log", base=clean_sandbox.remote / "runs")
        clean_sandbox.write("src/main.py", base=clean_sandbox.remote)
        before = _snapshot(clean_sandbox.root)
        clean_sandbox.run()
        assert _snapshot(clean_sandbox.root) == before

    @pytest.mark.parametrize("command", ["clean", "ls"])
    def test_cdpath_does_not_redirect_cd(self, clean_sandbox: _CleanSandbox, command: str) -> None:
        """SPEC_03「clean」: CDPATH が設定されていても，remote_dir の下の結果の置き場を見る."""
        decoy = clean_sandbox.root / "decoy"
        clean_sandbox.write("decoy.txt", b"d", base=decoy / "runs" / CLEAN_RUN)
        clean_sandbox.write("real.txt", b"r")
        env = {"CDPATH": decoy.as_posix()}
        if command == "clean":
            listing = clean_sandbox.run(env=env)
            assert list(_files_of(listing)) == ["real.txt"]
            # 結果の置き場が remote_dir に無いときも，CDPATH の先へ行かない
            (clean_sandbox.run_dir() / "real.txt").unlink()
            clean_sandbox.run_dir().rmdir()
            (clean_sandbox.remote / "runs").rmdir()
            assert clean_sandbox.run(env=env) == RemoteRunListing(CLEAN_STATE_MISSING)
        else:
            ls_command = build_ls_command(clean_sandbox.remote.as_posix(), results_dir="runs")
            result = subprocess.run(
                [clean_sandbox.bash, "-c", ls_command],
                cwd=clean_sandbox.root,
                capture_output=True,
                timeout=60,
                check=False,
                env={**os.environ, **env},
            )
            listing = parse_ls_output(result.stdout)
            (entry,) = listing.run_dirs
            assert entry.file_count == 1
            (clean_sandbox.run_dir() / "real.txt").unlink()
            clean_sandbox.run_dir().rmdir()
            (clean_sandbox.remote / "runs").rmdir()
            result = subprocess.run(
                [clean_sandbox.bash, "-c", ls_command],
                cwd=clean_sandbox.root,
                capture_output=True,
                timeout=60,
                check=False,
                env={**os.environ, **env},
            )
            listing = parse_ls_output(result.stdout)
            assert not listing.results_dir_exists and listing.run_dirs == ()

    # --- 権限・特殊なファイル（Linux だけ） ---

    def test_unreadable_file_is_nohash_and_rejected(self, clean_sandbox: _CleanSandbox) -> None:
        """SPEC_03「clean」: ハッシュを取れなかったファイルが 1 件でもあれば止まる."""
        clean_sandbox.write("ok.txt", b"1")
        locked = clean_sandbox.write("locked.txt", b"secret")
        locked.chmod(0)
        try:
            if os.access(locked, os.R_OK):
                pytest.skip("この環境では権限で読めないファイルを作れない（Windows・root）")
            raw = clean_sandbox.run_raw()
        finally:
            locked.chmod(0o644)
        assert b"nohash ./" + CLEAN_RUN.encode() + b"/locked.txt" in raw
        with pytest.raises(ValueError):
            parse_clean_output(raw, CLEAN_RUN)

    def test_unreadable_folder_inside_is_rejected(self, clean_sandbox: _CleanSandbox) -> None:
        """SPEC_03「clean」: 一覧の取得（find）が失敗した（読めないフォルダがある）なら止まる."""
        clean_sandbox.write("ok.txt", b"1")
        locked = clean_sandbox.run_dir() / "locked"
        clean_sandbox.write("hidden.txt", base=locked)
        locked.chmod(0)
        try:
            if os.access(locked, os.R_OK | os.X_OK):
                pytest.skip("この環境では権限で読めないフォルダを作れない（Windows・root）")
            raw = clean_sandbox.run_raw()
        finally:
            locked.chmod(0o755)
        with pytest.raises(ValueError):
            parse_clean_output(raw, CLEAN_RUN)

    def test_unreadable_run_dir_is_unreadable(self, clean_sandbox: _CleanSandbox) -> None:
        clean_sandbox.write("a.txt")
        run_dir = clean_sandbox.run_dir()
        run_dir.chmod(0)
        try:
            if os.access(run_dir, os.R_OK | os.X_OK):
                pytest.skip("この環境では権限で読めないフォルダを作れない（Windows・root）")
            listing = clean_sandbox.run()
        finally:
            run_dir.chmod(0o755)
        assert listing == RemoteRunListing(CLEAN_STATE_UNREADABLE)

    def test_fifo_is_other_and_not_opened(self, clean_sandbox: _CleanSandbox) -> None:
        """FIFO は開かずに「通常のファイル以外」とする（開いて止まらない）."""
        if not hasattr(os, "mkfifo"):
            pytest.skip("FIFO を作れない環境（Windows）")
        clean_sandbox.write("a.txt", b"1")
        os.mkfifo(clean_sandbox.run_dir() / "pipe")
        listing = clean_sandbox.run()
        assert _files_of(listing) == {"a.txt": (True, 1, _sha(b"1")), "pipe": (False, 0, "")}

    # --- リンク（作れない環境では飛ばす．CI の Linux で実行される） ---

    def test_run_dir_that_is_a_link_is_not_entered(
        self, clean_sandbox: _CleanSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「clean」: 実験フォルダそのものがリンクなら link（中に入らない）."""
        target = clean_sandbox.outside / "real"
        clean_sandbox.write("a.txt", base=target)
        (clean_sandbox.remote / "runs").mkdir(parents=True)
        links.symlink(clean_sandbox.run_dir(), target, is_dir=True)
        raw = clean_sandbox.run_raw()
        assert parse_clean_output(raw, CLEAN_RUN) == RemoteRunListing(CLEAN_STATE_LINK)
        assert b"a.txt" not in raw

    def test_run_dir_that_is_a_link_to_a_file(
        self, clean_sandbox: _CleanSandbox, links: LinkFactory
    ) -> None:
        target = clean_sandbox.write("f", b"x", base=clean_sandbox.outside)
        (clean_sandbox.remote / "runs").mkdir(parents=True)
        links.symlink(clean_sandbox.run_dir(), target, is_dir=False)
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_LINK)

    def test_broken_link_as_run_dir_is_link(
        self, clean_sandbox: _CleanSandbox, links: LinkFactory
    ) -> None:
        (clean_sandbox.remote / "runs").mkdir(parents=True)
        links.symlink(clean_sandbox.run_dir(), clean_sandbox.outside / "nowhere", is_dir=True)
        assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_LINK)

    def test_links_inside_are_other_and_not_followed(
        self, clean_sandbox: _CleanSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「clean」: 中のリンクは，先をたどらずに「通常のファイル以外」として 1 件ずつ."""
        target_file = clean_sandbox.write("t.txt", b"target", base=clean_sandbox.outside)
        target_dir = clean_sandbox.outside / "tdir"
        clean_sandbox.write("inner1.txt", b"i1", base=target_dir)
        clean_sandbox.write("inner2.txt", b"i2", base=target_dir)
        clean_sandbox.write("a.txt", b"1")
        run_dir = clean_sandbox.run_dir()
        links.symlink(run_dir / "file_link", target_file, is_dir=False)
        links.symlink(run_dir / "sub" / "dir_link", target_dir, is_dir=True)
        links.symlink(run_dir / "broken", clean_sandbox.outside / "nowhere", is_dir=False)
        links.symlink(run_dir / "inner_link", run_dir / "a.txt", is_dir=False)
        raw = clean_sandbox.run_raw()
        listing = parse_clean_output(raw, CLEAN_RUN)
        assert _files_of(listing) == {
            "a.txt": (True, 1, _sha(b"1")),
            "file_link": (False, 0, ""),
            "sub/dir_link": (False, 0, ""),
            "broken": (False, 0, ""),
            "inner_link": (False, 0, ""),
        }
        assert b"inner1" not in raw and b"inner2" not in raw
        assert _sha(b"target").encode() not in raw

    def test_junction_inside_is_not_followed(
        self, clean_sandbox: _CleanSandbox, links: LinkFactory
    ) -> None:
        """Windows のジャンクションも，中に入らない（Windows だけ）."""
        target_dir = clean_sandbox.outside / "tdir"
        clean_sandbox.write("inner1.txt", b"i1", base=target_dir)
        clean_sandbox.write("a.txt", b"1")
        links.junction(clean_sandbox.run_dir() / "junc", target_dir)
        raw = clean_sandbox.run_raw()
        assert b"inner1" not in raw
        listing = parse_clean_output(raw, CLEAN_RUN)
        assert "a.txt" in _files_of(listing)
        assert not any("inner1" in f.rel_path for f in listing.files)


# ---------------------------------------------------------------------------
# clean の削除（SPEC_03「clean」の「削除の細部」・SPEC_01「安全の枠」の「削除」）
#
# build_clean_delete_command を，tmp_path の下の偽のホーム（HOME を差し替える）と偽のフォルダで
# 実際に動かす．毎回，実験フォルダの周りに「消えてはいけないもの」を置き，前後の一覧と内容を比べる．
# ---------------------------------------------------------------------------

DEL_RUN = "r1"
# remote_dir の最初の部分．偽のホームの下にだけ作る（HOME の差し替えが効かなくても，本物の
# ホームの下の実在のフォルダを指さないよう，ありそうにない名前にする）
_FAKE_HOME_ONLY = "labremote_fake_home_only_q7v2"
# 標準出力・標準エラーに出てはならない，実験フォルダの中のファイル名
_DEL_SECRET = "secretdeletename_k3"
_END = CLEAN_EXPECT_END_RECORD.encode("ascii")
_MARKER = CLEAN_DELETED_MARKER.encode("ascii")

# 実験フォルダの中身（入れ子・空のファイル・隠しファイルを含む）
_DEL_BASE = {
    "a.txt": b"alpha",
    "sub/b.txt": b"bravo",
    "sub/deep/er/c.bin": bytes(range(256)) * 64,
    "empty.bin": b"",
    ".hidden": b"h",
    f"{_DEL_SECRET}.txt": b"secret",
}


def _b(value: str | bytes) -> bytes:
    return value if isinstance(value, bytes) else value.encode("utf-8")


def _file_rec(rel: str | bytes, data: bytes, run_id: str = DEL_RUN) -> bytes:
    """一覧のスクリプトと同じ形の file の記録（NUL を含まない）."""
    return f"{CLEAN_FILE_PREFIX}{len(data)} {_sha(data)} ./{run_id}/".encode() + _b(rel)


def _other_rec(rel: str | bytes, run_id: str = DEL_RUN) -> bytes:
    return f"{CLEAN_OTHER_PREFIX}./{run_id}/".encode() + _b(rel)


def _payload(records: list[bytes], *, end: bool = True) -> bytes:
    """記録を NUL 区切りで並べ，終わりの記録を付けた，送る一覧."""
    return b"".join(r + b"\0" for r in records) + (_END + b"\0" if end else b"")


def _recs(payload: bytes) -> list[bytes]:
    """送る一覧を記録に分ける（最後の終わりの記録を含む）."""
    assert payload.endswith(b"\0")
    return payload[:-1].split(b"\0")


def _join(records: list[bytes]) -> bytes:
    return b"".join(r + b"\0" for r in records)


class _DeleteSandbox:
    """tmp_path の下の偽のホームで，clean の一覧と削除のコマンドを bash で実際に動かす."""

    def __init__(self, tmp_path: Path) -> None:
        tmp_path.mkdir(parents=True, exist_ok=True)
        self.bash = _bash_or_skip(tmp_path)
        self.root = tmp_path
        self.home = tmp_path / "fakehome"
        self.home.mkdir()
        # HOME の差し替えが効かなかったときに，本物のホームの下を指さないことの前提
        assert not os.path.lexists(Path.home() / _FAKE_HOME_ONLY)
        self.remote_text = f"~/{_FAKE_HOME_ONLY}/proj"
        self.remote = self.home / _FAKE_HOME_ONLY / "proj"
        self.outside = tmp_path / "outside"
        self.outside.mkdir()

    @property
    def results(self) -> Path:
        return self.remote / "runs"

    def run_dir(self, run_id: str = DEL_RUN, results_dir: str = "runs") -> Path:
        return self.remote / results_dir / run_id

    def write(self, rel: str, data: bytes = b"x", *, base: Path | None = None) -> Path:
        path = (base or self.run_dir()) / rel if rel else (base or self.run_dir())
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
        return path

    def populate(
        self, contents: dict[str, bytes] | None = None, *, base: Path | None = None
    ) -> None:
        run_dir = base or self.run_dir()
        for rel, data in (_DEL_BASE if contents is None else contents).items():
            self.write(rel, data, base=run_dir)
        (run_dir / "emptydir").mkdir(parents=True, exist_ok=True)
        (run_dir / "nested" / "empty" / "dir").mkdir(parents=True, exist_ok=True)

    def guard(self, remote: Path | None = None) -> None:
        """実験フォルダの周りに，消えてはいけないものを置く（実験フォルダと同じ内容も含む）."""
        remote = remote or self.remote
        results = remote / "runs"
        for run_id in ("r10", "r1x", "r", "r1.bak"):
            if not os.path.lexists(results / run_id):
                self.write("a.txt", b"alpha", base=results / run_id)
                self.write("sub/b.txt", b"bravo", base=results / run_id)
        self.write("_remote_logs/train1.log", b"log", base=results)
        self.write("top.txt", b"top", base=results)
        self.write(".venv/lib/site.py", b"venv", base=remote)
        self.write("train.py", b"code", base=remote)
        self.write("src/pkg/__init__.py", b"", base=remote)
        self.write("keep.txt", b"sibling", base=remote.parent / "proj2")
        self.write(".profile", b"home", base=self.home)
        self.write("o.txt", b"outside", base=self.outside)

    def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:
        env = {k: v for k, v in os.environ.items() if k != "CDPATH"}
        env["HOME"] = self.home.as_posix()
        env.update(extra or {})
        return env

    def list_raw(self, run_id: str = DEL_RUN, *, results_dir: str = "runs") -> bytes:
        command = build_clean_list_command(self.remote_text, results_dir=results_dir, run_id=run_id)
        result = subprocess.run(
            [self.bash, "-c", command],
            cwd=self.root,
            capture_output=True,
            timeout=120,
            check=False,
            env=self.env(),
        )
        assert result.returncode == 0, result.stderr
        return result.stdout

    def records(self, run_id: str = DEL_RUN, **kwargs: str) -> list[bytes]:
        """一覧のスクリプトが出した，実験フォルダの中の記録（NUL を含まない）."""
        parts = self.list_raw(run_id, **kwargs).split(b"\0")
        start = parts.index((CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT).encode())
        rc = CLEAN_FIND_RC_PREFIX.encode()
        stop = next(i for i in range(start + 1, len(parts)) if parts[i].startswith(rc))
        return parts[start + 1 : stop]

    def flow_payload(self, run_id: str = DEL_RUN, **kwargs: str) -> bytes:
        """実際の流れ（一覧 → 解析 → 判定 → 送る一覧）で作った，送る一覧（全部一致とする）."""
        listing = parse_clean_output(self.list_raw(run_id, **kwargs), run_id)
        assert listing.state == CLEAN_STATE_PRESENT
        local = {
            f.rel_path: LocalFile(f.size_bytes, f.sha256)
            for f in local_paths_to_check(listing.files)
        }
        judgement = classify_clean(listing.files, local, CLEAN_RESULTS, discard_checkpoints=False)
        return build_clean_expected_input(judgement, run_id)

    def delete(
        self,
        payload: bytes,
        run_id: str = DEL_RUN,
        *,
        remote: str | None = None,
        results_dir: str = "runs",
        env: dict[str, str] | None = None,
        cwd: Path | None = None,
    ) -> subprocess.CompletedProcess[bytes]:
        command = build_clean_delete_command(
            self.remote_text if remote is None else remote, results_dir=results_dir, run_id=run_id
        )
        return subprocess.run(
            [self.bash, "-c", command],
            input=payload,
            cwd=cwd or self.root,
            capture_output=True,
            timeout=120,
            check=False,
            env=self.env(env),
        )

    def snapshot(self) -> dict[str, tuple]:
        return _snapshot(self.root)

    def assert_nothing_deleted(
        self,
        result: subprocess.CompletedProcess[bytes],
        before: dict[str, tuple],
        rc: int | None = None,
    ) -> None:
        """0 以外で終わり，目印が無く，何も消えていない・変わっていない."""
        assert result.returncode != 0
        if rc is not None:
            assert result.returncode == rc, (result.returncode, result.stderr)
        assert _MARKER not in result.stdout
        assert _DEL_SECRET.encode() not in result.stdout + result.stderr
        assert self.snapshot() == before

    def assert_only_run_dir_deleted(
        self,
        result: subprocess.CompletedProcess[bytes],
        before: dict[str, tuple],
        run_dir: Path | None = None,
    ) -> None:
        """0 で終わり，目印があり，実験フォルダだけが無くなり，周りは変わっていない."""
        run_dir = run_dir or self.run_dir()
        assert result.returncode == 0, (result.returncode, result.stderr)
        assert _MARKER in result.stdout.split(b"\n")
        assert _DEL_SECRET.encode() not in result.stdout + result.stderr
        assert not os.path.lexists(run_dir)
        rel = run_dir.relative_to(self.root).as_posix()
        assert rel in before
        expected = {k: v for k, v in before.items() if k != rel and not k.startswith(rel + "/")}
        assert self.snapshot() == expected


@pytest.fixture
def del_sandbox(tmp_path: Path) -> _DeleteSandbox:
    return _DeleteSandbox(tmp_path)


def _first_file_index(records: list[bytes]) -> int:
    return next(i for i, r in enumerate(records) if r.startswith(CLEAN_FILE_PREFIX.encode()))


def _flip_hash(records: list[bytes]) -> list[bytes]:
    i = _first_file_index(records)
    head, size, digest, path = records[i].split(b" ", 3)
    flipped = (b"0" if digest[:1] != b"0" else b"1") + digest[1:]
    return [*records[:i], b" ".join([head, size, flipped, path]), *records[i + 1 :]]


def _change_size(records: list[bytes]) -> list[bytes]:
    i = _first_file_index(records)
    head, size, digest, path = records[i].split(b" ", 3)
    bigger = str(int(size) + 1).encode()
    return [*records[:i], b" ".join([head, bigger, digest, path]), *records[i + 1 :]]


def _replace_first(records: list[bytes], old: bytes, new: bytes) -> list[bytes]:
    i = _first_file_index(records)
    return [*records[:i], records[i].replace(old, new, 1), *records[i + 1 :]]


# 送る一覧（実際の流れで作った正しいもの）を壊す．どれも消えてはならない
_BAD_PAYLOADS: dict[str, Callable[[bytes], bytes]] = {
    "empty": lambda p: b"",
    "end_only": lambda p: _END + b"\0",
    "no_end": lambda p: _join(_recs(p)[:-1]),
    "cut_third": lambda p: p[: len(p) // 3],
    "cut_half": lambda p: p[: len(p) // 2],
    "cut_before_end": lambda p: p[: len(p) - len(_END) - 1],
    "cut_inside_end": lambda p: p[: len(p) - 6],
    "cut_inside_first_record": lambda p: p[:10],
    "twice": lambda p: p + p,
    "one_more": lambda p: _join([_file_rec("ghost.txt", b"g"), *_recs(p)]),
    "one_less": lambda p: _join(_recs(p)[1:]),
    "duplicate_record": lambda p: _join([_recs(p)[0], *_recs(p)]),
    "hash_one_char": lambda p: _join(_flip_hash(_recs(p))),
    "size_differs": lambda p: _join(_change_size(_recs(p))),
    "other_run_id": lambda p: _join(_replace_first(_recs(p), b"./r1/", b"./r10/")),
    "tab_separator": lambda p: _join(_replace_first(_recs(p), b" ", b"\t")),
    "file_as_other": lambda p: _join(
        _replace_first(_recs(p), CLEAN_FILE_PREFIX.encode(), CLEAN_OTHER_PREFIX.encode())
    ),
    "find_failed": lambda p: _join([CLEAN_FIND_FAILED_RECORD.encode(), *_recs(p)]),
    "newline_separated": lambda p: p.replace(b"\0", b"\n"),
    "end_twice": lambda p: p + _END + b"\0",
}


def _add(rel: str, data: bytes = b"n") -> Callable[[_DeleteSandbox], None]:
    def change(sandbox: _DeleteSandbox) -> None:
        sandbox.write(rel, data)

    return change


def _to_dir(sandbox: _DeleteSandbox) -> None:
    (sandbox.run_dir() / "a.txt").unlink()
    (sandbox.run_dir() / "a.txt").mkdir()


def _rename(old: str, new: str) -> Callable[[_DeleteSandbox], None]:
    def change(sandbox: _DeleteSandbox) -> None:
        (sandbox.run_dir() / old).rename(sandbox.run_dir() / new)

    return change


# 判定（送る一覧の組み立て）の後に，実験フォルダの中身を変える．どれも消えてはならない
_CHANGES: dict[str, Callable[[_DeleteSandbox], None]] = {
    "added_top": _add("new.txt"),
    "added_nested": _add("sub/deep/er/new.txt"),
    "added_empty_file": _add("zero", b""),
    "added_hidden": _add(".hidden2"),
    "added_in_empty_dir": _add("emptydir/x", b""),
    "content_same_size": _add("sub/b.txt", b"BRAVO"),
    "size_changed": _add("sub/b.txt", b"bravo!"),
    "empty_file_grew": _add("empty.bin", b"z"),
    "removed": lambda s: (s.run_dir() / "a.txt").unlink(),
    "renamed": _rename("a.txt", "a2.txt"),
    "renamed_folder": _rename("sub", "sub2"),
    "file_became_dir": _to_dir,
}


class TestCleanDeleteInShell:
    """SPEC_03「clean」の手順 4・5: 照合が全部合うときだけ，実験フォルダ 1 つだけを消す."""

    def test_all_matching_deletes_only_the_run_dir(self, del_sandbox: _DeleteSandbox) -> None:
        contents = {**_DEL_BASE, "big/three_mb.bin": bytes(range(256)) * (3 * 4096)}
        del_sandbox.populate(contents)
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(payload)
        del_sandbox.assert_only_run_dir_deleted(result, before)

    def test_order_of_records_does_not_matter(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.populate()
        del_sandbox.guard()
        records = _recs(del_sandbox.flow_payload())
        payload = _join([*reversed(records[:-1]), records[-1]])
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload), before)

    def test_server_listing_as_is_matches(self, del_sandbox: _DeleteSandbox) -> None:
        """一覧のスクリプトの記録を，そのまま送る一覧にしても一致する（形が同じこと）."""
        del_sandbox.populate()
        del_sandbox.guard()
        flow = del_sandbox.flow_payload()
        server = _payload(del_sandbox.records())
        assert sorted(_recs(flow)) == sorted(_recs(server))
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(server), before)

    @pytest.mark.parametrize("with_empty_dirs", [False, True])
    def test_empty_run_dir_with_correct_list_is_deleted(
        self, del_sandbox: _DeleteSandbox, with_empty_dirs: bool
    ) -> None:
        """SPEC_03「clean」: 空の実験フォルダは，サーバでも 0 件であることを確かめてから消す."""
        del_sandbox.run_dir().mkdir(parents=True)
        if with_empty_dirs:
            (del_sandbox.run_dir() / "a" / "b").mkdir(parents=True)
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        assert payload == _END + b"\0"
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload), before)

    @pytest.mark.parametrize("stdin", [b"", b"\0", b"\n"], ids=["empty", "nul", "newline"])
    def test_empty_run_dir_with_empty_stdin_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, stdin: bytes
    ) -> None:
        """SPEC_03「clean」: 終わりの記録が無い入力は，実験フォルダが空でも一致としない."""
        del_sandbox.run_dir().mkdir(parents=True)
        del_sandbox.guard()
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(stdin), before, rc=EXIT_CLEAN_MISMATCH
        )

    @pytest.mark.parametrize("change", list(_CHANGES))
    def test_change_after_judgement_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, change: str
    ) -> None:
        """SPEC_03「clean」: 判定の後に増えた・変わった・減ったら，何も消さずに 96."""
        del_sandbox.populate()
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        _CHANGES[change](del_sandbox)
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload), before, rc=EXIT_CLEAN_MISMATCH
        )

    @pytest.mark.parametrize("bad", list(_BAD_PAYLOADS))
    def test_bad_list_is_not_deleted(self, del_sandbox: _DeleteSandbox, bad: str) -> None:
        """SPEC_03「clean」: 件数・種類・大きさ・ハッシュ・パスが全部合うときだけ消す."""
        del_sandbox.populate()
        del_sandbox.guard()
        good = del_sandbox.flow_payload()
        payload = _BAD_PAYLOADS[bad](good)
        assert payload != good
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload), before, rc=EXIT_CLEAN_MISMATCH
        )

    @pytest.mark.parametrize("run_id", ["r1", "r", "r10"])
    def test_only_the_named_run_dir_is_deleted(
        self, del_sandbox: _DeleteSandbox, run_id: str
    ) -> None:
        """RUN_ID が別の実験フォルダの名前の前半・後半と重なっても，その 1 つだけを消す."""
        for other in ("r1", "r10", "r1x", "r", "r1.bak", "R1"):
            if sys.platform == "win32" and other == "R1":
                continue  # Windows では大文字小文字だけが違う名前は同じフォルダ
            del_sandbox.populate({"a.txt": b"alpha"}, base=del_sandbox.run_dir(other))
        del_sandbox.guard()
        payload = del_sandbox.flow_payload(run_id)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(payload, run_id)
        del_sandbox.assert_only_run_dir_deleted(result, before, del_sandbox.run_dir(run_id))

    def test_list_of_other_run_does_not_delete(self, del_sandbox: _DeleteSandbox) -> None:
        """別の実験（同じ中身）の一覧を送っても，その実験 ID の照合は合わない."""
        del_sandbox.populate({"a.txt": b"alpha"})
        del_sandbox.populate({"a.txt": b"alpha"}, base=del_sandbox.run_dir("r10"))
        del_sandbox.guard()
        payload = del_sandbox.flow_payload("r10")
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload, "r1"), before, rc=EXIT_CLEAN_MISMATCH
        )

    # --- 実験フォルダ・置き場の状態 ---

    def test_missing_run_dir_is_92(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.guard()
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([]))
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_NOT_FOUND)

    def test_run_dir_that_is_a_file_is_94_and_kept(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.guard()
        del_sandbox.write("", b"file", base=del_sandbox.run_dir())
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([]))
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_UNSAFE_PATH)
        assert del_sandbox.run_dir().read_bytes() == b"file"

    def test_missing_remote_dir_is_90(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.write(".profile", b"home", base=del_sandbox.home)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([]))
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_REMOTE_DIR_MISSING)

    def test_missing_results_dir_is_92(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.write("train.py", b"code", base=del_sandbox.remote)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([]))
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_NOT_FOUND)

    @pytest.mark.parametrize("what", ["remote_dir", "results_dir"])
    def test_place_that_is_a_file_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, what: str
    ) -> None:
        target = del_sandbox.remote if what == "remote_dir" else del_sandbox.results
        del_sandbox.write("", b"file", base=target)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([]))
        del_sandbox.assert_nothing_deleted(result, before)

    @pytest.mark.parametrize("remote_kind", ["tilde", "absolute"])
    def test_remote_dir_with_special_characters(
        self, del_sandbox: _DeleteSandbox, remote_kind: str
    ) -> None:
        """remote_dir の名前に特殊な文字があっても，その下の実験フォルダだけを消す."""
        name = "p q;$(touch PWNED)'x"
        remote = del_sandbox.home / _FAKE_HOME_ONLY / name
        text = f"~/{_FAKE_HOME_ONLY}/{name}" if remote_kind == "tilde" else remote.as_posix()
        if not text.startswith(("~/", "/")):
            # 手元の Windows では tmp_path が `C:/...` になる．remote_dir は `~/...` か `/` で始まる
            # 絶対パスだけを受け付けるので（SPEC_02），この形は Linux でだけ確かめる
            pytest.skip("Windows の tmp_path は / で始まる絶対パスにならない")
        del_sandbox.populate({"a.txt": b"alpha"}, base=remote / "runs" / DEL_RUN)
        del_sandbox.guard()
        del_sandbox.guard(remote)
        records = [_file_rec("a.txt", b"alpha")]
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload(records), remote=text)
        del_sandbox.assert_only_run_dir_deleted(result, before, remote / "runs" / DEL_RUN)
        assert not list(del_sandbox.root.rglob("PWNED*"))


# 名前に入れる特殊な文字（どの OS でも作れ，手元のパスにしてよい名前）
_DEL_SAFE_NASTY = [
    "a b.txt",
    "it's",
    "$(touch PWNED)",
    "`touch PWNED2`",
    "a;b",
    "x && touch PWNED3",
    "-rf",
    "--no-preserve-root",
    "~",
    "~x",
    "-",
]
# POSIX でだけ作れる名前（手元のパスにできないので，実際の流れでは「説明がつかない」になる）
_DEL_POSIX_NASTY = ['q"d', "star*", "?", "nl\nname", "back\\slash", "tab\there", "x|y>z"]


def _nasty_contents(names: list[str]) -> dict[str, bytes]:
    contents: dict[str, bytes] = {}
    for i, name in enumerate(names):
        contents[name] = f"content {i}".encode()
        contents[f"dir {i}/{name}"] = f"nested {i}".encode()
    return contents


def _no_pwned(root: Path) -> bool:
    return not [p for p in root.rglob("*") if p.name.startswith("PWNED")]


class TestCleanDeleteNamesInShell:
    """特殊な名前のファイルがあっても，名前がコマンドとして解釈されず，照合が効く."""

    def test_safe_nasty_names_flow_is_deleted(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.populate(_nasty_contents(_DEL_SAFE_NASTY))
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        assert len(_recs(payload)) == 2 * len(_DEL_SAFE_NASTY) + 1
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload), before)
        assert _no_pwned(del_sandbox.root)

    def test_safe_nasty_names_with_one_changed_is_not_deleted(
        self, del_sandbox: _DeleteSandbox
    ) -> None:
        contents = _nasty_contents(_DEL_SAFE_NASTY)
        del_sandbox.populate(contents)
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        del_sandbox.write("dir 2/$(touch PWNED)", b"NESTED 2")  # 大きさは同じ
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload), before, rc=EXIT_CLEAN_MISMATCH
        )
        assert _no_pwned(del_sandbox.root)

    def test_posix_nasty_names_with_server_records(self, del_sandbox: _DeleteSandbox) -> None:
        """POSIX でだけ作れる名前（改行・引用符・ワイルドカード）も，一覧が一致すれば消える."""
        if sys.platform == "win32":
            pytest.skip("Windows ではこれらの名前を作れない")
        names = _DEL_SAFE_NASTY + _DEL_POSIX_NASTY
        del_sandbox.populate(_nasty_contents(names))
        del_sandbox.guard()
        # 実際の流れでは，手元のパスにできない名前は「説明がつかない」なので組み立てられない
        with pytest.raises(ValueError):
            del_sandbox.flow_payload()
        payload = _payload(del_sandbox.records())
        assert len(_recs(payload)) == 2 * len(names) + 1
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload), before)
        assert _no_pwned(del_sandbox.root)

    @pytest.mark.parametrize("changed", ["nl\nname", "star*", "?"])
    def test_posix_nasty_names_with_one_changed_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, changed: str
    ) -> None:
        if sys.platform == "win32":
            pytest.skip("Windows ではこれらの名前を作れない")
        names = _DEL_SAFE_NASTY + _DEL_POSIX_NASTY
        del_sandbox.populate(_nasty_contents(names))
        del_sandbox.guard()
        payload = _payload(del_sandbox.records())
        index = names.index(changed)
        del_sandbox.write(changed, f"CONTENT {index}".encode())
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload), before, rc=EXIT_CLEAN_MISMATCH
        )
        assert _no_pwned(del_sandbox.root)

    def test_newline_name_cannot_be_split_into_two_records(
        self, del_sandbox: _DeleteSandbox
    ) -> None:
        """改行を含む 1 つの名前を，2 つの記録に見せかけた一覧では消えない."""
        if sys.platform == "win32":
            pytest.skip("Windows では改行を含む名前を作れない")
        del_sandbox.populate({"a\nb": b"v"})
        del_sandbox.guard()
        payload = _payload([_file_rec("a", b"v"), _file_rec("b", b"v")])
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload), before, rc=EXIT_CLEAN_MISMATCH
        )

    def test_not_utf8_name_with_server_records(self, del_sandbox: _DeleteSandbox) -> None:
        if sys.platform == "win32":
            pytest.skip("Windows では UTF-8 として読めない名前を作れない")
        run_dir = del_sandbox.run_dir()
        run_dir.mkdir(parents=True)
        with open(os.path.join(os.fsencode(run_dir), b"bad\xff.bin"), "wb") as handle:
            handle.write(b"q")
        del_sandbox.guard()
        with pytest.raises(ValueError):
            del_sandbox.flow_payload()
        payload = _payload(del_sandbox.records())
        assert b"bad\xff.bin" in payload
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload), before)


class TestCleanDeleteLinksInShell:
    """SPEC_03「clean」: リンクをたどって消さない（作れない環境では飛ばす）."""

    def test_run_dir_that_is_a_link_is_94_and_target_kept(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        target = del_sandbox.outside / "real"
        del_sandbox.populate({"a.txt": b"alpha"}, base=target)
        del_sandbox.guard()
        links.symlink(del_sandbox.run_dir(), target, is_dir=True)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([_file_rec("a.txt", b"alpha")]))
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_UNSAFE_PATH)
        assert os.path.islink(del_sandbox.run_dir())

    def test_run_dir_that_is_a_junction_is_kept(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        target = del_sandbox.outside / "real"
        del_sandbox.populate({"a.txt": b"alpha"}, base=target)
        del_sandbox.guard()
        links.junction(del_sandbox.run_dir(), target)
        before = del_sandbox.snapshot()
        for payload in (_payload([_file_rec("a.txt", b"alpha")]), _payload([])):
            result = del_sandbox.delete(payload)
            del_sandbox.assert_nothing_deleted(result, before)
        assert (target / "a.txt").read_bytes() == b"alpha"

    def test_results_dir_that_is_a_link_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        real_results = del_sandbox.outside / "realruns"
        del_sandbox.populate({"a.txt": b"alpha"}, base=real_results / DEL_RUN)
        del_sandbox.write("train.py", b"code", base=del_sandbox.remote)
        links.symlink(del_sandbox.results, real_results, is_dir=True)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(_payload([_file_rec("a.txt", b"alpha")]))
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_UNSAFE_PATH)

    @pytest.mark.parametrize("linked", ["output", "output/runs"])
    def test_results_dir_with_link_in_the_middle_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory, linked: str
    ) -> None:
        """結果の置き場（output/runs）の途中のどの部分がリンクでも消さない."""
        real = del_sandbox.outside / "real"
        if linked == "output":
            del_sandbox.populate({"a.txt": b"alpha"}, base=real / "runs" / DEL_RUN)
            links.symlink(del_sandbox.remote / "output", real, is_dir=True)
        else:
            (del_sandbox.remote / "output").mkdir(parents=True)
            del_sandbox.populate({"a.txt": b"alpha"}, base=real / DEL_RUN)
            links.symlink(del_sandbox.remote / "output" / "runs", real, is_dir=True)
        del_sandbox.write("train.py", b"code", base=del_sandbox.remote)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(
            _payload([_file_rec("a.txt", b"alpha")]), results_dir="output/runs"
        )
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_UNSAFE_PATH)

    def test_list_command_reports_results_link(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        """一覧のコマンドは，結果の置き場の途中がリンクなら resultslink を出す（入らない）."""
        real = del_sandbox.outside / "real"
        del_sandbox.populate({"a.txt": b"alpha"}, base=real / "runs" / DEL_RUN)
        links.symlink(del_sandbox.remote / "output", real, is_dir=True)
        raw = del_sandbox.list_raw(results_dir="output/runs")
        assert parse_clean_output(raw, DEL_RUN) == RemoteRunListing(CLEAN_STATE_RESULTS_LINK)
        assert b"a.txt" not in raw
        links.symlink(del_sandbox.remote / "runs", real / "runs", is_dir=True)
        raw = del_sandbox.list_raw()
        assert parse_clean_output(raw, DEL_RUN) == RemoteRunListing(CLEAN_STATE_RESULTS_LINK)

    def test_list_command_reports_results_junction(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        real = del_sandbox.outside / "real"
        del_sandbox.populate({"a.txt": b"alpha"}, base=real / "runs" / DEL_RUN)
        del_sandbox.remote.mkdir(parents=True)
        links.junction(del_sandbox.remote / "output", real)
        raw = del_sandbox.list_raw(results_dir="output/runs")
        assert parse_clean_output(raw, DEL_RUN) == RemoteRunListing(CLEAN_STATE_RESULTS_LINK)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(
            _payload([_file_rec("a.txt", b"alpha")]), results_dir="output/runs"
        )
        del_sandbox.assert_nothing_deleted(result, before)

    def test_remote_dir_that_is_a_link_is_allowed(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        """SPEC_03「clean」: remote_dir そのものがリンクであることは認める."""
        real = del_sandbox.outside / "realproj"
        del_sandbox.populate(base=real / "runs" / DEL_RUN)
        del_sandbox.guard(real)
        links.symlink(del_sandbox.remote, real, is_dir=True)
        payload = del_sandbox.flow_payload()
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(payload)
        del_sandbox.assert_only_run_dir_deleted(result, before, real / "runs" / DEL_RUN)
        assert os.path.islink(del_sandbox.remote)

    def test_links_inside_are_not_followed_when_deleting(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        """中のリンクは，判定では説明がつかない．判定を飛ばして送っても，リンクの先は消えない."""
        target_dir = del_sandbox.outside / "tdir"
        del_sandbox.write("inner.txt", b"inner", base=target_dir)
        del_sandbox.write("deep/inner2.txt", b"inner2", base=target_dir)
        target_file = del_sandbox.write("t.txt", b"target", base=del_sandbox.outside)
        remote_target = del_sandbox.write("keep.py", b"code", base=del_sandbox.remote)
        del_sandbox.populate({"a.txt": b"alpha"})
        del_sandbox.guard()
        run_dir = del_sandbox.run_dir()
        links.symlink(run_dir / "dir_link", target_dir, is_dir=True)
        links.symlink(run_dir / "sub" / "file_link", target_file, is_dir=False)
        links.symlink(run_dir / "up_link", del_sandbox.remote, is_dir=True)
        links.symlink(run_dir / "code_link", remote_target, is_dir=False)
        with pytest.raises(ValueError):
            del_sandbox.flow_payload()
        payload = _payload(del_sandbox.records())
        assert payload.count(CLEAN_OTHER_PREFIX.encode()) == 4
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload), before)
        assert (target_dir / "deep" / "inner2.txt").read_bytes() == b"inner2"
        assert target_file.read_bytes() == b"target"
        assert remote_target.read_bytes() == b"code"

    def test_junction_inside_is_not_followed_when_deleting(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        target_dir = del_sandbox.outside / "tdir"
        del_sandbox.write("inner.txt", b"inner", base=target_dir)
        del_sandbox.populate({"a.txt": b"alpha"})
        del_sandbox.guard()
        links.junction(del_sandbox.run_dir() / "junc", target_dir)
        payload = _payload(del_sandbox.records())
        assert b"inner.txt" not in payload
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(payload)
        assert (target_dir / "inner.txt").read_bytes() == b"inner"
        del_sandbox.assert_only_run_dir_deleted(result, before)

    def test_file_replaced_by_link_to_same_content_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        """2-2 から持ち越した差し替えの穴: 判定の後に，同じ内容のファイルへのリンクに替えても 96."""
        del_sandbox.populate()
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        same = del_sandbox.write("same.txt", b"alpha", base=del_sandbox.outside)
        (del_sandbox.run_dir() / "a.txt").unlink()
        links.symlink(del_sandbox.run_dir() / "a.txt", same, is_dir=False)
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload), before, rc=EXIT_CLEAN_MISMATCH
        )

    def test_run_dir_replaced_by_link_to_copy_is_not_deleted(
        self, del_sandbox: _DeleteSandbox, links: LinkFactory
    ) -> None:
        del_sandbox.populate()
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        copy = del_sandbox.outside / "copy"
        shutil.copytree(del_sandbox.run_dir(), copy)
        shutil.rmtree(del_sandbox.run_dir())
        links.symlink(del_sandbox.run_dir(), copy, is_dir=True)
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(del_sandbox.delete(payload), before)
        assert (copy / "a.txt").read_bytes() == b"alpha"


def _skip_unless_permissions_work(path: Path, mode: int) -> None:
    if os.access(path, mode):
        pytest.skip("この環境では権限で制限できない（Windows・root）")


class TestCleanDeletePermissionsInShell:
    """権限で消せない・読めないもの（Linux で root でないときだけ）."""

    def test_undeletable_file_gives_no_marker(self, del_sandbox: _DeleteSandbox) -> None:
        """SPEC_03「clean」: 消した後も残っていれば，目印を出さずに 0 以外（97 か 96）."""
        del_sandbox.populate()
        del_sandbox.write("locked/keep.txt", b"k")
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        locked = del_sandbox.run_dir() / "locked"
        before = del_sandbox.snapshot()
        mode = locked.stat().st_mode & 0o7777
        locked.chmod(0o555)
        try:
            _skip_unless_permissions_work(locked, os.W_OK)
            result = del_sandbox.delete(payload)
        finally:
            locked.chmod(mode)
        assert result.returncode in (EXIT_CLEAN_REMAINS, EXIT_CLEAN_MISMATCH)
        assert _MARKER not in result.stdout
        assert _DEL_SECRET.encode() not in result.stdout + result.stderr
        assert (locked / "keep.txt").read_bytes() == b"k"
        # 実験フォルダの外は変わらない（中は一部だけ消えている可能性がある）
        rel = del_sandbox.run_dir().relative_to(del_sandbox.root).as_posix() + "/"
        after = del_sandbox.snapshot()
        assert {k: v for k, v in after.items() if not k.startswith(rel)} == {
            k: v for k, v in before.items() if not k.startswith(rel)
        }

    def test_unhashable_file_is_not_deleted_even_if_list_says_so(
        self, del_sandbox: _DeleteSandbox
    ) -> None:
        """SPEC_03「clean」: 照合でハッシュを取れなかったファイルがあれば，何も消さずに止まる.

        送る一覧に，サーバの一覧と同じ nohash の記録を入れても，一致としない．
        """
        del_sandbox.populate()
        locked = del_sandbox.write("locked.txt", b"secret")
        del_sandbox.guard()
        before = del_sandbox.snapshot()
        mode = locked.stat().st_mode & 0o7777
        locked.chmod(0)
        try:
            _skip_unless_permissions_work(locked, os.R_OK)
            records = del_sandbox.records()
            assert any(r.startswith(CLEAN_NOHASH_PREFIX.encode()) for r in records)
            result = del_sandbox.delete(_payload(records))
        finally:
            if locked.exists():
                locked.chmod(mode)
        assert result.returncode == EXIT_CLEAN_MISMATCH, result.returncode
        assert _MARKER not in result.stdout
        assert del_sandbox.snapshot() == before

    def test_unreadable_folder_is_not_deleted_even_if_list_says_so(
        self, del_sandbox: _DeleteSandbox
    ) -> None:
        """SPEC_03「clean」: 照合で読めないフォルダがあれば，何も消さずに止まる.

        送る一覧に，find の失敗を表す記録を入れても，一致としない．
        """
        del_sandbox.populate()
        del_sandbox.write("locked/hidden.txt", b"h")
        del_sandbox.guard()
        locked = del_sandbox.run_dir() / "locked"
        before = del_sandbox.snapshot()
        mode = locked.stat().st_mode & 0o7777
        locked.chmod(0)
        try:
            _skip_unless_permissions_work(locked, os.R_OK | os.X_OK)
            records = [r for r in del_sandbox.records() if b"/locked/" not in r]
            payload = _payload([*records, CLEAN_FIND_FAILED_RECORD.encode()])
            result = del_sandbox.delete(payload)
        finally:
            if locked.exists():
                locked.chmod(mode)
        assert result.returncode == EXIT_CLEAN_MISMATCH, result.returncode
        assert _MARKER not in result.stdout
        assert del_sandbox.snapshot() == before

    def test_unreadable_run_dir_is_94(self, del_sandbox: _DeleteSandbox) -> None:
        del_sandbox.populate({"a.txt": b"alpha"})
        del_sandbox.guard()
        run_dir = del_sandbox.run_dir()
        before = del_sandbox.snapshot()
        mode = run_dir.stat().st_mode & 0o7777
        run_dir.chmod(0)
        try:
            _skip_unless_permissions_work(run_dir, os.R_OK | os.X_OK)
            result = del_sandbox.delete(_payload([_file_rec("a.txt", b"alpha")]))
        finally:
            run_dir.chmod(mode)
        assert result.returncode == EXIT_UNSAFE_PATH
        assert _MARKER not in result.stdout
        assert del_sandbox.snapshot() == before


class TestCleanDeleteWhereInShell:
    """CDPATH・作業フォルダで，別の場所の同じ名前のフォルダを消さない."""

    def _decoy(self, del_sandbox: _DeleteSandbox, base: Path) -> None:
        del_sandbox.populate(base=base / "runs" / DEL_RUN)
        del_sandbox.populate(base=base / _FAKE_HOME_ONLY / "proj" / "runs" / DEL_RUN)

    def test_cdpath_does_not_redirect(self, del_sandbox: _DeleteSandbox) -> None:
        decoy = del_sandbox.root / "decoy"
        self._decoy(del_sandbox, decoy)
        del_sandbox.populate()
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        env = {"CDPATH": f"{decoy.as_posix()}:."}
        before = del_sandbox.snapshot()
        del_sandbox.assert_only_run_dir_deleted(del_sandbox.delete(payload, env=env), before)
        # remote_dir に結果の置き場が無いときも，CDPATH の先へ行かない
        shutil.rmtree(del_sandbox.results)
        before = del_sandbox.snapshot()
        del_sandbox.assert_nothing_deleted(
            del_sandbox.delete(payload, env=env), before, rc=EXIT_NOT_FOUND
        )

    def test_working_directory_does_not_matter(self, del_sandbox: _DeleteSandbox) -> None:
        elsewhere = del_sandbox.root / "elsewhere"
        self._decoy(del_sandbox, elsewhere)
        del_sandbox.populate()
        del_sandbox.guard()
        payload = del_sandbox.flow_payload()
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(payload, cwd=elsewhere)
        del_sandbox.assert_only_run_dir_deleted(result, before)
        before = del_sandbox.snapshot()
        result = del_sandbox.delete(payload, cwd=elsewhere / "runs")
        del_sandbox.assert_nothing_deleted(result, before, rc=EXIT_NOT_FOUND)


def _delete_script(run_id: str = DEL_RUN, **kwargs: str) -> str:
    """削除のコマンド（`bash -c '<スクリプト>'`）の，スクリプトの部分."""
    remote = kwargs.pop("remote_dir", "~/work/proj")
    results = kwargs.pop("results_dir", "runs")
    command = build_clean_delete_command(remote, results_dir=results, run_id=run_id)
    words = shlex.split(command)
    assert words[:2] == ["bash", "-c"] and len(words) == 3
    return words[2]


# 設定の検証（SPEC_02 の remote_dir）で拒否されるもの．消すコマンドも組み立てない
BAD_DELETE_REMOTE_DIRS = [
    "",
    "   ",
    "proj",
    "work/proj",
    "./proj",
    "../proj",
    "~",
    "~/",
    "/",
    "//",
    "~/./",
    "~/a/../b",
    "/a/..",
    "~user/proj",
]


class TestBuildCleanDeleteCommandString:
    """SPEC_03「clean」の「削除の細部」: 消すコマンドの文字列."""

    @pytest.mark.parametrize("run_id", [*BAD_CLEAN_RUN_IDS, "*", "?", "r1\n", "a/../b", "~"])
    def test_bad_run_id_is_rejected_before_building(self, run_id: str) -> None:
        with pytest.raises(ValueError):
            build_clean_delete_command("~/work/proj", results_dir="runs", run_id=run_id)

    @pytest.mark.parametrize(
        "results_dir",
        [
            "", "..", ".", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b",
            "a\x00b", "a\nb", "a\tb", "nul", "a/con", "a:b", "a*", "a?", "a.",
        ],
    )  # fmt: skip
    def test_bad_results_dir_is_rejected_before_building(self, results_dir: str) -> None:
        with pytest.raises(ValueError):
            build_clean_delete_command("~/work/proj", results_dir=results_dir, run_id=DEL_RUN)

    @pytest.mark.parametrize("remote_dir", BAD_DELETE_REMOTE_DIRS)
    def test_bad_remote_dir_is_rejected_before_building(self, remote_dir: str) -> None:
        """設定で拒否する remote_dir（相対パス・ホームやルートそのもの・..）は，消すコマンドでも."""
        with pytest.raises(ValueError):
            build_clean_delete_command(remote_dir, results_dir="runs", run_id=DEL_RUN)

    @pytest.mark.parametrize("run_id", [DEL_RUN, CLEAN_RUN, "A.b_c-d", "x1"])
    @pytest.mark.parametrize("results_dir", ["runs", "output/runs", "my res"])
    @pytest.mark.parametrize("remote_dir", ["~/work/proj", "/srv/a b/p;q $(id)"])
    def test_only_one_rm_on_the_run_dir(
        self, run_id: str, results_dir: str, remote_dir: str
    ) -> None:
        """消すのは ./<RUN_ID> の 1 つだけ（-- の後．絶対パス・ワイルドカード・変数を使わない）."""
        script = _delete_script(run_id, results_dir=results_dir, remote_dir=remote_dir)
        assert len(re.findall(r"(^|[\s;(|&{])rm(\s|$)", script)) == 1
        for word in ["rmdir", "unlink", "shred", "mv", "truncate", "dd", "tee", "xargs", "eval"]:
            assert not re.search(rf"(^|[\s;(|&{{]){word}(\s|$)", script), word
        words = shlex.split(script)
        i = words.index("rm")
        args = words[i + 1 : words.index("--", i) + 2]
        assert "--one-file-system" in args
        assert args[-2] == "--"
        target = args[-1]
        assert target == f"./{run_id}"
        assert not target.startswith("/") and "*" not in target and "$" not in target
        # rm の行に，ほかの対象が無い（標準エラーを捨てるだけ）
        rest = words[words.index("--", i) + 2]
        assert rest.startswith("2>/dev/null")

    def test_run_id_is_quoted_even_if_shell_would_glob(self) -> None:
        """RUN_ID は引用して埋め込む（検証済みでも，そのままの語にしない）."""
        command = build_clean_delete_command("~/w/p", results_dir="runs", run_id="A.b_c-d")
        assert "./A.b_c-d" in command

    def test_no_eval_and_no_link_following(self) -> None:
        script = _delete_script()
        assert "eval" not in script
        assert "source " not in script
        assert "-follow" not in script
        assert not re.search(r"\bfind\s+-[LHP]\b", script)
        # 目印（@@labremote-clean-deleted）に -delete の文字が含まれるので，語として探す
        for option in ["-delete", "-execdir", "-ok", "-okdir", "-fprint", "-fls", "--dereference"]:
            assert not re.search(rf"\s{option}(\s|$)", script), option
        assert not re.search(r"\b(stat|sha256sum)\s+-L\b", script)

    def test_unset_cdpath_before_cd(self) -> None:
        script = _delete_script()
        assert "unset CDPATH" in script
        assert script.index("unset CDPATH") < script.index("cd ")

    def test_writes_no_files(self) -> None:
        """書き込むリダイレクトは，標準エラーを捨てる 2>/dev/null だけ（一時ファイルを作らない）."""
        script = _delete_script(results_dir="output/runs")
        assert ">" not in script.replace("2>/dev/null", "")
        for word in ["mktemp", "touch", "tee", "cp", "mkdir", "ln", "chmod", "install"]:
            assert not re.search(rf"(^|[\s;(|&{{]){word}(\s|$)", script), word

    def test_stdin_is_only_sorted_and_hashed(self) -> None:
        """送られた一覧（標準入力）を読むのは，並べてハッシュを取る所だけ（read・変数にしない）."""
        script = _delete_script()
        assert not re.search(r"(^|[\s;(|&{])(read|mapfile|readarray)(\s|$)", script)
        assert "/dev/stdin" not in script

    @pytest.mark.parametrize("remote_dir", ["~/work/proj", "/srv/a b/proj", "/srv/x;y $(id)/p"])
    def test_remote_dir_is_one_word(self, remote_dir: str) -> None:
        script = _delete_script(remote_dir=remote_dir)
        targets = _cd_dash_targets(script)
        assert remote_dir.replace("~", "$HOME", 1) in targets

    @pytest.mark.parametrize(
        "build",
        [
            lambda: build_clean_list_command("~/w/p", results_dir="runs", run_id=DEL_RUN),
            lambda: build_ls_command("~/w/p", results_dir="runs"),
        ],
        ids=["clean_list", "ls"],
    )
    def test_list_and_ls_commands_still_have_no_rm(self, build: Callable[[], str]) -> None:
        command = build()
        assert not re.search(r"(^|[\s;(|&'\"{])rm(\s|$)", command)
        assert "-delete" not in command
