Newer
Older
LabRemote / tests / test_cli.py
"""labremote CLI のテスト(SPEC_03).ssh はすべてモックし,実サーバに接続しない.

- 接続できないサーバがあっても他のサーバで続行する(全台不可ならエラー)
- `LABREMOTE_JUMP` が空文字なら踏み台を使わない
- 手元のホスト名がサーバ名と一致したら止まる(`LABREMOTE_ALLOW_SELF=1` で無効化)
- pull は回収ホワイトリストに一致するファイルだけを持ち帰り,回収しなかったファイルの名前を
  出さない.受け取った tar に不正なメンバーがあれば何も展開しない
- run はジョブに LABREMOTE_GIT_COMMIT(未コミットの変更があれば -dirty 付き)を渡す.手元の git は
  subprocess.run をモックする(実プロセスは起動しない)
- run --cpu は GPU を観測・選択せず,CUDA_VISIBLE_DEVICES を空文字で渡す

設定(labremote.yaml)にアドレス・ユーザー名を書くキーは無く,ssh の接続先はサーバ名
(~/.ssh/config の Host 名)になる.
回収の一覧は,テスト用の設定の `results`(tests/results_helpers.py の SAMPLE_RESULTS_YAML)で
与える(SPEC_02「`results`」).
"""

from __future__ import annotations

import io
import logging
import os
import re
import shlex
import subprocess
import sys
import tarfile
import threading
from collections.abc import Callable, Iterator
from importlib.metadata import entry_points
from pathlib import Path

import pytest
import yaml
from clean_helpers import (
    CLEAN_RESULTS_YAML,
    CLEAN_RUN_ID,
    clean_output,
    clean_state_output,
    file_record,
    nohash_record,
    other_record,
    raw_file_record,
    sha,
)
from ls_helpers import (
    dir_record,
    encode_records,
    job_record,
    log_record,
    ls_missing_remote_dir,
    ls_output,
)
from results_helpers import OTHER_RESULTS_YAML, SAMPLE_RESULTS_YAML

import labremote.cli as cli
from labremote.cleanup import CleanCategory, build_clean_expected_input
from labremote.commands import (
    CLEAN_BEGIN_MARKER,
    CLEAN_DELETED_MARKER,
    CLEAN_EXPECT_END_RECORD,
    CLEAN_LOGS_DELETED_MARKER,
    CLEAN_STATE_LINK,
    CLEAN_STATE_MISSING,
    CLEAN_STATE_NOT_DIR,
    CLEAN_STATE_RESULTS_LINK,
    CLEAN_STATE_UNREADABLE,
    EXIT_CLEAN_MISMATCH,
    EXIT_CLEAN_REMAINS,
    EXIT_NOT_FOUND,
    EXIT_NOT_JOB,
    EXIT_REMOTE_DIR_MISSING,
    EXIT_UNSAFE_PATH,
    LS_BEGIN_MARKER,
    PROBE_APPS_MARKER,
    PROBE_APPS_RC_PREFIX,
    PROBE_END_MARKER,
    PROBE_GPU_RC_PREFIX,
    PROBE_GPUS_MARKER,
    PROBE_OWNERS_MARKER,
    PROBE_SAMPLES_MARKER,
    PROBE_SESSIONS_MARKER,
    PROBE_USER_PREFIX,
    RESERVED_ENV_VARS,
    SSH_FAILURE_RC,
    build_clean_delete_command,
    build_clean_list_command,
    build_clean_logs_command,
    build_ls_command,
)
from labremote.gpu import GpuState
from labremote.report import format_clean_deleted, format_project_line

# 設定にアドレスを書くキーは無いため,ssh の接続先はサーバ名になる
NEWTON_ADDR = "Newton"
ARCHIMEDES_ADDR = "Archimedes"
RUN_ID = "20261119-120000_demo_abc1234"

CONFIG_YAML = (
    """\
project:
  name: DemoProject
push: {}
jump_host: labpc
connect_timeout_sec: 15
gpu_free:
  max_memory_used_mib: 1024
  max_utilization_percent: 10
  observe_sec: 10
  sample_interval_ms: 500
servers:
  - name: Newton
    priority: 1
    remote_dir: ~/work/DemoProject
    uv: ~/.local/bin/uv
    data_ready: true
  - name: Archimedes
    priority: 2
    remote_dir: ~/work/DemoProject
    uv: ~/.local/bin/uv
    data_ready: true
"""
    + SAMPLE_RESULTS_YAML
)


def _probe_stdout(gpus: list[tuple[int, int, int]], apps: list[str] | None = None) -> bytes:
    """probe の出力(gpus は (index, 使用中メモリ, 使用率) のリスト.観測サンプルも同じ値)."""
    lines = [f"{PROBE_USER_PREFIX}carol", PROBE_SESSIONS_MARKER, PROBE_GPUS_MARKER]
    lines += [f"{i}, GPU-{i}, NVIDIA RTX A6000, {mem}, 49140, {util}" for i, mem, util in gpus]
    lines.append(f"{PROBE_GPU_RC_PREFIX}0")
    lines.append(PROBE_SAMPLES_MARKER)
    lines += [f"{i}, {util}, {mem}" for i, mem, util in gpus for _ in range(3)]
    lines.append(PROBE_APPS_MARKER)
    lines += apps or []
    lines += [f"{PROBE_APPS_RC_PREFIX}0", PROBE_OWNERS_MARKER, PROBE_END_MARKER]
    return ("\n".join(lines) + "\n").encode()


class FakeSsh:
    """`_run_ssh` の代わり.接続先(argv の最後から 2 番目)ごとに応答を返し,呼び出しを記録する."""

    def __init__(self, responses: dict[str, Callable[[list[str]], cli._SshResult]]) -> None:
        self.responses = responses
        self.calls: list[list[str]] = []
        self._lock = threading.Lock()

    def __call__(
        self, argv: list[str], *, input_bytes: bytes | None = None, timeout: float | None = None
    ) -> cli._SshResult:
        with self._lock:
            self.calls.append(list(argv))
        for host, respond in self.responses.items():
            if argv[-2] == host:
                return respond(argv)
        raise AssertionError("想定外の接続先")


def _ok(stdout: bytes) -> Callable[[list[str]], cli._SshResult]:
    return lambda argv: cli._SshResult(0, stdout, b"")


def _fail(rc: int = 255, stderr: bytes = b"ssh: connect to host: Connection timed out"):
    return lambda argv: cli._SshResult(rc, b"", stderr)


class FakeGit:
    """手元の git(`subprocess.run(["git", ...])`)の代わり.git 以外のコマンドは拒否する.

    Attributes:
        head: `git rev-parse --short HEAD` の出力.None なら失敗(リポジトリでない等).
        status: `git status --porcelain` の出力.None なら失敗.
        missing: True なら git が無い(FileNotFoundError).
    """

    def __init__(self) -> None:
        self.head: str | None = "abc1234\n"
        self.status: str | None = ""
        self.missing = False
        self.calls: list[list[str]] = []

    def __call__(self, argv: list[str], *args: object, **kwargs: object):
        argv = list(argv)
        if not argv or argv[0] != "git":
            raise AssertionError("テストが git 以外の実プロセスを起動しようとした")
        self.calls.append(argv)
        if self.missing:
            raise FileNotFoundError("git")
        if "rev-parse" in argv:
            out = self.head
        elif "status" in argv:
            out = self.status
        else:
            raise AssertionError(f"想定外の git コマンド: {argv}")
        if out is None:
            return subprocess.CompletedProcess(argv, 128, "", "fatal: not a git repository")
        return subprocess.CompletedProcess(argv, 0, out, "")


@pytest.fixture
def fake_git(monkeypatch: pytest.MonkeyPatch) -> FakeGit:
    """`run` が手元で求める LABREMOTE_GIT_COMMIT 用の git をモックする(実プロセスは起動しない)."""
    fake = FakeGit()
    monkeypatch.setattr(cli.subprocess, "run", fake)
    return fake


@pytest.fixture
def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fake_git: FakeGit) -> Path:
    """手元のプロジェクトルートを模したディレクトリ(ssh は一切起動させない).

    ルートは labremote.yaml のあるフォルダで決まる(SPEC_01「プロジェクトのルートの見つけ方」).
    """
    root = tmp_path / "proj"
    (root / "src" / "demo_project").mkdir(parents=True)
    (root / "src" / "demo_project" / "__init__.py").write_bytes(b"")
    (root / "pyproject.toml").write_bytes(b"[project]\nname = 'x'\n")
    (root / "labremote.yaml").write_text(CONFIG_YAML, encoding="utf-8")
    monkeypatch.chdir(root)
    for var in ("LABREMOTE_JUMP", "LABREMOTE_ALLOW_SELF"):
        monkeypatch.delenv(var, raising=False)
    monkeypatch.setenv("LABREMOTE_SSH", "ssh")
    monkeypatch.setattr(cli.socket, "gethostname", lambda: "my-laptop")

    def _no_process(*args: object, **kwargs: object) -> None:
        raise AssertionError("テストが実プロセス(ssh)を起動しようとした")

    monkeypatch.setattr(cli, "_popen", _no_process)
    monkeypatch.setattr(cli.subprocess, "Popen", _no_process)
    return root


def _spy_selection(monkeypatch: pytest.MonkeyPatch) -> list:
    picked: list = []
    original = cli.select_gpu

    def spy(*args, **kwargs):
        result = original(*args, **kwargs)
        picked.append(result)
        return result

    monkeypatch.setattr(cli, "select_gpu", spy)
    return picked


# ---------------------------------------------------------------------------
# 接続できないサーバ
# ---------------------------------------------------------------------------


class TestUnreachableServers:
    def test_gpus_continues_with_other_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        picked = _spy_selection(monkeypatch)
        assert cli.main(["gpus"]) == 0
        assert picked[0] is not None
        assert (picked[0].server.name, picked[0].gpu_index) == ("Archimedes", 0)
        assert len(fake.calls) == 2

    def test_run_selects_gpu_on_reachable_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        picked = _spy_selection(monkeypatch)
        rc = cli.main(["run", "--name", "exp1", "--dry-run", "--", "python", "-V"])
        assert rc == 0
        assert picked[0].server.name == "Archimedes"
        assert picked[0].state is GpuState.UNUSED

    def test_unparsable_probe_is_treated_as_unreachable(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh(
            {NEWTON_ADDR: _ok(b"garbage\n"), ARCHIMEDES_ADDR: _ok(_probe_stdout([(1, 5, 0)]))}
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        picked = _spy_selection(monkeypatch)
        assert cli.main(["gpus"]) == 0
        assert (picked[0].server.name, picked[0].gpu_index) == ("Archimedes", 1)

    @pytest.mark.parametrize("subcommand", [["gpus"], ["status"], ["push"]])
    def test_all_unreachable_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, subcommand: list[str]
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _fail()})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(subcommand) != 0

    def test_run_all_unreachable_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _fail()})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) != 0


class TestRunSelection:
    def test_unused_on_lower_priority_server_is_chosen(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        newton = _probe_stdout([(0, 300, 0)], apps=["GPU-0, 4321, 300"])
        fake = FakeSsh({NEWTON_ADDR: _ok(newton), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        picked = _spy_selection(monkeypatch)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        assert picked[0].server.name == "Archimedes"

    def test_no_free_gpu_does_not_start_job(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        busy = _probe_stdout([(0, 20000, 95)])
        fake = FakeSsh({NEWTON_ADDR: _ok(busy), ARCHIMEDES_ADDR: _ok(busy)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["run", "--name", "exp1", "--", "python"]) != 0
        # probe の 2 回だけで,起動のための ssh は呼ばない
        assert len(fake.calls) == 2

    def test_gpu_without_server_is_rejected_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["run", "--name", "exp1", "--gpu", "0", "--", "python"]) != 0
        assert fake.calls == []

    def test_explicit_busy_gpu_is_error_without_force(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        busy = _probe_stdout([(0, 20000, 95)])
        fake = FakeSsh({NEWTON_ADDR: _ok(busy), ARCHIMEDES_ADDR: _ok(busy)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        args = ["run", "--name", "e", "--server", "Newton", "--gpu", "0", "--dry-run", "--", "x"]
        assert cli.main(args) != 0
        assert cli.main([*args[:7], "--force", *args[7:]]) == 0


# ---------------------------------------------------------------------------
# 環境変数
# ---------------------------------------------------------------------------


class TestEnvironment:
    def _run_gpus(self, monkeypatch: pytest.MonkeyPatch) -> FakeSsh:
        fake = FakeSsh(
            {
                NEWTON_ADDR: _ok(_probe_stdout([(0, 5, 0)])),
                ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)])),
            }
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["gpus"]) == 0
        return fake

    def test_config_jump_host_is_used(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        fake = self._run_gpus(monkeypatch)
        for argv in fake.calls:
            assert argv[argv.index("-J") + 1] == "labpc"
            assert "BatchMode=yes" in argv

    def test_empty_jump_env_means_direct(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setenv("LABREMOTE_JUMP", "")
        fake = self._run_gpus(monkeypatch)
        assert fake.calls
        for argv in fake.calls:
            assert "-J" not in argv

    def test_self_server_is_detected(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(cli.socket, "gethostname", lambda: "Newton")
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["gpus"]) != 0
        assert fake.calls == []

    def test_allow_self_disables_detection(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(cli.socket, "gethostname", lambda: "Newton")
        monkeypatch.setenv("LABREMOTE_ALLOW_SELF", "1")
        fake = self._run_gpus(monkeypatch)
        assert len(fake.calls) == 2


# ---------------------------------------------------------------------------
# pull
# ---------------------------------------------------------------------------

LISTING_NAMES = [
    "config.yaml",
    "history.csv",
    "metrics.json",
    "log.txt",
    "figures/loss.png",
    "figures/iou.png",
    "split.json",
    "predictions.csv",
    "P0001_yamada.png",
    "manifest.csv",
    "figures/sub/P0002_suzuki.png",
    "checkpoints/epoch3.pth",
    "checkpoints/best.pth",
    "checkpoints/Model.onnx",
]
ALLOWED = LISTING_NAMES[:6]
CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/Model.onnx"]
SECRET_NAMES = [
    "split.json",
    "predictions.csv",
    "P0001_yamada",
    "manifest.csv",
    "P0002_suzuki",
    "epoch3",
]


def _listing() -> bytes:
    return b"".join(f"f {RUN_ID}/{name}\0".encode() for name in LISTING_NAMES)


def _tar_of(names: list[str]) -> bytes:
    buffer = io.BytesIO()
    with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as tar:
        for name in names:
            data = f"content of {name}".encode()
            info = tarfile.TarInfo(name)
            info.size = len(data)
            tar.addfile(info, io.BytesIO(data))
    return buffer.getvalue()


class FakeReceive:
    """`_receive_tar` の代わり.要求されたパスの tar(と任意の追加メンバー)を返す."""

    def __init__(self, extra: list[str] | None = None) -> None:
        self.extra = extra or []
        self.requested: list[str] = []

    def __call__(self, argv: list[str], payload: bytes, destination) -> cli._SshResult:
        self.requested = [p.decode() for p in payload.split(b"\0") if p]
        destination.write(_tar_of(self.requested + self.extra))
        return cli._SshResult(0, b"", b"")


def _setup_pull(monkeypatch: pytest.MonkeyPatch, receive: FakeReceive) -> FakeSsh:
    fake = FakeSsh(
        {
            NEWTON_ADDR: _ok(_listing()),
            ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND, stderr=b""),
        }
    )
    monkeypatch.setattr(cli, "_run_ssh", fake)
    monkeypatch.setattr(cli, "_receive_tar", receive)
    return fake


def _local_files(root: Path) -> list[str]:
    run = root / "runs" / RUN_ID
    if not run.exists():
        return []
    return sorted(p.relative_to(run).as_posix() for p in run.rglob("*") if p.is_file())


class TestPull:
    def test_pulls_only_whitelisted_files(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        caplog.set_level(logging.DEBUG)
        receive = FakeReceive()
        _setup_pull(monkeypatch, receive)
        assert cli.main(["pull", RUN_ID]) == 0
        assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in ALLOWED)
        assert _local_files(project) == sorted(ALLOWED)
        captured = capsys.readouterr()
        output = captured.out + captured.err + caplog.text
        for secret in SECRET_NAMES:
            assert secret not in output
        # 回収しなかった件数(split・predictions・画像 2・manifest・重み 3 の 8 件)と,
        # そのうち --with-checkpoints で回収できる件数(2 件)は示す
        assert "8 件" in output
        assert "2 件は --with-checkpoints で回収できる" in output

    @pytest.mark.parametrize("flag", ["--with-checkpoints", "--checkpoints"])
    def test_with_checkpoints(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, flag: str
    ) -> None:
        receive = FakeReceive()
        _setup_pull(monkeypatch, receive)
        assert cli.main(["pull", RUN_ID, flag]) == 0
        # split.json・predictions.csv・指定外の重みは --with-checkpoints でも回収しない
        expected = [*ALLOWED, *CHECKPOINTS]
        assert _local_files(project) == sorted(expected)
        assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in expected)

    @pytest.mark.parametrize(
        "extra",
        [
            f"{RUN_ID}/split.json",
            f"{RUN_ID}/predictions.csv",
            f"{RUN_ID}/P0001_yamada.png",
            f"{RUN_ID}/checkpoints/best.pth",
            f"{RUN_ID}/figures/P0001_yamada:x.png",
            f"{RUN_ID}/Config.yaml",
            f"{RUN_ID}/../evil.txt",
            "../evil.txt",
            "other_run/config.yaml",
        ],
    )
    def test_malicious_archive_extracts_nothing(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        extra: str,
    ) -> None:
        caplog.set_level(logging.DEBUG)
        _setup_pull(monkeypatch, FakeReceive(extra=[extra]))
        assert cli.main(["pull", RUN_ID]) != 0
        assert _local_files(project) == []
        assert not (project / "runs" / "evil.txt").exists()
        assert not (project / "evil.txt").exists()
        captured = capsys.readouterr()
        output = captured.out + captured.err + caplog.text
        assert "P0001_yamada" not in output
        assert "split.json" not in output
        assert "predictions.csv" not in output

    @pytest.mark.parametrize(
        "run_id",
        ["../etc", "a/b", "a\\b", "..", "x..y", ".x", "a;b", "$(id)", "a b", "C:x", "a\n"],
    )
    def test_invalid_run_id_is_rejected_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["pull", run_id]) != 0
        assert fake.calls == []

    def test_run_on_multiple_servers_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _ok(_listing()), ARCHIMEDES_ADDR: _ok(_listing())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.setattr(cli, "_receive_tar", FakeReceive())
        assert cli.main(["pull", RUN_ID]) != 0
        assert cli.main(["pull", RUN_ID, "--server", "Newton"]) == 0

    def test_run_not_found_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"")
        fake = FakeSsh({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["pull", RUN_ID]) != 0


# ---------------------------------------------------------------------------
# push
# ---------------------------------------------------------------------------


class TestPush:
    def test_dry_run_lists_code_but_not_excluded(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        # data・archive・重みは設定の push に書いたときに送られない(SPEC_02「`push`」)
        _write_config_data(
            project,
            lambda data: data.update(
                push={"exclude_root": ["data", "archive"], "exclude_suffixes": [".pth", ".onnx"]}
            ),
        )
        for rel in [
            "data/synthetic/manifest.csv",
            "runs/x/metrics.json",
            ".claude/a.md",
            "archive/source/main.py",
            "src/demo_project/models/best.pth",
            "configs/Model.ONNX",
            ".env",
            "src/demo_project/data/bundle.py",
        ]:
            path = project / rel
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(b"x")
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["push", "--dry-run"]) == 0
        out = capsys.readouterr().out
        assert "pyproject.toml" in out
        # 設定ファイルはサーバで使わないため送らない(SPEC_01「安全の枠」)
        assert "labremote.yaml" not in out
        assert "data/synthetic" not in out
        assert "runs/x" not in out
        assert ".claude" not in out
        assert "archive" not in out
        assert "best.pth" not in out
        assert "Model.ONNX" not in out
        assert ".env" not in out
        # data/ の除外は直下だけ(パッケージの data/ は送る)
        assert "src/demo_project/data/bundle.py" in out
        assert fake.calls == []


# ---------------------------------------------------------------------------
# run: LABREMOTE_GIT_COMMIT(SPEC_03「run」・SPEC_01「環境変数」)
# ---------------------------------------------------------------------------


def _spy_job_script(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
    """`build_job_script` に渡された引数(env・gpu_index・server_name)を記録する."""
    captured: list[dict] = []
    original = cli.build_job_script

    def spy(*args, **kwargs):
        captured.append(kwargs)
        return original(*args, **kwargs)

    monkeypatch.setattr(cli, "build_job_script", spy)
    return captured


def _free_everywhere(monkeypatch: pytest.MonkeyPatch) -> FakeSsh:
    fake = FakeSsh(
        {
            NEWTON_ADDR: _ok(_probe_stdout([(0, 5, 0)])),
            ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)])),
        }
    )
    monkeypatch.setattr(cli, "_run_ssh", fake)
    return fake


# git の情報が取れない場合(git が無い・リポジトリでない・変更状況が取れない)
GIT_FAILURES = ["missing", "not_repo", "status_fails"]


def _break_git(fake_git: FakeGit, failure: str) -> None:
    """`GIT_FAILURES` の 1 つの失敗を `fake_git` に設定する."""
    if failure == "missing":
        fake_git.missing = True
    elif failure == "not_repo":
        fake_git.head = None
    else:
        fake_git.status = None


class TestRunGitCommit:
    def test_clean_tree_passes_short_hash(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        fake_git: FakeGit,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        assert captured[0]["env"]["LABREMOTE_GIT_COMMIT"] == "abc1234"
        # ジョブのスクリプトに実際に export される
        assert "export LABREMOTE_GIT_COMMIT=abc1234" in capsys.readouterr().out
        assert fake_git.calls

    def test_dirty_tree_appends_suffix(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        fake_git: FakeGit,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        fake_git.status = " M src/demo_project/schema.py\n"
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        assert captured[0]["env"]["LABREMOTE_GIT_COMMIT"] == "abc1234-dirty"
        assert "export LABREMOTE_GIT_COMMIT=abc1234-dirty" in capsys.readouterr().out

    @pytest.mark.parametrize("failure", GIT_FAILURES)
    def test_git_unavailable_does_not_set_variable(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        fake_git: FakeGit,
        capsys: pytest.CaptureFixture[str],
        failure: str,
    ) -> None:
        _break_git(fake_git, failure)
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        # git が使えなくてもジョブは起動できる(変数を渡さないだけで,実験 ID の作り方には触れない)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        assert "LABREMOTE_GIT_COMMIT" not in captured[0]["env"]
        assert "LABREMOTE_GIT_COMMIT" not in capsys.readouterr().out

    @pytest.mark.parametrize("git_ok", [True, False])
    def test_env_option_cannot_override_git_commit(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, fake_git: FakeGit, git_ok: bool
    ) -> None:
        fake_git.missing = not git_ok
        fake = _free_everywhere(monkeypatch)
        args = ["run", "--name", "exp1", "--env", "LABREMOTE_GIT_COMMIT=fake", "--", "python"]
        assert cli.main(args) != 0
        # probe の 2 回だけで,起動のための ssh は呼ばない
        assert len(fake.calls) == 2


# ---------------------------------------------------------------------------
# run --cpu(SPEC_03「run」)
# ---------------------------------------------------------------------------


def _probe_stdout_instant() -> bytes:
    """観測なし(瞬間値のみ)の probe の出力.GPU は使用中."""
    lines = [
        PROBE_SESSIONS_MARKER,
        PROBE_GPUS_MARKER,
        "0, GPU-0, NVIDIA RTX A6000, 20000, 49140, 95",
        f"{PROBE_GPU_RC_PREFIX}0",
        PROBE_APPS_MARKER,
        "GPU-0, 4321, 20000",
        f"{PROBE_APPS_RC_PREFIX}0",
        PROBE_OWNERS_MARKER,
        PROBE_END_MARKER,
    ]
    return ("\n".join(lines) + "\n").encode()


def _forbid_gpu_selection(monkeypatch: pytest.MonkeyPatch) -> None:
    def forbidden(*args: object, **kwargs: object) -> None:
        raise AssertionError("--cpu で GPU を選ぼうとした")

    monkeypatch.setattr(cli, "select_gpu", forbidden)


def _write_remote_config(project: Path, *, newton_data_ready: bool) -> None:
    text = CONFIG_YAML
    if not newton_data_ready:
        text = text.replace("data_ready: true", "data_ready: false", 1)
    (project / "labremote.yaml").write_text(text, encoding="utf-8")


class TestRunCpu:
    def _setup(
        self,
        monkeypatch: pytest.MonkeyPatch,
        *,
        newton_ok: bool = True,
        archimedes_ok: bool = True,
    ) -> tuple[FakeSsh, list[dict]]:
        # GPU はすべて使用中にしておく(--cpu では GPU の状態に関わらず起動できること)
        fake = FakeSsh(
            {
                NEWTON_ADDR: _ok(_probe_stdout_instant()) if newton_ok else _fail(),
                ARCHIMEDES_ADDR: _ok(_probe_stdout_instant()) if archimedes_ok else _fail(),
            }
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        _forbid_gpu_selection(monkeypatch)
        return fake, _spy_job_script(monkeypatch)

    def test_does_not_observe_or_select_gpu(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake, captured = self._setup(monkeypatch)
        args = ["run", "--name", "export1", "--cpu", "--dry-run", "--", "demo-export", "--run", "x"]
        assert cli.main(args) == 0
        assert fake.calls
        for argv in fake.calls:
            remote_command = argv[-1]
            assert PROBE_SAMPLES_MARKER not in remote_command
            assert "-lms" not in remote_command
            assert "pmon" not in remote_command
        assert captured[0]["gpu_index"] is None

    def test_cuda_visible_devices_is_empty_string(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _fake, captured = self._setup(monkeypatch)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0
        env = captured[0]["env"]
        assert "CUDA_VISIBLE_DEVICES" in env
        assert env["CUDA_VISIBLE_DEVICES"] == ""
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"

    def test_log_header_says_no_gpu(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        self._setup(monkeypatch)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0
        assert "gpu=なし(CPU)" in capsys.readouterr().out

    def test_without_server_uses_highest_priority_reachable(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _fake, captured = self._setup(monkeypatch)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0
        assert captured[0]["server_name"] == "Newton"

    def test_unreachable_server_is_skipped(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _fake, captured = self._setup(monkeypatch, newton_ok=False)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0
        assert captured[0]["server_name"] == "Archimedes"

    def test_all_unreachable_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _fake, captured = self._setup(monkeypatch, newton_ok=False, archimedes_ok=False)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) != 0
        assert captured == []

    def test_explicit_server(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        _fake, captured = self._setup(monkeypatch)
        args = ["run", "--name", "s", "--cpu", "--server", "Archimedes", "--dry-run", "--", "x"]
        assert cli.main(args) == 0
        assert captured[0]["server_name"] == "Archimedes"

    def test_explicit_unreachable_server_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _fake, captured = self._setup(monkeypatch, archimedes_ok=False)
        args = ["run", "--name", "s", "--cpu", "--server", "Archimedes", "--dry-run", "--", "x"]
        assert cli.main(args) != 0
        assert captured == []

    def test_data_not_ready_server_is_skipped_without_no_data(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _write_remote_config(project, newton_data_ready=False)
        _fake, captured = self._setup(monkeypatch)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0
        assert captured[0]["server_name"] == "Archimedes"

    def test_no_data_includes_not_ready_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _write_remote_config(project, newton_data_ready=False)
        _fake, captured = self._setup(monkeypatch)
        args = ["run", "--name", "s", "--cpu", "--no-data", "--dry-run", "--", "x"]
        assert cli.main(args) == 0
        assert captured[0]["server_name"] == "Newton"

    @pytest.mark.parametrize(
        "extra",
        [
            ["--gpu", "0", "--server", "Newton"],
            ["--gpu", "0"],
            ["--force"],
            ["--observe", "0"],
            ["--observe", "10"],
        ],
    )
    def test_gpu_options_are_rejected_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, extra: list[str]
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["run", "--name", "s", "--cpu", *extra, "--dry-run", "--", "x"]) != 0
        assert fake.calls == []

    def test_launch_on_selected_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # --no-push で起動まで進める(起動の ssh もモック)
        fake, captured = self._setup(monkeypatch)
        assert cli.main(["run", "--name", "s", "--cpu", "--no-push", "--", "x"]) == 0
        launch = fake.calls[-1]
        assert launch[-2] == NEWTON_ADDR
        assert "tmux" in launch[-1]
        assert captured[0]["env"]["CUDA_VISIBLE_DEVICES"] == ""


# ---------------------------------------------------------------------------
# ジョブの起動・引数の誤り・pull・logs と kill・表示の文字コードの確認
# ---------------------------------------------------------------------------

# シェルが特別に解釈する文字を含むコマンド引数
NASTY_ARGS = ["a b", "it's", 'say "hi"', "x; rm -rf ~", "$(id)", "`id`", "$HOME", "*", ""]


def _uv_run_args_of_launch(remote_command: str) -> list[str]:
    """起動の ssh に渡したリモートコマンドから,最終的に `uv run` へ渡る引数を取り出す.

    tmux の new-session の引数 → `bash -c` のスクリプト → `uv run` の引数の順に,
    POSIX シェルの解釈(shlex)で引用を外す.
    """
    tokens = shlex.split(remote_command)
    i = tokens.index("new-session")
    inner = shlex.split(tokens[i + 6])
    assert inner[:2] == ["bash", "-c"]
    script_tokens = shlex.split(inner[2])
    start = script_tokens.index("$HOME/.local/bin/uv") + 1
    assert script_tokens[start] == "run"
    return script_tokens[start + 1 : script_tokens.index("<", start)]


class TestRunLaunch:
    def test_nasty_arguments_reach_uv_run_unchanged(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _free_everywhere(monkeypatch)
        command = ["demo-train", "--config", *NASTY_ARGS]
        assert cli.main(["run", "--name", "train1", "--no-push", "--", *command]) == 0
        launch = fake.calls[-1]
        assert launch[-2] == NEWTON_ADDR
        assert _uv_run_args_of_launch(launch[-1]) == command

    def test_launch_uses_host_name_only(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "train1", "--no-push", "--", "demo-train"]) == 0
        for argv in fake.calls:
            assert argv[-2] in {NEWTON_ADDR, ARCHIMEDES_ADDR}
            assert not any("@" in arg for arg in argv[:-1])
            assert "BatchMode=yes" in argv

    def test_launch_exports_selected_gpu_and_git_commit(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _free_everywhere(monkeypatch)
        args = ["run", "--name", "t", "--no-push", "--env", "DEMO_DATA_DIR=data/synthetic"]
        assert cli.main([*args, "--", "demo-train"]) == 0
        script = shlex.split(shlex.split(fake.calls[-1][-1])[-1])[2]
        for statement in [
            "export CUDA_DEVICE_ORDER=PCI_BUS_ID",
            "export CUDA_VISIBLE_DEVICES=0",
            "export PYTHONUNBUFFERED=1",
            "export LABREMOTE_GIT_COMMIT=abc1234",
            "export DEMO_DATA_DIR=data/synthetic",
        ]:
            assert statement in script
        assert "TIAS_DATA_ROOT" not in script

    @pytest.mark.parametrize(
        "item",
        [
            "CUDA_VISIBLE_DEVICES=1",
            "CUDA_DEVICE_ORDER=FASTEST_FIRST",
            "PYTHONUNBUFFERED=0",
            "LABREMOTE_GIT_COMMIT=fake",
            "BAD KEY=x",
            "1X=y",
            "NOEQUALS",
        ],
    )
    def test_reserved_or_bad_env_is_rejected_without_launch(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, item: str
    ) -> None:
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "t", "--no-push", "--env", item, "--", "x"]) == 1
        # probe だけで,起動の ssh は呼ばない
        assert all("new-session" not in argv[-1] for argv in fake.calls)

    def test_busy_gpu_is_not_used_without_force(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        busy = _probe_stdout([(0, 20000, 95)])
        fake = FakeSsh({NEWTON_ADDR: _ok(busy), ARCHIMEDES_ADDR: _ok(busy)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        args = ["run", "--name", "t", "--server", "Newton", "--gpu", "0", "--no-push"]
        assert cli.main([*args, "--", "x"]) == 1
        assert all("new-session" not in argv[-1] for argv in fake.calls)
        # 自動選択でも使用中の GPU は選ばない
        assert cli.main(["run", "--name", "t", "--no-push", "--", "x"]) == 1
        assert all("new-session" not in argv[-1] for argv in fake.calls)
        # --force を付けたときだけ使う
        assert cli.main([*args, "--force", "--", "x"]) == 0
        assert "new-session" in fake.calls[-1][-1]

    def test_cpu_launch_hides_gpus(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "t", "--cpu", "--no-push", "--", "demo-export"]) == 0
        script = shlex.split(shlex.split(fake.calls[-1][-1])[-1])[2]
        assert "export CUDA_VISIBLE_DEVICES=''" in script
        assert "gpu=なし(CPU)" in script

    @pytest.mark.parametrize("name", ["a b", "x;id", "-x", "_x", "a.b", "a/b", "$(id)"])
    def test_bad_job_name_is_rejected_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, name: str
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        try:
            rc = cli.main(["run", "--name", name, "--", "x"])
        except SystemExit as exc:  # - 始まりは argparse が引数の誤りとして止める
            rc = exc.code
        assert rc in (1, 2)
        assert fake.calls == []

    def test_session_exists_returns_91(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        probe = _ok(_probe_stdout([(0, 5, 0)]))

        def respond(argv: list[str]) -> cli._SshResult:
            if "new-session" in argv[-1]:
                return cli._SshResult(91, b"", b"labremote: tmux session already exists: t")
            return probe(argv)

        monkeypatch.setattr(
            cli, "_run_ssh", FakeSsh({NEWTON_ADDR: respond, ARCHIMEDES_ADDR: probe})
        )
        assert cli.main(["run", "--name", "t", "--no-push", "--", "x"]) == 91


class TestArgumentErrors:
    @pytest.mark.parametrize(
        "args",
        [
            [],
            ["unknown"],
            ["run", "--", "x"],  # --name が無い
            ["run", "--name", "t", "--gpu", "x", "--", "x"],
            ["pull"],
            ["pull", RUN_ID, "--bogus"],
            ["logs"],
        ],
    )
    def test_argument_errors_exit_2(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, args: list[str]
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        with pytest.raises(SystemExit) as excinfo:
            cli.main(args)
        assert excinfo.value.code == 2
        assert fake.calls == []

    def test_config_option_is_used(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
    ) -> None:
        other = tmp_path / "other.yaml"
        other.write_text(CONFIG_YAML.replace("jump_host: labpc", "jump_host: otherjump"), "utf-8")
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["gpus", "--config", str(other)]) == 0
        for argv in fake.calls:
            assert argv[argv.index("-J") + 1] == "otherjump"

    def test_bad_config_is_error_1(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
    ) -> None:
        bad = tmp_path / "bad.yaml"
        bad.write_text("servers: [\n", encoding="utf-8")
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["gpus", "--config", str(bad)]) == 1
        unknown = tmp_path / "unknown.yaml"
        unknown.write_text(CONFIG_YAML + "data_dir: x\n", encoding="utf-8")
        assert cli.main(["gpus", "--config", str(unknown)]) == 1
        assert fake.calls == []


class TestPullMore:
    def test_split_and_predictions_never_pulled_even_with_checkpoints(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        receive = FakeReceive()
        _setup_pull(monkeypatch, receive)
        assert cli.main(["pull", RUN_ID, "--with-checkpoints"]) == 0
        for name in ["split.json", "predictions.csv", "manifest.csv", "checkpoints/epoch3.pth"]:
            assert f"{RUN_ID}/{name}" not in receive.requested
            assert not (project / "runs" / RUN_ID / name).exists()

    def test_run_dir_link_on_server_is_refused(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        receive = FakeReceive()
        fake = FakeSsh(
            {NEWTON_ADDR: _fail(rc=94, stderr=b""), ARCHIMEDES_ADDR: _fail(rc=92, stderr=b"")}
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.setattr(cli, "_receive_tar", receive)
        assert cli.main(["pull", RUN_ID]) != 0
        assert receive.requested == []
        assert _local_files(project) == []

    def test_nothing_to_pull_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        listing = f"f {RUN_ID}/split.json\0f {RUN_ID}/predictions.csv\0".encode()
        receive = FakeReceive()
        fake = FakeSsh({NEWTON_ADDR: _ok(listing), ARCHIMEDES_ADDR: _fail(rc=92, stderr=b"")})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.setattr(cli, "_receive_tar", receive)
        assert cli.main(["pull", RUN_ID]) == 1
        assert receive.requested == []


class TestLogsAndKill:
    def test_logs_not_found_anywhere_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"")
        monkeypatch.setattr(
            cli, "_run_ssh", FakeSsh({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing})
        )
        assert cli.main(["logs", "train1"]) != 0

    def test_logs_shows_tail_from_the_server_with_the_log(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        def newton(argv: list[str]) -> cli._SshResult:
            if "tail" in argv[-1]:
                return cli._SshResult(0, b"epoch 1\n", b"")
            return cli._SshResult(0, b"", b"")

        fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND, stderr=b"")})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["logs", "train1", "-n", "5"]) == 0
        assert "epoch 1" in capsys.readouterr().out
        assert "tail -n 5 runs/_remote_logs/train1.log" in fake.calls[-1][-1]

    def test_kill_refuses_non_job_session(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        lines = [
            PROBE_SESSIONS_MARKER,
            "other mywork",
            PROBE_GPUS_MARKER,
            f"{PROBE_GPU_RC_PREFIX}127",
        ]
        text = ("\n".join([*lines, PROBE_END_MARKER]) + "\n").encode()
        fake = FakeSsh({NEWTON_ADDR: _ok(text), ARCHIMEDES_ADDR: _ok(text)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["kill", "mywork"]) == 1
        assert all("kill-session" not in argv[-1] for argv in fake.calls)

    @pytest.mark.parametrize("remote_rc", [EXIT_NOT_JOB, EXIT_REMOTE_DIR_MISSING])
    def test_kill_reports_server_side_refusal(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        remote_rc: int,
    ) -> None:
        """SPEC_03「logs・kill」: サーバが止めなかったこと(ログ・置き場が無い)を示して 0 以外."""
        caplog.set_level(logging.DEBUG)

        def newton(argv: list[str]) -> cli._SshResult:
            if "kill-session" in argv[-1]:
                return cli._SshResult(remote_rc, b"", b"labremote: refused\n")
            return cli._SshResult(0, _probe_with_sessions(["job train1"]), b"")

        fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _ok(_probe_with_sessions([]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["kill", "train1"]) != 0
        captured = capsys.readouterr()
        output = captured.out + captured.err + caplog.text
        assert "train1" in output
        assert "止め" in output  # 「止めなかった」に当たる内容(文言は 1-7b で変わりうる)

    @pytest.mark.parametrize("flag", ["--force", "--any", "--all"])
    def test_kill_has_no_flag_to_stop_sessions_without_log(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, flag: str
    ) -> None:
        """SPEC_03「logs・kill」: ログが無いセッションを止めるための引数は設けない."""
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        with pytest.raises(SystemExit) as excinfo:
            cli.main(["kill", "train1", flag])
        assert excinfo.value.code == 2
        assert fake.calls == []


class TestTolerateUnencodableOutput:
    @pytest.mark.parametrize("make_stream", [io.StringIO, lambda: None])
    def test_streams_without_reconfigure_are_skipped(
        self, monkeypatch: pytest.MonkeyPatch, make_stream: Callable[[], object]
    ) -> None:
        """SPEC_03「表示と文字コード」: 差し替えた出力(StringIO・None)でも設定で落ちない."""
        stdout, stderr = make_stream(), make_stream()
        monkeypatch.setattr(sys, "stdout", stdout)
        monkeypatch.setattr(sys, "stderr", stderr)
        cli._tolerate_unencodable_output()
        assert sys.stdout is stdout
        assert sys.stderr is stderr


# ---------------------------------------------------------------------------
# 安全策の補強: Windows の予約名・末尾の `.`,送らなかったリンクの表示,--env の NUL
# ---------------------------------------------------------------------------


# project が subprocess.run・Popen を差し替える前の本物(ジャンクションを作る mklink だけに使う)
_REAL_POPEN = subprocess.Popen


def _symlink_or_skip(link: Path, target: Path) -> None:
    """tmp_path の中に link → target のシンボリックリンクを作る(作れなければ skip)."""
    try:
        os.symlink(target, link, target_is_directory=target.is_dir())
    except (OSError, NotImplementedError) as exc:
        code = getattr(exc, "winerror", None) or getattr(exc, "errno", None)
        pytest.skip(f"この環境ではシンボリックリンクを作れない({type(exc).__name__} {code})")


@pytest.fixture
def junction_or_skip() -> Iterator[Callable[[Path, Path], None]]:
    """link → target のジャンクションを作る関数(Windows のみ).後始末でリンクだけを外す."""
    created: list[Path] = []

    def make(link: Path, target: Path) -> None:
        if sys.platform != "win32":
            pytest.skip("ジャンクションは Windows のみ")
        # project が subprocess.run・Popen を差し替えるため,読み込み時の本物を使う
        with _REAL_POPEN(
            ["cmd", "/c", "mklink", "/J", str(link), str(target)],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        ) as process:
            returncode = process.wait()
        if returncode != 0 or not os.path.isjunction(link):
            pytest.skip("この環境ではジャンクションを作れない")
        created.append(link)

    yield make
    for link in reversed(created):
        if os.path.isjunction(link):
            os.rmdir(link)


@pytest.fixture
def outside(tmp_path: Path) -> Path:
    """「リポジトリの外」役のフォルダ(tmp_path の中.project とは別のフォルダ)."""
    root = tmp_path / "outside"
    (root / "patients").mkdir(parents=True)
    (root / "patients" / "P0001_yamada.png").write_bytes(b"png")
    (root / "secret_code.py").write_bytes(b"x")
    return root


class TestPushDryRunLinks:
    def _dry_run(self, monkeypatch: pytest.MonkeyPatch) -> tuple[FakeSsh, int]:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        return fake, cli.main(["push", "--dry-run"])

    def test_no_links_reports_zero(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        fake, rc = self._dry_run(monkeypatch)
        assert rc == 0
        assert "送らなかったリンク: 0 件" in capsys.readouterr().out
        assert fake.calls == []

    def test_directory_junction_to_outside_is_reported_and_not_listed(
        self,
        project: Path,
        outside: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        junction_or_skip: Callable[[Path, Path], None],
    ) -> None:
        junction_or_skip(project / "src" / "ext", outside)
        fake, rc = self._dry_run(monkeypatch)
        assert rc == 0
        out = capsys.readouterr().out
        assert "送らなかったリンク: 1 件" in out
        assert "src/ext" in out
        assert "P0001_yamada" not in out
        assert "secret_code" not in out
        assert "pyproject.toml" in out
        assert fake.calls == []

    def test_symlinks_are_counted(
        self,
        project: Path,
        outside: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        _symlink_or_skip(project / "leak.py", outside / "secret_code.py")
        _symlink_or_skip(project / "src" / "data_alias", outside / "patients")
        fake, rc = self._dry_run(monkeypatch)
        assert rc == 0
        out = capsys.readouterr().out
        assert "送らなかったリンク: 2 件" in out
        assert "P0001_yamada" not in out
        assert "secret_code" not in out
        assert fake.calls == []

    def test_links_in_excluded_directories_are_not_counted(
        self,
        project: Path,
        outside: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        junction_or_skip: Callable[[Path, Path], None],
    ) -> None:
        (project / ".venv").mkdir()
        junction_or_skip(project / ".venv" / "ext", outside)
        fake, rc = self._dry_run(monkeypatch)
        assert rc == 0
        assert "送らなかったリンク: 0 件" in capsys.readouterr().out


class TestWindowsUnsafeNamesInPull:
    @pytest.mark.parametrize("run_id", ["abc.", "nul", "NUL", "con.txt", "Com1", "lpt9.x"])
    def test_reserved_or_trailing_dot_run_id_is_rejected_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["pull", run_id]) != 0
        assert fake.calls == []
        assert not (project / "runs").exists()

    @pytest.mark.parametrize(
        "extra",
        [
            f"{RUN_ID}/figures/CON.png",
            f"{RUN_ID}/figures/nul.png",
            f"{RUN_ID}/figures/COM1.png",
            f"{RUN_ID}/figures/LPT9.png",
            f"{RUN_ID}/figures/Aux.x.png",
            f"{RUN_ID}/figures/nul .png",
            f"{RUN_ID}/config.yaml.",
        ],
    )
    def test_archive_with_reserved_name_extracts_nothing(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, extra: str
    ) -> None:
        _setup_pull(monkeypatch, FakeReceive(extra=[extra]))
        assert cli.main(["pull", RUN_ID]) != 0
        assert _local_files(project) == []


class TestEnvNul:
    @pytest.mark.parametrize("item", ["A=x\x00y", "DEMO_DATA_DIR=\x00"])
    def test_nul_in_env_value_is_rejected_without_launch(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, item: str
    ) -> None:
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "t", "--no-push", "--env", item, "--", "x"]) == 1
        assert all("new-session" not in argv[-1] for argv in fake.calls)

    def test_newline_in_env_value_reaches_job(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        captured = _spy_job_script(monkeypatch)
        _free_everywhere(monkeypatch)
        args = ["run", "--name", "t", "--no-push", "--env", "CODE=a\nb", "--", "x"]
        assert cli.main(args) == 0
        assert captured
        assert captured[-1]["env"]["CODE"] == "a\nb"


# ---------------------------------------------------------------------------
# 名前(SPEC_01「全体像」「環境変数」・SPEC_03「サブコマンド」)
# ---------------------------------------------------------------------------

# 今のステップで動くサブコマンド
SUBCOMMANDS = ["gpus", "status", "push", "run", "logs", "kill", "pull", "ls", "clean"]
# SPEC_03「サブコマンド」に書かれた全部
SPEC_SUBCOMMANDS = {*SUBCOMMANDS, "ls", "clean"}


def _help_text(args: list[str], capsys: pytest.CaptureFixture[str]) -> str:
    with pytest.raises(SystemExit) as excinfo:
        cli.main(args)
    assert excinfo.value.code == 0
    return capsys.readouterr().out


class TestCommandName:
    def test_console_script_points_to_cli_main(self) -> None:
        # SPEC_01「全体像」: コマンドの名前は labremote([project.scripts])
        found = entry_points(group="console_scripts", name="labremote")
        assert [ep.value for ep in found] == ["labremote.cli:main"]
        assert next(iter(found)).load() is cli.main

    def test_old_console_script_is_not_registered(self) -> None:
        # SPEC_01「全体像」: コマンドの名前は labremote(古い tsm-remote は登録しない)
        assert not list(entry_points(group="console_scripts", name="tsm-remote"))

    def test_help_usage_starts_with_labremote(self, capsys: pytest.CaptureFixture[str]) -> None:
        # SPEC_03「サブコマンド」: uv run labremote <サブコマンド> として実行する
        out = _help_text(["--help"], capsys)
        assert out.startswith("usage: labremote ")
        assert "tsm-remote" not in out
        assert "TSM_REMOTE" not in out

    @pytest.mark.parametrize("subcommand", SUBCOMMANDS)
    def test_each_subcommand_exists(
        self, subcommand: str, capsys: pytest.CaptureFixture[str]
    ) -> None:
        # SPEC_03「サブコマンド」: gpus・status・push・run・logs・kill・pull
        out = _help_text([subcommand, "--help"], capsys)
        assert out.startswith(f"usage: labremote {subcommand}")

    def test_subcommands_listed_in_help_are_from_spec(
        self, capsys: pytest.CaptureFixture[str]
    ) -> None:
        # SPEC_03「サブコマンド」: help の一覧は仕様の名前だけで,今のステップの 7 つを含む
        out = _help_text(["--help"], capsys)
        lines = out.splitlines()
        start = next(i for i, line in enumerate(lines) if line.strip() == "SUBCOMMAND")
        listed = set()
        for line in lines[start + 1 :]:
            if not line.startswith("    ") or not line.strip():
                if listed:
                    break
                continue
            if not line.startswith("     "):
                listed.add(line.split()[0])
        assert set(SUBCOMMANDS) <= listed
        assert listed <= SPEC_SUBCOMMANDS

    def test_unknown_subcommand_is_rejected(self, capsys: pytest.CaptureFixture[str]) -> None:
        with pytest.raises(SystemExit) as excinfo:
            cli.main(["bogus"])
        assert excinfo.value.code == 2
        assert capsys.readouterr().err.startswith("usage: labremote ")


class TestOldEnvNames:
    """移す元の名前(`TSM_REMOTE_*`)を設定しても効かない.

    SPEC_01「環境変数」: 手元の環境変数は `LABREMOTE_JUMP`・`LABREMOTE_SSH`・
    `LABREMOTE_ALLOW_SELF`.
    """

    def test_old_jump_env_does_not_disable_jump(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setenv("TSM_REMOTE_JUMP", "")
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["gpus"]) == 0
        assert fake.calls
        for argv in fake.calls:
            assert argv[argv.index("-J") + 1] == "labpc"

    def test_old_ssh_env_is_not_used(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.delenv("LABREMOTE_SSH", raising=False)
        monkeypatch.setenv("TSM_REMOTE_SSH", "old-ssh-binary")
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["gpus"]) == 0
        assert fake.calls
        assert all(argv[0] != "old-ssh-binary" for argv in fake.calls)

    def test_old_allow_self_env_does_not_disable_detection(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(cli.socket, "gethostname", lambda: "Newton")
        monkeypatch.setenv("TSM_REMOTE_ALLOW_SELF", "1")
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["gpus"]) == 1
        assert fake.calls == []


class TestRunGitCommitName:
    def test_job_gets_labremote_git_commit_not_old_name(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        # SPEC_01「環境変数」: ジョブへ渡す git のハッシュは LABREMOTE_GIT_COMMIT
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        env = captured[0]["env"]
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert "TSM_GIT_COMMIT" not in env
        assert "TSM_GIT_COMMIT" not in capsys.readouterr().out


# ---------------------------------------------------------------------------
# ルートの探索を cli.main から(SPEC_01「プロジェクトのルートの見つけ方」)
# ---------------------------------------------------------------------------


def _push_dry_run_names(args: list[str], capsys: pytest.CaptureFixture[str]) -> list[str]:
    """`push --dry-run` の出力から,送る対象のファイル名(ルートからの相対)を取り出す."""
    assert cli.main(["push", "--dry-run", *args]) == 0
    out = capsys.readouterr().out
    names = []
    for line in out.splitlines():
        # "  <大きさ>  <名前>" の行(大きさと名前の間は 2 つの空白)
        if line.startswith("  ") and "  " in line.strip():
            names.append(line.strip().split("  ", 1)[1].strip())
    return names


class TestProjectRootFromCli:
    def test_root_is_config_folder_when_run_there(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01: 実行した場所の labremote.yaml のフォルダが送るファイルの起点."""
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        names = _push_dry_run_names([], capsys)
        assert "pyproject.toml" in names
        assert "src/demo_project/__init__.py" in names
        assert fake.calls == []

    def test_root_is_found_from_subfolder(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01: サブフォルダから実行しても,親へたどった labremote.yaml のフォルダが起点."""
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.chdir(project / "src" / "demo_project")
        names = _push_dry_run_names([], capsys)
        assert "pyproject.toml" in names
        assert "src/demo_project/__init__.py" in names
        assert "__init__.py" not in names
        assert fake.calls == []

    def test_nearest_config_wins(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01: 親と祖先の両方にあれば,最初に見つかった(近い)ほうのフォルダがルート."""
        inner = project / "nested"
        (inner / "deeper").mkdir(parents=True)
        (inner / "labremote.yaml").write_text(CONFIG_YAML, encoding="utf-8")
        (inner / "only_inner.txt").write_text("x", encoding="utf-8")
        monkeypatch.setattr(cli, "_run_ssh", FakeSsh({}))
        monkeypatch.chdir(inner / "deeper")
        names = _push_dry_run_names([], capsys)
        assert "only_inner.txt" in names
        assert "pyproject.toml" not in names
        assert not any(name.startswith("nested/") for name in names)

    @pytest.mark.parametrize("file_name", ["labremote.yaml", "custom.yaml"])
    def test_config_option_sets_root_over_found_config(
        self,
        project: Path,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        file_name: str,
    ) -> None:
        """SPEC_01: `--config PATH` のファイルのあるフォルダがルート(上に別の設定があっても)."""
        other = tmp_path / "other_project"
        other.mkdir()
        (other / file_name).write_text(CONFIG_YAML, encoding="utf-8")
        (other / "marker.txt").write_text("x", encoding="utf-8")
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.chdir(project / "src")
        names = _push_dry_run_names(["--config", str(other / file_name)], capsys)
        assert "marker.txt" in names
        assert "pyproject.toml" not in names
        assert fake.calls == []

    def test_relative_config_option(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01: `--config PATH` は実行した場所からの相対パスでもよい."""
        sub = project / "cfg"
        sub.mkdir()
        (sub / "labremote.yaml").write_text(CONFIG_YAML, encoding="utf-8")
        (sub / "marker.txt").write_text("x", encoding="utf-8")
        monkeypatch.setattr(cli, "_run_ssh", FakeSsh({}))
        names = _push_dry_run_names(["--config", str(Path("cfg") / "labremote.yaml")], capsys)
        assert "marker.txt" in names
        assert "pyproject.toml" not in names

    @pytest.mark.parametrize("subcommand", [["gpus"], ["status"], ["push"], ["pull", RUN_ID]])
    def test_no_config_anywhere_is_error_without_ssh(
        self,
        project: Path,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
        subcommand: list[str],
    ) -> None:
        """SPEC_01: どこにも無ければエラーで止まる(推測でルートを決めない.ssh も呼ばない)."""
        elsewhere = tmp_path / "no_config" / "sub"
        elsewhere.mkdir(parents=True)
        (elsewhere / "pyproject.toml").write_bytes(b"[project]\nname = 'y'\n")
        monkeypatch.chdir(elsewhere)
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(subcommand) == 1
        assert fake.calls == []
        assert not (elsewhere / "runs").exists()

    @pytest.mark.parametrize("kind", ["missing", "directory"])
    def test_config_option_without_file_is_error_without_ssh(
        self, project: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, kind: str
    ) -> None:
        """SPEC_01: `--config` のパスにファイルが無ければ,見つかる設定に頼らずエラー."""
        explicit = tmp_path / "nothing.yaml"
        if kind == "directory":
            explicit.mkdir()
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["gpus", "--config", str(explicit)]) == 1
        assert fake.calls == []

    def test_pull_saves_under_root_from_subfolder(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「pull」: 保存先は `<ルート>/<結果の置き場>/<RUN_ID>/`(実行した場所ではない)."""
        sub = project / "src" / "demo_project"
        monkeypatch.chdir(sub)
        _setup_pull(monkeypatch, FakeReceive())
        assert cli.main(["pull", RUN_ID]) == 0
        assert _local_files(project) == sorted(ALLOWED)
        assert not (sub / "runs").exists()


# ---------------------------------------------------------------------------
# ssh の接続先はサーバ名だけ(SPEC_03「接続」,SPEC_02「`servers`」)
# ---------------------------------------------------------------------------


class TestSshDestinationFromCli:
    @pytest.mark.parametrize("subcommand", [["gpus"], ["status"]])
    def test_destination_is_server_name_only(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, subcommand: list[str]
    ) -> None:
        """SPEC_03「接続」: ssh の接続先は `servers[].name`(ユーザー名・アドレスを付けない)."""
        fake = _free_everywhere(monkeypatch)
        assert cli.main(subcommand) == 0
        assert sorted(argv[-2] for argv in fake.calls) == ["Archimedes", "Newton"]
        for argv in fake.calls:
            # 最後の 1 つはサーバで実行するコマンド.それ以外に @ と -l(ユーザー名)が無い
            assert not any("@" in arg for arg in argv[:-1])
            assert "-l" not in argv[:-1]


# ---------------------------------------------------------------------------
# 設定由来の環境変数と git_commit_env を cli.main から(SPEC_01「環境変数」,SPEC_02「`run`」)
# ---------------------------------------------------------------------------


def _write_config_data(project: Path, mutate: Callable[[dict], None]) -> None:
    data = yaml.safe_load(CONFIG_YAML)
    mutate(data)
    (project / "labremote.yaml").write_text(
        yaml.safe_dump(data, allow_unicode=True), encoding="utf-8"
    )


def _run_dry(args: list[str]) -> list[str]:
    return ["run", "--name", "exp1", "--dry-run", *args, "--", "python"]


class TestGitCommitEnvFromCli:
    def _with_git_commit_env(self, project: Path) -> None:
        def mutate(data: dict) -> None:
            data["project"]["git_commit_env"] = "DEMO_GIT_COMMIT"

        _write_config_data(project, mutate)

    def test_job_gets_both_names(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前でも LABREMOTE_GIT_COMMIT と同じ値を渡す."""
        self._with_git_commit_env(project)
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(_run_dry([])) == 0
        env = captured[0]["env"]
        assert env["LABREMOTE_GIT_COMMIT"] == "abc1234"
        assert env["DEMO_GIT_COMMIT"] == "abc1234"
        out = capsys.readouterr().out
        assert "export LABREMOTE_GIT_COMMIT=abc1234" in out
        assert "export DEMO_GIT_COMMIT=abc1234" in out

    def test_without_git_commit_env_only_labremote_name(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_02「`project`」: 指定しなければ,ハッシュは LABREMOTE_GIT_COMMIT だけで渡す."""
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(_run_dry([])) == 0
        env = captured[0]["env"]
        assert [k for k, v in env.items() if v == "abc1234"] == ["LABREMOTE_GIT_COMMIT"]

    @pytest.mark.parametrize("git_ok", [True, False])
    def test_env_option_cannot_set_git_commit_env(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, fake_git: FakeGit, git_ok: bool
    ) -> None:
        """SPEC_01「環境変数」: git_commit_env の名前は予約で,`--env` で指定すると拒否される."""
        self._with_git_commit_env(project)
        fake_git.missing = not git_ok
        fake = _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        args = ["run", "--name", "exp1", "--env", "DEMO_GIT_COMMIT=fake", "--", "python"]
        assert cli.main(args) != 0
        assert captured == []
        assert all("new-session" not in argv[-1] for argv in fake.calls)


class TestConfigEnvFromCli:
    def _write_env(
        self, project: Path, run_env: dict | None, newton: dict | None, archimedes: dict | None
    ) -> None:
        def mutate(data: dict) -> None:
            if run_env is not None:
                data["run"] = {"env": run_env}
            if newton is not None:
                data["servers"][0]["env"] = newton
            if archimedes is not None:
                data["servers"][1]["env"] = archimedes

        _write_config_data(project, mutate)

    def _env_for(
        self, monkeypatch: pytest.MonkeyPatch, server: str, extra: list[str]
    ) -> dict[str, str]:
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(_run_dry(["--server", server, *extra])) == 0
        assert captured[0]["server_name"] == server
        return captured[0]["env"]

    def test_all_three_sources_priority(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_02「`run`」: 優先の順は run.env → servers[].env → --env(後のものが勝つ)."""
        self._write_env(
            project,
            {"A": "run", "B": "run", "C": "run"},
            {"B": "server", "C": "server"},
            None,
        )
        env = self._env_for(monkeypatch, "Newton", ["--env", "C=cli"])
        assert (env["A"], env["B"], env["C"]) == ("run", "server", "cli")

    @pytest.mark.parametrize(
        ("run_env", "newton", "extra", "expected"),
        [
            ({"X": "run"}, {"X": "server"}, [], "server"),
            ({"X": "run"}, None, ["--env", "X=cli"], "cli"),
            (None, {"X": "server"}, ["--env", "X=cli"], "cli"),
            ({"X": "run"}, None, [], "run"),
        ],
    )
    def test_two_sources_priority(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        run_env: dict | None,
        newton: dict | None,
        extra: list[str],
        expected: str,
    ) -> None:
        """SPEC_02「`run`」: 2 つに同じ名前を書いたときも,後のもの(--env が最後)が勝つ."""
        self._write_env(project, run_env, newton, None)
        assert self._env_for(monkeypatch, "Newton", extra)["X"] == expected

    def test_server_env_only_for_that_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_02「`servers`」: servers[].env はそのサーバのジョブにだけ渡り,他には渡らない."""
        self._write_env(project, {"A": "run"}, {"ONLY_NEWTON": "n"}, {"ONLY_ARCH": "a"})
        env = self._env_for(monkeypatch, "Archimedes", [])
        assert env["A"] == "run"
        assert env["ONLY_ARCH"] == "a"
        assert "ONLY_NEWTON" not in env

    def test_server_env_for_selected_server_without_server_option(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_02「`servers`」: --server が無くても,選ばれたサーバの env だけが渡る."""
        self._write_env(project, None, {"ONLY_NEWTON": "n"}, {"ONLY_ARCH": "a"})
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(_run_dry([])) == 0
        env = captured[0]["env"]
        if captured[0]["server_name"] == "Newton":
            assert env["ONLY_NEWTON"] == "n" and "ONLY_ARCH" not in env
        else:
            assert env["ONLY_ARCH"] == "a" and "ONLY_NEWTON" not in env

    @pytest.mark.parametrize("where", ["run", "newton", "archimedes"])
    @pytest.mark.parametrize(
        "name",
        [
            "CUDA_VISIBLE_DEVICES",
            "CUDA_DEVICE_ORDER",
            "PYTHONUNBUFFERED",
            "LABREMOTE_GIT_COMMIT",
            "DEMO_GIT_COMMIT",
        ],
    )
    @pytest.mark.parametrize("subcommand", [["gpus"], ["push", "--dry-run"], ["run"]])
    def test_reserved_name_in_config_stops_before_ssh(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        where: str,
        name: str,
        subcommand: list[str],
    ) -> None:
        """SPEC_02「`run`」: 予約の名前を設定に書くと,設定を読む時点でエラー(ssh を呼ばない)."""

        def mutate(data: dict) -> None:
            data["project"]["git_commit_env"] = "DEMO_GIT_COMMIT"
            env = {name: "x"}
            if where == "run":
                data["run"] = {"env": env}
            else:
                data["servers"][0 if where == "newton" else 1]["env"] = env

        _write_config_data(project, mutate)
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        args = subcommand if subcommand[0] != "run" else ["run", "--name", "t", "--", "x"]
        assert cli.main(args) == 1
        assert fake.calls == []

    @pytest.mark.parametrize("where", ["run", "newton"])
    @pytest.mark.parametrize(
        ("name", "value"), [("A B", "x"), ("1A", "x"), ("A\n", "x"), ("A", "a\x00b")]
    )
    def test_bad_name_or_nul_value_stops_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, where: str, name: str, value: str
    ) -> None:
        """SPEC_01「名前と値の検証」: 不正な名前・NUL を含む値は設定の時点で止まる."""

        def mutate(data: dict) -> None:
            if where == "run":
                data["run"] = {"env": {name: value}}
            else:
                data["servers"][0]["env"] = {name: value}

        _write_config_data(project, mutate)
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["run", "--name", "t", "--", "x"]) == 1
        assert fake.calls == []

    def test_special_characters_are_quoted_in_remote_command(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_01「名前と値の検証」: 値の特殊文字は引用され,サーバで別のコマンドにならない."""
        values = {
            "SPACE": "a b",
            "SEMI": "x; touch pwned",
            "SUBST": "$(id)",
            "QUOTES": 'it\'s "q"',
            "NEWLINE": "a\ntouch pwned",
        }
        self._write_env(
            project,
            {"SPACE": values["SPACE"], "SEMI": values["SEMI"]},
            {
                "SUBST": values["SUBST"],
                "QUOTES": values["QUOTES"],
                "NEWLINE": values["NEWLINE"],
            },
            None,
        )
        _free_everywhere(monkeypatch)
        built: list[str] = []
        original = cli.build_run_command

        def spy(*args, **kwargs):
            command = original(*args, **kwargs)
            built.append(command)
            return command

        monkeypatch.setattr(cli, "build_run_command", spy)
        assert cli.main(_run_dry(["--server", "Newton"])) == 0
        tokens = shlex.split(built[0])
        inner = shlex.split(tokens[tokens.index("new-session") + 6])
        assert inner[:2] == ["bash", "-c"]
        lexer = shlex.shlex(inner[2], posix=True, punctuation_chars=True)
        lexer.whitespace_split = True
        script_tokens = list(lexer)
        for key, value in values.items():
            i = script_tokens.index(f"{key}={value}")
            assert script_tokens[i - 1] == "export"
            assert script_tokens[i + 1] == ";"
        assert "touch" not in script_tokens


# ---------------------------------------------------------------------------
# push の設定と固定の除外を cli.main から(SPEC_01「送信」・SPEC_02「`push`」)
# ---------------------------------------------------------------------------

PUSH_SUBCOMMANDS = [
    ["gpus"],
    ["status"],
    ["push"],
    ["push", "--dry-run"],
    ["run", "--name", "t", "--", "x"],
    ["pull", RUN_ID],
]


class TestPushSectionFromCli:
    @pytest.mark.parametrize("subcommand", PUSH_SUBCOMMANDS)
    @pytest.mark.parametrize("case", ["missing", "null"])
    def test_config_without_push_stops_before_ssh(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
        subcommand: list[str],
        case: str,
    ) -> None:
        """SPEC_02「`push`」: push の節が無い・null なら,どのサブコマンドも ssh を呼ばない."""

        def mutate(data: dict) -> None:
            if case == "missing":
                del data["push"]
            else:
                data["push"] = None

        _write_config_data(project, mutate)
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        with caplog.at_level(logging.ERROR):
            assert cli.main(subcommand) == 1
        assert fake.calls == []
        assert "push: {}" in caplog.text
        assert not (project / "runs").exists()


def _fake_labremote_at(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:
    """実行中の labremote パッケージが repo/src/labremote/ にあるように見せる."""
    monkeypatch.setattr(cli.labremote, "__file__", str(repo / "src" / "labremote" / "__init__.py"))


class TestLabRemoteDirFromCli:
    LABREMOTE_FILES = ["pyproject.toml", "src/labremote/__init__.py", "README.md"]

    @pytest.mark.parametrize("where", ["external/LabRemote", "tools/deps/lr"])
    def test_labremote_under_root_is_not_sent(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        where: str,
    ) -> None:
        """SPEC_01「送信」: 実行中の labremote のリポジトリがルートの下なら,その下を送らない."""
        for rel in self.LABREMOTE_FILES:
            path = project / where / rel
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(b"x")
        _fake_labremote_at(monkeypatch, project / where)
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        names = _push_dry_run_names([], capsys)
        assert not [name for name in names if name.startswith(f"{where}/")]
        assert "pyproject.toml" in names
        assert "src/demo_project/__init__.py" in names
        assert fake.calls == []

    def test_same_name_elsewhere_is_sent(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01「送信」: 名前ではなく場所で除く(LabRemote でない external/LabRemote は送る)."""
        (project / "external" / "LabRemote").mkdir(parents=True)
        (project / "external" / "LabRemote" / "a.py").write_bytes(b"x")
        (project / "vendor" / "lr").mkdir(parents=True)
        (project / "vendor" / "lr" / "b.py").write_bytes(b"x")
        _fake_labremote_at(monkeypatch, project / "vendor" / "lr")
        monkeypatch.setattr(cli, "_run_ssh", FakeSsh({}))
        names = _push_dry_run_names([], capsys)
        assert "external/LabRemote/a.py" in names
        assert "vendor/lr/b.py" not in names

    def test_real_labremote_location_is_this_repository(self) -> None:
        """SPEC_01「送信」: LabRemote 自身は,実行中の labremote パッケージのリポジトリ."""
        repo = Path(__file__).resolve().parents[1]
        assert cli._labremote_repo_dir() == repo
        assert (cli._labremote_repo_dir() / "src" / "labremote" / "cli.py").is_file()

    def test_real_labremote_outside_project_excludes_nothing(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01「送信」: 実際の LabRemote はルート(tmp_path)の外なので,何も除かれない."""
        (project / "external" / "LabRemote").mkdir(parents=True)
        (project / "external" / "LabRemote" / "a.py").write_bytes(b"x")
        monkeypatch.setattr(cli, "_run_ssh", FakeSsh({}))
        names = _push_dry_run_names([], capsys)
        assert sorted(names) == [
            "external/LabRemote/a.py",
            "pyproject.toml",
            "src/demo_project/__init__.py",
        ]


class TestPushConfigFromCli:
    def test_config_option_file_is_not_sent(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_01「送信」: `--config` で読んだ別の名前の設定ファイルも,ルートの直下の
        labremote.yaml も送らない."""
        (project / "custom.yaml").write_text(CONFIG_YAML, encoding="utf-8")
        monkeypatch.setattr(cli, "_run_ssh", FakeSsh({}))
        names = _push_dry_run_names(["--config", str(project / "custom.yaml")], capsys)
        assert "custom.yaml" not in names
        assert "labremote.yaml" not in names
        assert "pyproject.toml" in names

    def test_partial_and_exclusions_are_applied(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「`push`」: 設定の exclude_dirs・partial が push の一覧に効く."""
        _write_config_data(
            project,
            lambda data: data.update(
                push={
                    "exclude_dirs": ["wandb"],
                    "partial": [{"path": "external/Sub", "include": ["src", "README.md"]}],
                }
            ),
        )
        for rel in [
            "external/Sub/src/a.py",
            "external/Sub/README.md",
            "external/Sub/docs/x.md",
            "src/demo_project/wandb/run.log",
        ]:
            path = project / rel
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(b"x")
        monkeypatch.setattr(cli, "_run_ssh", FakeSsh({}))
        names = _push_dry_run_names([], capsys)
        assert sorted(names) == [
            "external/Sub/README.md",
            "external/Sub/src/a.py",
            "pyproject.toml",
            "src/demo_project/__init__.py",
        ]

    @pytest.mark.parametrize(
        "push",
        [
            {"no_fixed_exclude": True},
            {"exclude_root": ["da*ta"]},
            {"partial": [{"path": ".git/x", "include": ["a"]}]},
            {"partial": [{"path": "../x", "include": ["a"]}]},
        ],
    )
    def test_bad_push_stops_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, push: dict
    ) -> None:
        """SPEC_02「`push`」: 書けない push は設定を読む時点でエラー(ssh を呼ばない)."""
        _write_config_data(project, lambda data: data.update(push=push))
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["push"]) == 1
        assert fake.calls == []


# ---------------------------------------------------------------------------
# 設定の results を変えたとき(SPEC_02「`results`」,SPEC_03「pull」「run」)
# ---------------------------------------------------------------------------

# 結果の置き場と回収の一覧を書かない設定(results を省略)
CONFIG_YAML_WITHOUT_RESULTS = CONFIG_YAML.replace(SAMPLE_RESULTS_YAML, "")

# OTHER_RESULTS_YAML(dir: output/runs)の一覧で回収するもの・回収しないもの
OTHER_LISTING_ALLOWED = ["summary.txt", "scores.tsv", "out/plots/a.svg", "curves/train.csv"]
OTHER_LISTING_WEIGHTS = ["weights/final.ckpt"]
OTHER_LISTING_NOT_ALLOWED = [
    # SAMPLE_RESULTS の一覧にあった名前
    "config.yaml",
    "metrics.json",
    "figures/loss.png",
    "checkpoints/best.pth",
    # discard の名前・一覧に無い名前・下の階層・大文字小文字の違い
    "trace.bin",
    "debug/secret_case07.png",
    "secret_case08.csv",
    "out/plots/sub/secret_case09.svg",
    "Summary.txt",
    "weights/secret_case10.ckpt",
]
OTHER_SECRETS = ["trace.bin", "secret_case07", "secret_case08", "secret_case09", "secret_case10"]


def _use_config(project: Path, results_yaml: str) -> None:
    (project / "labremote.yaml").write_text(
        CONFIG_YAML_WITHOUT_RESULTS + results_yaml, encoding="utf-8"
    )


def _other_listing() -> bytes:
    names = OTHER_LISTING_ALLOWED + OTHER_LISTING_WEIGHTS + OTHER_LISTING_NOT_ALLOWED
    return b"".join(f"f {RUN_ID}/{name}\0".encode() for name in names)


class RecordingReceive(FakeReceive):
    """`_receive_tar` の代わり(FakeReceive に加えて,tar を作らせるコマンドを記録する)."""

    def __init__(self) -> None:
        super().__init__()
        self.argv: list[str] = []

    def __call__(self, argv: list[str], payload: bytes, destination) -> cli._SshResult:
        self.argv = list(argv)
        return super().__call__(argv, payload, destination)


def _files_under(base: Path) -> list[str]:
    if not base.exists():
        return []
    return sorted(p.relative_to(base).as_posix() for p in base.rglob("*") if p.is_file())


def _setup_other_pull(monkeypatch: pytest.MonkeyPatch) -> tuple[FakeSsh, RecordingReceive]:
    receive = RecordingReceive()
    fake = FakeSsh(
        {
            NEWTON_ADDR: _ok(_other_listing()),
            ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND, stderr=b""),
        }
    )
    monkeypatch.setattr(cli, "_run_ssh", fake)
    monkeypatch.setattr(cli, "_receive_tar", receive)
    return fake, receive


def _probe_with_sessions(sessions: list[str]) -> bytes:
    lines = [PROBE_SESSIONS_MARKER, *sessions, PROBE_GPUS_MARKER, f"{PROBE_GPU_RC_PREFIX}127"]
    return ("\n".join([*lines, PROBE_END_MARKER]) + "\n").encode()


class TestResultsFromCli:
    def test_other_list_pulls_only_its_names_into_results_dir(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「pull」: 設定の一覧の名前だけを,<ルート>/<results.dir>/<RUN_ID>/ に保存する."""
        caplog.set_level(logging.DEBUG)
        _use_config(project, OTHER_RESULTS_YAML)
        _, receive = _setup_other_pull(monkeypatch)
        assert cli.main(["pull", RUN_ID]) == 0
        assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in OTHER_LISTING_ALLOWED)
        assert _files_under(project / "output" / "runs" / RUN_ID) == sorted(OTHER_LISTING_ALLOWED)
        # 既定の置き場(runs)には何も作らない
        assert not (project / "runs").exists()
        # 回収しなかったファイル(一覧に無い 10 件と重み 1 件)は件数だけ.名前は出さない
        captured = capsys.readouterr()
        output = captured.out + captured.err + caplog.text
        for secret in OTHER_SECRETS:
            assert secret not in output
        assert "11 件" in output
        assert "1 件は --with-checkpoints で回収できる" in output

    def test_other_list_with_checkpoints_pulls_listed_weights_only(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_02「`results`」.

        --with-checkpoints で checkpoints.files の名前だけを足して回収する.
        """
        _use_config(project, OTHER_RESULTS_YAML)
        _, receive = _setup_other_pull(monkeypatch)
        assert cli.main(["pull", RUN_ID, "--with-checkpoints"]) == 0
        expected = OTHER_LISTING_ALLOWED + OTHER_LISTING_WEIGHTS
        assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in expected)
        assert _files_under(project / "output" / "runs" / RUN_ID) == sorted(expected)

    def test_pull_commands_use_results_dir(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「pull」.

        サーバの <remote_dir>/<results.dir>/<RUN_ID>/ を一覧し,そこで tar を作る.
        """
        _use_config(project, OTHER_RESULTS_YAML)
        fake, receive = _setup_other_pull(monkeypatch)
        assert cli.main(["pull", RUN_ID]) == 0
        list_commands = [argv[-1] for argv in fake.calls]
        assert list_commands
        for command in [*list_commands, receive.argv[-1]]:
            assert shlex.split(command)[:2] == ["cd", "$HOME/work/DemoProject/output/runs"]

    @pytest.mark.parametrize(
        "extra",
        [
            f"{RUN_ID}/config.yaml",
            f"{RUN_ID}/trace.bin",
            f"{RUN_ID}/weights/final.ckpt",
            f"{RUN_ID}/out/plots/sub/a.svg",
            f"{RUN_ID}/../evil.txt",
        ],
    )
    def test_other_list_bad_archive_extracts_nothing(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, extra: str
    ) -> None:
        """SPEC_01「回収」: 別の一覧でも,受け取った tar に一覧に無い名前があれば何も展開しない."""
        _use_config(project, OTHER_RESULTS_YAML)
        fake = FakeSsh(
            {NEWTON_ADDR: _ok(_other_listing()), ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND)}
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.setattr(cli, "_receive_tar", FakeReceive(extra=[extra]))
        assert cli.main(["pull", RUN_ID]) != 0
        assert _files_under(project / "output") == []
        assert not (project / "runs").exists()
        assert not (project / "evil.txt").exists()

    @pytest.mark.parametrize("flag", [[], ["--with-checkpoints"]])
    def test_pull_without_results_stops_before_ssh(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        flag: list[str],
    ) -> None:
        """SPEC_02「`results`」.

        一覧が空の pull は接続せず,設定に書く場所を示して 0 以外で終わる.
        """
        caplog.set_level(logging.DEBUG)
        _use_config(project, "")
        fake = FakeSsh({})
        receive = FakeReceive()
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.setattr(cli, "_receive_tar", receive)
        assert cli.main(["pull", RUN_ID, *flag]) != 0
        assert fake.calls == []
        assert receive.requested == []
        assert not (project / "runs").exists()
        captured = capsys.readouterr()
        assert "results.pull" in captured.out + captured.err + caplog.text

    def test_pull_with_only_weights_needs_flag(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_02「`results`」.

        重みだけが書かれた設定は,--with-checkpoints のときだけ回収に進む.
        """
        _use_config(project, "results:\n  checkpoints:\n    files: [best.pth]\n")
        fake = FakeSsh({NEWTON_ADDR: _ok(_listing()), ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND)})
        receive = FakeReceive()
        monkeypatch.setattr(cli, "_run_ssh", fake)
        monkeypatch.setattr(cli, "_receive_tar", receive)
        assert cli.main(["pull", RUN_ID]) != 0
        assert fake.calls == []

        assert cli.main(["pull", RUN_ID, "--with-checkpoints"]) == 0
        assert receive.requested == [f"{RUN_ID}/checkpoints/best.pth"]
        assert _local_files(project) == ["checkpoints/best.pth"]

    def test_logs_use_results_dir(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        """SPEC_03「run」: ログの表示は <results.dir>/_remote_logs/<ジョブ名>.log を読む."""
        _use_config(project, OTHER_RESULTS_YAML)

        def newton(argv: list[str]) -> cli._SshResult:
            return cli._SshResult(0, b"epoch 1\n" if "tail" in argv[-1] else b"", b"")

        fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["logs", "train1", "-n", "5"]) == 0
        assert fake.calls
        for argv in fake.calls:
            assert "output/runs/_remote_logs/train1.log" in argv[-1]
            assert " runs/_remote_logs" not in argv[-1]

    def test_kill_uses_results_dir(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        """SPEC_03「run」: probe と kill は <results.dir>/_remote_logs/ のログを見る・書く."""
        _use_config(project, OTHER_RESULTS_YAML)

        def newton(argv: list[str]) -> cli._SshResult:
            if "kill-session" in argv[-1]:
                return cli._SshResult(0, b"", b"")
            return cli._SshResult(0, _probe_with_sessions(["job train1"]), b"")

        fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _ok(_probe_with_sessions([]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["kill", "train1"]) == 0
        kills = [argv[-1] for argv in fake.calls if "kill-session" in argv[-1]]
        assert len(kills) == 1
        assert "output/runs/_remote_logs/train1.log" in kills[0]
        for argv in fake.calls:
            assert "output/runs/_remote_logs" in argv[-1]

    def test_run_dry_run_uses_results_dir(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_03「run」: ログの置き場は <remote_dir>/<results.dir>/_remote_logs/ になる."""
        _use_config(project, OTHER_RESULTS_YAML)
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        out = capsys.readouterr().out
        assert "output/runs/_remote_logs" in out
        assert "exp1.log" in out
        for argv in fake.calls:
            assert "output/runs/_remote_logs" in argv[-1]

    def test_push_excludes_changed_results_dir(
        self, project: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「結果の置き場と送信」: dir を変えると,送らない場所もその場所に変わる."""
        _use_config(project, OTHER_RESULTS_YAML)
        for rel in ["output/runs/r1/summary.txt", "output/note.txt", "runs/x.txt"]:
            (project / rel).parent.mkdir(parents=True, exist_ok=True)
            (project / rel).write_bytes(b"x")
        names = _push_dry_run_names([], capsys)
        assert "output/note.txt" in names
        assert "runs/x.txt" in names
        assert not any(name.startswith("output/runs") for name in names)

    def test_push_excludes_default_results_dir(
        self, project: Path, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「`results`」: results を省略したとき,ルートの直下の runs/ は送らない."""
        _use_config(project, "")
        (project / "runs" / "r1").mkdir(parents=True)
        (project / "runs" / "r1" / "metrics.json").write_bytes(b"x")
        names = _push_dry_run_names([], capsys)
        assert names
        assert not any(name.startswith("runs") for name in names)


# ---------------------------------------------------------------------------
# run.exclude_groups(SPEC_02「`exclude_groups` の書き方」,SPEC_03「run」)
# ---------------------------------------------------------------------------


def _remote_command_of_dry_run(out: str) -> str:
    """`run --dry-run` の出力から,表示された「実行するリモートコマンド」を取り出す."""
    lines = out.splitlines()
    return lines[lines.index("実行するリモートコマンド:") + 1]


class TestExcludeGroupsFromCli:
    def _with_groups(self, project: Path, groups: object) -> None:
        def mutate(data: dict) -> None:
            data["run"] = {"exclude_groups": groups}

        _write_config_data(project, mutate)

    def test_dry_run_shows_frozen_and_no_group_options(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: `--dry-run` の表示も `--frozen` と書いた順."""
        self._with_groups(project, ["remote", "dev.tools"])
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        assert cli.main(_run_dry([])) == 0
        assert tuple(captured[0]["exclude_groups"]) == ("remote", "dev.tools")
        remote_command = _remote_command_of_dry_run(capsys.readouterr().out)
        assert _uv_run_args_of_launch(remote_command) == [
            "--frozen",
            "--no-group",
            "remote",
            "--no-group",
            "dev.tools",
            "python",
        ]

    def test_dry_run_without_groups_has_no_option(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 書いていなければ何も付かない(`--frozen` も)."""
        _free_everywhere(monkeypatch)
        assert cli.main(_run_dry([])) == 0
        remote_command = _remote_command_of_dry_run(capsys.readouterr().out)
        assert _uv_run_args_of_launch(remote_command) == ["python"]

    def test_cpu_dry_run_also_has_options(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: `--cpu` のジョブにも同じように付く."""
        self._with_groups(project, ["remote"])
        fake = FakeSsh(
            {
                NEWTON_ADDR: _ok(_probe_stdout_instant()),
                ARCHIMEDES_ADDR: _ok(_probe_stdout_instant()),
            }
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0
        remote_command = _remote_command_of_dry_run(capsys.readouterr().out)
        assert _uv_run_args_of_launch(remote_command) == ["--frozen", "--no-group", "remote", "x"]

    def test_launch_passes_options(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        """SPEC_03「run」: 起動のコマンドでも,`--frozen --no-group` がコマンド本体より前に付く."""
        self._with_groups(project, ["remote"])
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "train1", "--no-push", "--", "demo-train"]) == 0
        assert _uv_run_args_of_launch(fake.calls[-1][-1]) == [
            "--frozen",
            "--no-group",
            "remote",
            "demo-train",
        ]

    def test_launch_without_groups_has_no_frozen(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「run」: 外すグループが無ければ,起動のコマンドは `<uv> run <CMD>` のまま."""
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "train1", "--no-push", "--", "demo-train"]) == 0
        assert _uv_run_args_of_launch(fake.calls[-1][-1]) == ["demo-train"]

    @pytest.mark.parametrize(
        "groups", [["-x"], ["--frozen"], ["a b"], ["remote", "Remote"], "remote"]
    )
    @pytest.mark.parametrize("subcommand", [["gpus"], ["run", "--name", "t", "--", "x"]])
    def test_invalid_config_stops_before_ssh(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, groups: object, subcommand: list[str]
    ) -> None:
        """SPEC_02「`exclude_groups` の書き方」: 不正な設定は読む時点でエラー(ssh を呼ばない)."""
        self._with_groups(project, groups)
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(subcommand) == 1
        assert fake.calls == []


# ---------------------------------------------------------------------------
# 表示の言葉(SPEC_03「表示の言葉」「表示する項目」)
# ---------------------------------------------------------------------------

# 利用する側のプロジェクトの言葉(コマンド名・データの呼び方・実験 ID の作り方).
# 大文字小文字を問わない
PROJECT_WORDS = ["tsm", "tongueseg", "tias", "resunet", "バンドル", "nogit"]
HELP_ARGS = [["--help"], *([subcommand, "--help"] for subcommand in SUBCOMMANDS)]


def _wide_help_text(
    args: list[str], capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
) -> str:
    """help を,折り返しで名前が切れないよう広い幅で取り出す."""
    monkeypatch.setenv("COLUMNS", "400")
    return _help_text(args, capsys)


def _error_messages(caplog: pytest.LogCaptureFixture) -> str:
    return "\n".join(r.getMessage() for r in caplog.records if r.levelno >= logging.ERROR)


class TestHelpWording:
    @pytest.mark.parametrize("args", HELP_ARGS, ids=lambda args: " ".join(args))
    def test_help_has_no_project_words(
        self, args: list[str], capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_03「表示の言葉」: help にプロジェクトのコマンド名・データの呼び方を書かない."""
        out = _help_text(args, capsys).lower()
        for word in PROJECT_WORDS:
            assert word not in out

    @pytest.mark.parametrize("args", HELP_ARGS, ids=lambda args: " ".join(args))
    def test_help_does_not_call_tool_kono_tool(
        self, args: list[str], capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_03「表示の言葉」: このツールを指すときは labremote と書く."""
        assert "このツール" not in _help_text(args, capsys)

    def test_run_env_help_lists_all_reserved_names(
        self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「表示の言葉」: --env の help に予約の環境変数の名前を全部出す."""
        out = "".join(_wide_help_text(["run", "--help"], capsys, monkeypatch).split())
        for name in RESERVED_ENV_VARS:
            assert name in out

    def test_run_env_help_follows_reserved_constant(
        self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「表示の言葉」: 予約の名前はコードの定数から作る(定数に足せば help にも出る)."""
        monkeypatch.setattr(cli, "RESERVED_ENV_VARS", RESERVED_ENV_VARS | {"DEMO_RESERVED_VAR"})
        out = "".join(_wide_help_text(["run", "--help"], capsys, monkeypatch).split())
        assert "DEMO_RESERVED_VAR" in out
        for name in RESERVED_ENV_VARS:
            assert name in out


class TestProjectLine:
    @pytest.mark.parametrize("subcommand", ["gpus", "status"])
    @pytest.mark.parametrize("name", ["DemoProject", "OtherDemo"])
    def test_output_starts_with_project_name_line(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        subcommand: str,
        name: str,
    ) -> None:
        """SPEC_03「表示の言葉」: gpus・status の先頭に project.name を 1 行で出す."""
        _write_config_data(project, lambda data: data["project"].update(name=name))
        _free_everywhere(monkeypatch)
        assert cli.main([subcommand]) == 0
        lines = capsys.readouterr().out.splitlines()
        assert lines[0] == format_project_line(name)
        assert name in lines[0]
        # 名前の行は 1 回だけ(サーバごとに繰り返さない)
        assert sum(1 for line in lines if line == format_project_line(name)) == 1

    @pytest.mark.parametrize("subcommand", ["gpus", "status"])
    def test_project_line_is_shown_even_if_one_server_is_unreachable(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        subcommand: str,
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main([subcommand]) == 0
        assert capsys.readouterr().out.splitlines()[0] == format_project_line("DemoProject")


class TestStatusOtherSessions:
    def _run_status(
        self,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        sessions: list[str],
    ) -> str:
        caplog.set_level(logging.DEBUG)
        fake = FakeSsh(
            {
                NEWTON_ADDR: _ok(_probe_with_sessions(sessions)),
                ARCHIMEDES_ADDR: _ok(_probe_with_sessions([])),
            }
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["status"]) == 0
        captured = capsys.readouterr()
        return captured.out + captured.err + caplog.text

    def test_other_sessions_are_counted_without_names(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「表示する項目」: ジョブでないセッションは件数だけ.名前は出さない."""
        sessions = ["job train1", "other hidden-alpha", "other hidden-beta"]
        output = self._run_status(monkeypatch, capsys, caplog, sessions)
        count_lines = [
            line for line in output.splitlines() if "このプロジェクトのジョブではない" in line
        ]
        assert len(count_lines) == 1
        assert "2" in count_lines[0]
        assert "hidden-alpha" not in output
        assert "hidden-beta" not in output
        assert "train1" in output

    def test_no_count_line_without_other_sessions(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        output = self._run_status(monkeypatch, capsys, caplog, ["job train1"])
        assert "このプロジェクトのジョブではない" not in output
        assert "train1" in output


class TestDataNotReadyWordingFromCli:
    def test_gpus_alternative_line_mentions_data_ready(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_03「表示の言葉」: データの有無は data_ready と結び付けて書く."""
        _write_remote_config(project, newton_data_ready=False)
        busy = _probe_stdout([(0, 20000, 95)])
        fake = FakeSsh({NEWTON_ADDR: _ok(_probe_stdout([(0, 5, 0)])), ARCHIMEDES_ADDR: _ok(busy)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["gpus"]) == 0
        out = capsys.readouterr().out
        hint = [line for line in out.splitlines() if "--no-data" in line]
        assert hint
        assert "data_ready" in hint[0]
        assert "バンドル" not in out

    def test_run_on_not_ready_server_error_mentions_data_ready(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        caplog.set_level(logging.DEBUG)
        _write_remote_config(project, newton_data_ready=False)
        fake = _free_everywhere(monkeypatch)
        args = ["run", "--name", "t", "--server", "Newton", "--gpu", "0", "--", "x"]
        assert cli.main(args) != 0
        errors = _error_messages(caplog)
        assert "data_ready" in errors
        assert "バンドル" not in caplog.text
        assert all("new-session" not in argv[-1] for argv in fake.calls)


class TestKillWording:
    @staticmethod
    def _assert_tool_name_is_lowercase(message: str) -> None:
        assert "labremote" in message
        assert "LabRemote" not in message
        assert "このツール" not in message

    def test_local_refusal_names_labremote_in_lowercase(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「表示の言葉」: ジョブでないセッションの案内は labremote(小文字)で書く."""
        caplog.set_level(logging.DEBUG)
        text = _probe_with_sessions(["other mywork"])
        fake = FakeSsh({NEWTON_ADDR: _ok(text), ARCHIMEDES_ADDR: _ok(text)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["kill", "mywork"]) == 1
        errors = _error_messages(caplog)
        assert "mywork" in errors
        self._assert_tool_name_is_lowercase(errors)
        assert all("kill-session" not in argv[-1] for argv in fake.calls)

    def test_server_refusal_names_labremote_in_lowercase(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        caplog.set_level(logging.DEBUG)

        def newton(argv: list[str]) -> cli._SshResult:
            if "kill-session" in argv[-1]:
                return cli._SshResult(EXIT_NOT_JOB, b"", b"")
            return cli._SshResult(0, _probe_with_sessions(["job train1"]), b"")

        fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _ok(_probe_with_sessions([]))})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["kill", "train1"]) != 0
        errors = _error_messages(caplog)
        assert "train1" in errors
        self._assert_tool_name_is_lowercase(errors)


class TestGitWarningWording:
    @pytest.mark.parametrize("failure", GIT_FAILURES)
    def test_warning_names_variable_and_not_project_rule(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        fake_git: FakeGit,
        caplog: pytest.LogCaptureFixture,
        failure: str,
    ) -> None:
        """SPEC_03「表示の言葉」: 実験 ID の作り方に触れず,labremote がすることだけを書く."""
        caplog.set_level(logging.DEBUG)
        _break_git(fake_git, failure)
        _free_everywhere(monkeypatch)
        assert cli.main(_run_dry([])) == 0
        warnings = [
            r.getMessage()
            for r in caplog.records
            if r.levelno == logging.WARNING and "git" in r.getMessage()
        ]
        assert len(warnings) == 1
        assert "LABREMOTE_GIT_COMMIT" in warnings[0]
        assert "nogit" not in caplog.text.lower()
        assert "実験 ID" not in warnings[0]


# ---------------------------------------------------------------------------
# ls(SPEC_03「ls」)
# ---------------------------------------------------------------------------

LS_RUN_B = "20261120-090000_demo_def5678"


def _ls_ok_stdout() -> bytes:
    return ls_output(
        results=[dir_record(RUN_ID, 12, 2048), dir_record(LS_RUN_B, 3, 8), "other"],
        logs=[log_record("train1.log", 300), log_record("old.log", 20)],
        jobs=[job_record("train1")],
    )


class _TimeoutSpy(FakeSsh):
    """FakeSsh に,応答待ちの上限(timeout)の記録を足したもの."""

    def __init__(self, responses: dict[str, Callable[[list[str]], cli._SshResult]]) -> None:
        super().__init__(responses)
        self.timeouts: list[float | None] = []

    def __call__(
        self, argv: list[str], *, input_bytes: bytes | None = None, timeout: float | None = None
    ) -> cli._SshResult:
        self.timeouts.append(timeout)
        return super().__call__(argv, input_bytes=input_bytes, timeout=timeout)


def _all_output(capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture) -> str:
    captured = capsys.readouterr()
    return captured.out + captured.err + caplog.text


class TestLs:
    def test_output_starts_with_project_line(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_03「ls」: 表示の先頭に project.name を 1 行で出す."""
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0
        lines = capsys.readouterr().out.splitlines()
        assert lines[0] == format_project_line("DemoProject")
        assert sum(1 for line in lines if line == format_project_line("DemoProject")) == 1

    def test_shows_leftovers_of_each_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        fake = FakeSsh(
            {NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(ls_missing_remote_dir())}
        )
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0
        out = capsys.readouterr().out
        assert RUN_ID in out and LS_RUN_B in out
        assert "train1" in out and "実行中" in out and "停止中" in out
        assert "Newton" in out and "Archimedes" in out

    def test_queries_servers_with_data_ready_false(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「ls」: data_ready は見ない(データの有無に関わらず問い合わせる)."""
        _write_config_data(
            project, lambda data: [s.update(data_ready=False) for s in data["servers"]]
        )
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0
        assert sorted(argv[-2] for argv in fake.calls) == ["Archimedes", "Newton"]

    @pytest.mark.parametrize("given", ["Archimedes", "archimedes", "ARCHIMEDES"])
    def test_server_option_queries_only_that_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, given: str
    ) -> None:
        """SPEC_03「ls」: --server を付けると,そのサーバにだけ問い合わせる."""
        fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", given]) == 0
        assert [argv[-2] for argv in fake.calls] == ["Archimedes"]
        # 使う人の入力(--server の値)はサーバのコマンドに埋め込まない
        if given != "Archimedes":
            assert given not in fake.calls[0][-1]

    @pytest.mark.parametrize("name", ["Nowhere", "x;rm -rf ~", "$(id)", ""])
    def test_unknown_server_is_error_without_connecting(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, name: str
    ) -> None:
        fake = FakeSsh({})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", name]) != 0
        assert fake.calls == []

    def test_remote_command_is_built_from_config_only(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「ls」: 埋め込むのは remote_dir と結果の置き場だけ.GPU の観測をしない."""
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", "Newton"]) == 0
        assert len(fake.calls) == 1
        command = fake.calls[0][-1]
        assert command == build_ls_command("~/work/DemoProject", results_dir="runs")
        assert "nvidia-smi" not in command

    def test_one_ssh_call_per_server(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0
        assert sorted(argv[-2] for argv in fake.calls) == ["Archimedes", "Newton"]
        for argv in fake.calls:
            assert "nvidia-smi" not in argv[-1]

    def test_waits_90_seconds_longer(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        """SPEC_03「ls」: 他のサブコマンドより 90 秒長く応答を待つ."""
        fake = _TimeoutSpy({NEWTON_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", "Newton"]) == 0
        missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"")
        other = _TimeoutSpy({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing})
        monkeypatch.setattr(cli, "_run_ssh", other)
        cli.main(["logs", "train1"])
        assert fake.timeouts[0] is not None and other.timeouts[0] is not None
        assert fake.timeouts[0] == other.timeouts[0] + 90

    def test_all_ok_is_zero(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0

    @pytest.mark.parametrize("rc", [255, cli._TIMEOUT_RC])
    def test_one_unreachable_continues_and_warns(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        rc: int,
    ) -> None:
        """SPEC_03「ls」: 接続できないサーバは「接続不可」とし,他で続け,最後に警告する.

        仕様が 0 以外を求めるのは「どれにも接続できなかった」「解釈できなかった」「数え切れ
        なかった」ときだけなので,1 台だけ接続不可で他が正常なら 0 で終わる.
        """
        caplog.set_level(logging.DEBUG)
        fake = FakeSsh({NEWTON_ADDR: _fail(rc=rc), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0
        captured = capsys.readouterr()
        newton = [line for line in captured.out.splitlines() if "[Newton]" in line]
        assert len(newton) == 1 and "接続不可" in newton[0]
        assert "何も残っていない" not in newton[0]
        assert RUN_ID in captured.out
        warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
        assert any("Newton" in w for w in warnings)

    @pytest.mark.parametrize("rc", [255, cli._TIMEOUT_RC])
    def test_all_unreachable_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, rc: int
    ) -> None:
        """SPEC_03「ls」: どれにも接続できなかったときは 0 以外(残っていないと見誤らない)."""
        fake = FakeSsh({NEWTON_ADDR: _fail(rc=rc), ARCHIMEDES_ADDR: _fail(rc=rc)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) != 0

    def test_single_server_unreachable_is_error(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = FakeSsh({NEWTON_ADDR: _fail()})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", "Newton"]) != 0

    @pytest.mark.parametrize(
        "stdout",
        [
            b"",
            b"garbage\n",
            ls_output()[:-30],
            encode_records(["@@labremote-ls-begin", "@@labremote-ls-remote-dir unreadable"]),
            encode_records(
                [
                    "@@labremote-ls-begin",
                    "@@labremote-ls-remote-dir unreadable",
                    "@@labremote-ls-end",
                ]
            ),
        ],
        ids=["empty", "garbage", "truncated", "unreadable_truncated", "unreadable"],
    )
    def test_unparsable_server_is_error_and_not_shown_as_empty(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        stdout: bytes,
    ) -> None:
        """SPEC_03「ls」: 解釈できないサーバは「確認できない」とし,0 以外で終わる."""
        caplog.set_level(logging.DEBUG)
        fake = FakeSsh({NEWTON_ADDR: _ok(stdout), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) != 0
        out = capsys.readouterr().out
        newton = [line for line in out.splitlines() if "[Newton]" in line]
        assert len(newton) == 1
        assert "確認できない" in newton[0]
        assert "何も残っていない" not in newton[0] and "0 件" not in newton[0]
        newton_block = out.split("[Newton]", 1)[1].split("[Archimedes]", 1)[0]
        assert "0 件" not in newton_block
        assert "Newton" in caplog.text

    @pytest.mark.parametrize("rc", [1, 2, 127, 126])
    def test_remote_command_failure_is_unchecked_not_unreachable(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        rc: int,
    ) -> None:
        """ssh 自身の失敗(255)以外の失敗は「確認できない」で 0 以外.stderr は表示しない."""
        caplog.set_level(logging.DEBUG)
        secret = b"find: './secretfile_k9.txt': Permission denied\n"
        fake = FakeSsh({NEWTON_ADDR: _fail(rc=rc, stderr=secret), ARCHIMEDES_ADDR: _fail()})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) != 0
        output = _all_output(capsys, caplog)
        newton = [line for line in output.splitlines() if "[Newton]" in line]
        assert len(newton) == 1 and "確認できない" in newton[0]
        assert "secretfile_k9" not in output

    def test_incomplete_count_is_error_with_note(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「ls」: 数え切れなかったときは,少ない可能性を添え,0 以外で終わる."""
        caplog.set_level(logging.DEBUG)
        incomplete = ls_output(results=[dir_record(RUN_ID, 2, 8, find_rc=1)])
        fake = FakeSsh({NEWTON_ADDR: _ok(incomplete), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) != 0
        out = capsys.readouterr().out
        newton_block = out.split("[Newton]", 1)[1].split("[Archimedes]", 1)[0]
        (run_line,) = [line for line in newton_block.splitlines() if RUN_ID in line]
        assert "少ない" in run_line
        archimedes_block = out.split("[Archimedes]", 1)[1]
        assert "少ない" not in archimedes_block
        assert "Newton" in caplog.text

    def test_incomplete_size_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        incomplete = ls_output(venv_rc=1)
        fake = FakeSsh({NEWTON_ADDR: _ok(incomplete), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) != 0

    def test_local_is_yes_only_for_folder(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_03「ls」: 手元の <ルート>/<結果の置き場>/<実験 ID> がフォルダのときだけ「あり」."""
        (project / "runs" / RUN_ID).mkdir(parents=True)
        (project / "runs" / LS_RUN_B).write_bytes(b"not a folder")
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", "Newton"]) == 0
        lines = capsys.readouterr().out.splitlines()
        (line_a,) = [line for line in lines if RUN_ID in line]
        (line_b,) = [line for line in lines if LS_RUN_B in line]
        assert "手元: あり" in line_a
        assert "手元: なし" in line_b

    def test_local_uses_configured_results_dir(
        self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
    ) -> None:
        """SPEC_02「`results`」: 結果の置き場が別の名前なら,手元もサーバもその名前で見る."""
        _write_config_data(project, lambda data: data["results"].update(dir="output/runs"))
        (project / "runs" / RUN_ID).mkdir(parents=True)  # 既定の名前の側にだけある
        (project / "output" / "runs" / LS_RUN_B).mkdir(parents=True)
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls", "--server", "Newton"]) == 0
        assert fake.calls[0][-1] == build_ls_command(
            "~/work/DemoProject", results_dir="output/runs"
        )
        lines = capsys.readouterr().out.splitlines()
        (line_a,) = [line for line in lines if RUN_ID in line]
        (line_b,) = [line for line in lines if LS_RUN_B in line]
        assert "手元: なし" in line_a
        assert "手元: あり" in line_b

    def test_does_not_create_local_folders(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        before = sorted(p.relative_to(project).as_posix() for p in project.rglob("*"))
        fake = FakeSsh({NEWTON_ADDR: _ok(_ls_ok_stdout()), ARCHIMEDES_ADDR: _ok(_ls_ok_stdout())})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        assert cli.main(["ls"]) == 0
        after = sorted(p.relative_to(project).as_posix() for p in project.rglob("*"))
        assert after == before

    def test_bad_names_from_server_never_appear(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「ls」: 規則に合わない名前(制御文字等)は,表示・ログ・エラーに出ない."""
        caplog.set_level(logging.DEBUG)
        bad = [
            "evil\x1b]0;pwned\x07",
            "evil\x1b[2J",
            "evilname two",
            "evil$(id)",
            "evil\nfake line",
            "evil\r",
        ]
        stdout = ls_output(
            results=[dir_record(name) for name in bad] + [dir_record(b"evil\xff\xfe")],
            logs=[log_record(name + ".log") for name in bad],
            jobs=[job_record(name) for name in bad],
        )
        broken = ls_output(results=[b"dir 0 0 x 4 evilbroken\x1b[31m"])
        fake = FakeSsh({NEWTON_ADDR: _ok(stdout), ARCHIMEDES_ADDR: _ok(broken)})
        monkeypatch.setattr(cli, "_run_ssh", fake)
        cli.main(["ls"])
        output = _all_output(capsys, caplog)
        assert "evil" not in output
        assert "\x1b" not in output
        assert "\x07" not in output
        # 規則に合わない名前は「その他」の件数に入る
        newton_block = output.split("[Newton]", 1)[1]
        assert f"結果の置き場に {len(bad) + 1} 件" in newton_block
        assert f"ログの置き場に {len(bad)} 件" in newton_block

    def test_ls_help_has_server_option(self, capsys: pytest.CaptureFixture[str]) -> None:
        out = _help_text(["ls", "--help"], capsys)
        assert "--server" in out


# ---------------------------------------------------------------------------
# clean RUN_ID(SPEC_03「clean」の手順 1〜3.削除は 2-3 で入る)
# ---------------------------------------------------------------------------

# サーバの出力に入れる,表示・ログ・エラーに出てはならない名前
CLEAN_SECRET = "secretcleanfile_p8"
_DELETE_WORDS = [
    "rm", "rmdir", "unlink", "shred", "mv", "truncate", "tee", "dd", "touch", "cp", "xargs",
]  # fmt: skip


class _CleanServer:
    """1 台のサーバの応答(clean の一覧のコマンドには clean_stdout,probe には probe_stdout)."""

    def __init__(
        self,
        clean_stdout: bytes,
        *,
        probe_stdout: bytes | None = None,
        rc: int = 0,
        probe_rc: int = 0,
    ) -> None:
        self.clean_stdout = clean_stdout
        self.probe_stdout = _probe_with_sessions([]) if probe_stdout is None else probe_stdout
        self.rc = rc
        self.probe_rc = probe_rc

    def __call__(self, argv: list[str]) -> cli._SshResult:
        if CLEAN_BEGIN_MARKER in argv[-1]:
            return cli._SshResult(self.rc, self.clean_stdout if self.rc == 0 else b"", b"")
        if CLEAN_DELETED_MARKER in argv[-1]:
            # 削除のコマンド: 消せたときの応答
            return cli._SshResult(0, CLEAN_DELETED_MARKER.encode("ascii") + b"\n", b"")
        return cli._SshResult(self.probe_rc, self.probe_stdout, b"")


_MISSING = clean_state_output(CLEAN_STATE_MISSING)


def _clean_fake(
    monkeypatch: pytest.MonkeyPatch,
    newton: bytes | _CleanServer,
    archimedes: bytes | _CleanServer = _MISSING,
) -> FakeSsh:
    servers = {
        NEWTON_ADDR: newton if isinstance(newton, _CleanServer) else _CleanServer(newton),
        ARCHIMEDES_ADDR: (
            archimedes if isinstance(archimedes, _CleanServer) else _CleanServer(archimedes)
        ),
    }
    fake = _TimeoutSpy(servers)  # type: ignore[arg-type]
    monkeypatch.setattr(cli, "_run_ssh", fake)
    return fake


@pytest.fixture
def clean_project(project: Path) -> Path:
    """discard を含む設定(tests/clean_helpers.py の CLEAN_RESULTS_YAML)のプロジェクト."""
    _use_config(project, CLEAN_RESULTS_YAML)
    return project


def _local_run(project: Path) -> Path:
    return project / "runs" / CLEAN_RUN_ID


def _put_local(project: Path, rel: str, data: bytes) -> Path:
    path = _local_run(project) / rel
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(data)
    return path


def _spy_judgement(monkeypatch: pytest.MonkeyPatch) -> list:
    judged: list = []
    original = cli.classify_clean

    def spy(*args, **kwargs):
        result = original(*args, **kwargs)
        judged.append(result)
        return result

    monkeypatch.setattr(cli, "classify_clean", spy)
    return judged


def _categories(judgement) -> dict[str, CleanCategory]:
    return {e.file.rel_path: e.category for e in judgement.entries}


def _assert_no_delete_commands(fake: FakeSsh) -> None:
    """サーバへ送ったのは,一覧のコマンドと probe だけで,どれにも消すコマンドが無い."""
    expected = build_clean_list_command(
        "~/work/DemoProject", results_dir="runs", run_id=CLEAN_RUN_ID
    )
    assert fake.calls
    for argv in fake.calls:
        command = argv[-1]
        if CLEAN_BEGIN_MARKER in command:
            assert command == expected
        else:
            assert PROBE_END_MARKER in command
        for word in _DELETE_WORDS:
            assert not re.search(rf"(^|[\s;(|&'\"]){word}(\s|$)", command), word
        assert "-delete" not in command
        # 書き込むリダイレクトは /dev/null へのものだけ(一覧のコマンドは 2>/dev/null だけ)
        assert ">" not in re.sub(r"[12]?>\s*/dev/null|2>&1", "", command)
        if CLEAN_BEGIN_MARKER in command:
            assert ">" not in command.replace("2>/dev/null", "")


# 手元と一致する 3 件と,捨ててよい 2 件
_MATCHED = {"metrics.json": b"{}", "sub/a b.txt": b"hello", "figures/loss.png": b"png" * 100}


def _matched_output(extra: list | None = None) -> bytes:
    entries = [file_record(rel, data) for rel, data in _MATCHED.items()]
    entries += [file_record("cache.bin", b"c" * 10), file_record("debug/x.png", b"d")]
    return clean_output(entries + (extra or []))


def _put_matched(project: Path) -> None:
    for rel, data in _MATCHED.items():
        _put_local(project, rel, data)


class TestClean:
    def test_all_explained_with_dry_run_is_zero(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        _put_matched(clean_project)
        fake = _clean_fake(monkeypatch, _matched_output())
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0
        (judgement,) = judged
        assert judgement.deletable
        assert judgement.matched.count == 3 and judgement.discardable.count == 2
        out = capsys.readouterr().out
        assert "消せる" in out and "[Newton]" in out
        _assert_no_delete_commands(fake)

    def test_all_explained_without_dry_run_sends_one_delete_command(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「clean」の手順 4: 全部説明がつき --dry-run が無いときだけ,その実験 ID の
        削除のコマンドが 1 回送られる(手元のファイルは消さない)."""
        caplog.set_level(logging.DEBUG)
        _put_matched(clean_project)
        before = sorted(p.relative_to(clean_project).as_posix() for p in clean_project.rglob("*"))
        fake = _clean_fake(monkeypatch, _matched_output())
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0
        expected = build_clean_delete_command(
            "~/work/DemoProject", results_dir="runs", run_id=CLEAN_RUN_ID
        )
        deletes = [argv for argv in fake.calls if CLEAN_DELETED_MARKER in argv[-1]]
        assert [(argv[-2], argv[-1]) for argv in deletes] == [("Newton", expected)]
        assert "消した" in _all_output(capsys, caplog)
        after = sorted(p.relative_to(clean_project).as_posix() for p in clean_project.rglob("*"))
        assert after == before

    @pytest.mark.parametrize("dry_run", [False, True])
    @pytest.mark.parametrize(
        "extra",
        [
            file_record("extra.txt", b"e"),
            other_record("link"),
            file_record("checkpoints/best.pth", b"w"),
            raw_file_record("1", sha(b"x"), f"./{CLEAN_RUN_ID}/../outside.txt"),
        ],
        ids=["not_local", "link", "checkpoint", "unsafe"],
    )
    def test_unexplained_is_error_with_and_without_dry_run(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        dry_run: bool,
        extra: bytes,
    ) -> None:
        """SPEC_03「clean」の手順 3: 説明がつかないものがあれば 0 以外(--dry-run でも)."""
        _put_matched(clean_project)
        fake = _clean_fake(monkeypatch, _matched_output([extra]))
        args = ["clean", CLEAN_RUN_ID] + (["--dry-run"] if dry_run else [])
        assert cli.main(args) != 0
        out = capsys.readouterr().out
        assert "消せない" in out
        assert "結論: 消せる" not in out
        _assert_no_delete_commands(fake)

    def test_discard_checkpoints_flag(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _put_matched(clean_project)
        output = _matched_output([file_record("checkpoints/sub/e1.pth", b"w")])
        _clean_fake(monkeypatch, output)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        _clean_fake(monkeypatch, output)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run", "--discard-checkpoints"]) == 0

    def test_empty_run_dir_is_deletable(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _clean_fake(monkeypatch, clean_output([]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0

    def test_sends_only_list_command_built_from_config(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _put_matched(clean_project)
        fake = _clean_fake(monkeypatch, _matched_output())
        cli.main(["clean", CLEAN_RUN_ID, "--server", "Newton", "--dry-run"])
        lists = [argv for argv in fake.calls if CLEAN_BEGIN_MARKER in argv[-1]]
        assert [argv[-2] for argv in lists] == ["Newton"]
        _assert_no_delete_commands(fake)

    def test_waits_600_seconds_longer(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「clean」: 他のサブコマンドより 600 秒長く応答を待つ."""
        fake = _clean_fake(monkeypatch, clean_output([]))
        cli.main(["clean", CLEAN_RUN_ID, "--server", "Newton", "--dry-run"])
        list_timeouts = [
            t for argv, t in zip(fake.calls, fake.timeouts, strict=True)
            if CLEAN_BEGIN_MARKER in argv[-1]
        ]  # fmt: skip
        missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"")
        other = _TimeoutSpy({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing})
        monkeypatch.setattr(cli, "_run_ssh", other)
        cli.main(["logs", "train1"])
        assert list_timeouts == [other.timeouts[0] + 600]

    # --- 手元の照合(tmp_path の実際のファイル) ---

    @pytest.mark.parametrize(
        ("local", "expected"),
        [
            (b"same content", CleanCategory.MATCHED),
            (b"SAME CONTENT", CleanCategory.UNEXPLAINED),  # 内容が違う(大きさは同じ)
            (b"same content!", CleanCategory.UNEXPLAINED),  # 大きさが違う
            (b"", CleanCategory.UNEXPLAINED),
            (None, CleanCategory.UNEXPLAINED),  # 手元に無い
            ("dir", CleanCategory.UNEXPLAINED),  # 手元の側がフォルダ
        ],
        ids=["same", "content_differs", "size_differs", "empty", "missing", "folder"],
    )
    @pytest.mark.parametrize("rel", ["result.txt", "deep/er/result.txt"])
    def test_local_comparison(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        local: bytes | str | None,
        expected: CleanCategory,
        rel: str,
    ) -> None:
        _local_run(clean_project).mkdir(parents=True)
        if isinstance(local, bytes):
            _put_local(clean_project, rel, local)
        elif local == "dir":
            (_local_run(clean_project) / rel).mkdir(parents=True)
            _put_local(clean_project, f"{rel}/inner", b"same content")
        _clean_fake(monkeypatch, clean_output([file_record(rel, b"same content")]))
        judged = _spy_judgement(monkeypatch)
        rc = cli.main(["clean", CLEAN_RUN_ID, "--dry-run"])
        assert _categories(judged[0]) == {rel: expected}
        assert (rc == 0) == (expected is CleanCategory.MATCHED)

    @pytest.mark.parametrize(
        ("server_rel", "local_rel"),
        [
            ("Config.yaml", "config.yaml"),
            ("config.yaml", "Config.yaml"),
            ("RESULT.TXT", "result.txt"),
            ("Sub/a.txt", "sub/a.txt"),
            ("sub/Deep/a.txt", "sub/deep/a.txt"),
            ("sub/a.TXT", "sub/a.txt"),
        ],
    )
    def test_case_of_local_name_must_match(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        server_rel: str,
        local_rel: str,
    ) -> None:
        """SPEC_03「clean」: 手元の名前は,大文字と小文字まで同じものだけ(Windows でも)."""
        _put_local(clean_project, local_rel, b"v")
        _clean_fake(monkeypatch, clean_output([file_record(server_rel, b"v")]))
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert _categories(judged[0]) == {server_rel: CleanCategory.UNEXPLAINED}

    def test_case_of_local_run_dir_must_match(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """手元の実験フォルダの名前の大文字小文字が違うときも,一致としない."""
        other = clean_project / "runs" / CLEAN_RUN_ID.upper()
        other.mkdir(parents=True)
        (other / "a.txt").write_bytes(b"v")
        _clean_fake(monkeypatch, clean_output([file_record("a.txt", b"v")]))
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert _categories(judged[0]) == {"a.txt": CleanCategory.UNEXPLAINED}

    def test_two_server_names_differing_in_case_match_only_once(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """サーバの A.csv と a.csv を,手元の 1 つのファイルで両方一致にしない."""
        _put_local(clean_project, "a.csv", b"v")
        output = clean_output([file_record("A.csv", b"v"), file_record("a.csv", b"v")])
        _clean_fake(monkeypatch, output)
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert judged[0].matched.count == 1
        assert _categories(judged[0]) == {
            "A.csv": CleanCategory.UNEXPLAINED,
            "a.csv": CleanCategory.MATCHED,
        }

    def test_windows_short_name_is_not_matched(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """Windows の短い名前(8.3)でファイルを開けても,実際の名前でなければ一致としない."""
        if sys.platform != "win32":
            pytest.skip("短い名前は Windows だけ")
        import ctypes

        path = _put_local(clean_project, "averylongfilename_example.txt", b"v")
        buffer = ctypes.create_unicode_buffer(1024)
        length = ctypes.windll.kernel32.GetShortPathNameW(str(path), buffer, 1024)
        short = Path(buffer.value).name if length else ""
        if not short or short == path.name:
            pytest.skip("この環境では短い名前が作られない")
        _clean_fake(monkeypatch, clean_output([file_record(short, b"v")]))
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert _categories(judged[0]) == {short: CleanCategory.UNEXPLAINED}

    def test_local_file_link_is_not_matched(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
    ) -> None:
        target = tmp_path / "elsewhere.txt"
        target.write_bytes(b"v")
        _local_run(clean_project).mkdir(parents=True)
        _symlink_or_skip(_local_run(clean_project) / "a.txt", target)
        _clean_fake(monkeypatch, clean_output([file_record("a.txt", b"v")]))
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert _categories(judged[0]) == {"a.txt": CleanCategory.UNEXPLAINED}

    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    @pytest.mark.parametrize("where", ["middle", "run_dir"])
    def test_local_folder_link_is_not_matched(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        tmp_path: Path,
        junction_or_skip: Callable[[Path, Path], None],
        kind: str,
        where: str,
    ) -> None:
        """SPEC_03「clean」: 途中のフォルダ・手元の実験フォルダがリンク等なら一致としない."""
        target = tmp_path / "elsewhere"
        (target / "sub").mkdir(parents=True)
        (target / "sub" / "a.txt").write_bytes(b"v")
        (target / "a.txt").write_bytes(b"v")
        if where == "middle":
            _local_run(clean_project).mkdir(parents=True)
            link, rel = _local_run(clean_project) / "sub", "sub/a.txt"
            target = target / "sub"
        else:
            (clean_project / "runs").mkdir(parents=True)
            link, rel = _local_run(clean_project), "a.txt"
        if kind == "symlink":
            _symlink_or_skip(link, target)
        else:
            junction_or_skip(link, target)
        _clean_fake(monkeypatch, clean_output([file_record(rel, b"v")]))
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert _categories(judged[0]) == {rel: CleanCategory.UNEXPLAINED}

    def test_server_paths_never_open_files_outside_local_run_dir(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
    ) -> None:
        """サーバから来た相対パスで,手元の実験フォルダの外のファイルを開かない・一致にしない."""
        data = b"outside content"
        (clean_project / "runs").mkdir(parents=True)
        (clean_project / "runs" / "outside.txt").write_bytes(data)
        (clean_project / "top.txt").write_bytes(data)
        absolute = tmp_path / "abs.txt"
        absolute.write_bytes(data)
        _put_local(clean_project, "ok.txt", data)
        prefix = f"./{CLEAN_RUN_ID}/"
        size, digest = str(len(data)), sha(data)
        bad = [
            "../outside.txt",
            "../../top.txt",
            "sub/../../outside.txt",
            "./../outside.txt",
            "..\\outside.txt",
            "..\\..\\top.txt",
            absolute.as_posix(),
            "/" + absolute.as_posix().lstrip("/"),
            str(absolute),
            "C:" + "../outside.txt",
            "ok.txt/",
            "ok.txt.",
            "ok.txt ",
            "ok.txt:stream",
        ]
        # Linux では,絶対パスの 3 つの書き方が同じ文字列になる.同じ相対パスが 2 回出る出力は
        # 解析が拒否するので(別のテストで確かめている),重なりを除いてから並べる
        bad = list(dict.fromkeys(bad))
        entries = [raw_file_record(size, digest, prefix + rel) for rel in bad]
        _clean_fake(monkeypatch, clean_output(entries))
        opened: list[Path] = []
        original = cli._hash_local_file

        def spy(path: Path, info):
            opened.append(Path(path))
            return original(path, info)

        monkeypatch.setattr(cli, "_hash_local_file", spy)
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert judged[0].matched.count == 0
        assert judged[0].unexplained.count == len(bad)
        run_dir = _local_run(clean_project).resolve()
        for path in opened:
            assert path.resolve().is_relative_to(run_dir)

    # --- 実験 ID・サーバの探し方 ---

    @pytest.mark.parametrize(
        "run_id",
        ["", "..", "a/b", "-rf", "a;b", "$(x)", f"{CLEAN_RUN_ID}\n", "x.", "nul", "_x", "a b"],
    )
    def test_bad_run_id_is_error_without_connecting(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str
    ) -> None:
        """SPEC_03「clean」: 不正な RUN_ID は,サーバに接続せずにエラー.

        `-` で始まるものは `--` の後に置く(置かなければ argparse のエラーになる).
        """
        fake = _clean_fake(monkeypatch, clean_output([]))
        try:
            rc = cli.main(["clean", "--dry-run", "--", run_id])
        except SystemExit as exc:
            rc = exc.code
        assert rc not in (0, None)
        assert fake.calls == []

    def test_found_on_one_server(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        _clean_fake(monkeypatch, _MISSING, clean_output([]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0
        out = capsys.readouterr().out
        assert "[Archimedes]" in out and "[Newton]" not in out

    def test_found_on_two_servers_is_error(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _clean_fake(monkeypatch, clean_output([]), clean_output([]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0

    def test_found_nowhere_is_error(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _clean_fake(monkeypatch, _MISSING, _MISSING)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0

    @pytest.mark.parametrize("rc", [255, cli._TIMEOUT_RC])
    def test_unreachable_server_warns_and_continues(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
        rc: int,
    ) -> None:
        caplog.set_level(logging.DEBUG)
        _clean_fake(monkeypatch, _CleanServer(b"", rc=rc), clean_output([]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0
        warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
        assert any("Newton" in w for w in warnings)

    def test_all_unreachable_is_error(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _clean_fake(monkeypatch, _CleanServer(b"", rc=255), _CleanServer(b"", rc=255))
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0

    @pytest.mark.parametrize(
        "bad",
        [
            b"",
            b"garbage\n",
            clean_output([])[:-10],
            clean_output([], find_rc=1),
            clean_output([], after=CLEAN_STATE_LINK),
            clean_output([nohash_record("x")]),
            clean_state_output(CLEAN_STATE_LINK),
            clean_state_output(CLEAN_STATE_NOT_DIR),
            clean_state_output(CLEAN_STATE_UNREADABLE),
            clean_output([]) + clean_output([]),
        ],
        ids=[
            "empty", "garbage", "truncated", "find_failed", "after_link", "nohash", "link",
            "notdir", "unreadable", "twice",
        ],
    )  # fmt: skip
    @pytest.mark.parametrize("bad_on", ["Newton", "Archimedes"])
    def test_bad_server_stops_even_if_other_has_it(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        bad: bytes,
        bad_on: str,
    ) -> None:
        """SPEC_03「clean」: 解釈できない・リンク等のサーバが 1 台でもあれば止まる."""
        caplog.set_level(logging.DEBUG)
        good = clean_output([])
        newton, archimedes = (bad, good) if bad_on == "Newton" else (good, bad)
        judged = _spy_judgement(monkeypatch)
        _clean_fake(monkeypatch, newton, archimedes)
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0
        assert judged == []
        output = _all_output(capsys, caplog)
        assert "消せる" not in output
        assert bad_on in output

    @pytest.mark.parametrize(
        "bad",
        [b"", clean_output([])[:-10], clean_state_output(CLEAN_STATE_LINK)],
        ids=["empty", "truncated", "link"],
    )
    def test_bad_output_with_server_option_is_error(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        bad: bytes,
    ) -> None:
        _clean_fake(monkeypatch, bad)
        assert cli.main(["clean", CLEAN_RUN_ID, "--server", "Newton", "--dry-run"]) != 0
        assert "消せる" not in capsys.readouterr().out

    def test_running_job_warns(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """SPEC_03「clean」: そのサーバでジョブが実行中なら,警告を出す."""
        caplog.set_level(logging.DEBUG)
        server = _CleanServer(clean_output([]), probe_stdout=_probe_with_sessions(["job train1"]))
        _clean_fake(monkeypatch, server)
        cli.main(["clean", CLEAN_RUN_ID, "--dry-run"])
        warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
        assert any("実行中" in w and "Newton" in w for w in warnings)

    def test_no_running_job_no_warning(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        caplog.set_level(logging.DEBUG)
        _clean_fake(monkeypatch, clean_output([]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0
        warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
        assert not any("実行中" in w for w in warnings)

    # --- 名前を出さない ---

    @pytest.mark.parametrize(
        "entries",
        [
            [file_record(f"{CLEAN_SECRET}.txt", b"v")],  # 一致
            [file_record(f"{CLEAN_SECRET}_x.txt", b"v")],  # 手元に無い
            [other_record(f"{CLEAN_SECRET}_link")],
            [file_record(f"{CLEAN_SECRET}/../e", b"v")],
            [file_record(f"checkpoints/{CLEAN_SECRET}", b"v")],
            [file_record(f"{CLEAN_SECRET}.txt"), file_record(f"{CLEAN_SECRET}.txt")],  # 解釈不可
            [nohash_record(CLEAN_SECRET)],
            [raw_file_record("x", "y", f"./{CLEAN_RUN_ID}/{CLEAN_SECRET}")],
            [raw_file_record("1", sha(b"x"), f"./other/{CLEAN_SECRET}")],
        ],
        ids=[
            "matched", "unexplained", "link", "unsafe", "checkpoint", "duplicate", "nohash",
            "malformed", "outside",
        ],
    )  # fmt: skip
    @pytest.mark.parametrize("dry_run", [False, True])
    def test_server_names_never_appear(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        entries: list,
        dry_run: bool,
    ) -> None:
        """SPEC_03「clean」: 相対パス・ファイル名は,表示・ログ・エラーのどこにも出さない."""
        caplog.set_level(logging.DEBUG)
        _put_local(clean_project, f"{CLEAN_SECRET}.txt", b"v")
        _clean_fake(monkeypatch, clean_output(entries))
        cli.main(["clean", CLEAN_RUN_ID] + (["--dry-run"] if dry_run else []))
        output = _all_output(capsys, caplog)
        assert CLEAN_SECRET not in output
        assert "secretclean" not in output

    # --- 引数 ---

    def test_run_id_and_logs_cannot_be_combined(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """SPEC_03「ログの削除の細部」: RUN_ID と --logs の両方,--logs と --discard-checkpoints は
        argparse のエラー(何も接続しない)."""
        fake = _clean_fake(monkeypatch, clean_output([]))
        for args in (
            ["clean", CLEAN_RUN_ID, "--logs"],
            ["clean", CLEAN_RUN_ID, "--logs", "train1"],
            ["clean", "--logs", "--discard-checkpoints"],
            ["clean", "--logs", "train1", "--discard-checkpoints"],
        ):
            with pytest.raises(SystemExit) as excinfo:
                cli.main(args)
            assert excinfo.value.code == 2
        assert fake.calls == []

    def test_run_id_is_required(self, clean_project: Path) -> None:
        with pytest.raises(SystemExit) as excinfo:
            cli.main(["clean"])
        assert excinfo.value.code == 2

    def test_help_has_options(self, capsys: pytest.CaptureFixture[str]) -> None:
        out = _help_text(["clean", "--help"], capsys)
        for option in ["--server", "--discard-checkpoints", "--dry-run", "--logs"]:
            assert option in out


# ---------------------------------------------------------------------------
# clean RUN_ID の削除(SPEC_03「clean」の手順 4・5,「削除の細部」)
# ---------------------------------------------------------------------------

_DELETED_OK = cli._SshResult(0, CLEAN_DELETED_MARKER.encode("ascii") + b"\n", b"")
# 消したことを表す 1 行(format_clean_deleted)に必ず入る言葉
_DELETED_LINE_WORD = "を消した:"


class _DeletingServer(_CleanServer):
    """_CleanServer に,削除のコマンドへの応答を決められるようにしたもの."""

    def __init__(self, clean_stdout: bytes, *, delete_result: cli._SshResult = _DELETED_OK):
        super().__init__(clean_stdout)
        self.delete_result = delete_result

    def __call__(self, argv: list[str]) -> cli._SshResult:
        if CLEAN_DELETED_MARKER in argv[-1] and CLEAN_BEGIN_MARKER not in argv[-1]:
            return self.delete_result
        return super().__call__(argv)


class _InputSpy(_TimeoutSpy):
    """_TimeoutSpy に,標準入力へ渡したバイト列の記録を足したもの."""

    def __init__(self, responses: dict[str, Callable[[list[str]], cli._SshResult]]) -> None:
        super().__init__(responses)
        self.inputs: list[bytes | None] = []

    def __call__(
        self, argv: list[str], *, input_bytes: bytes | None = None, timeout: float | None = None
    ) -> cli._SshResult:
        self.inputs.append(input_bytes)
        return super().__call__(argv, input_bytes=input_bytes, timeout=timeout)


def _delete_fake(
    monkeypatch: pytest.MonkeyPatch,
    newton: bytes | _CleanServer,
    archimedes: bytes | _CleanServer = _MISSING,
) -> _InputSpy:
    def server(value: bytes | _CleanServer) -> _CleanServer:
        return value if isinstance(value, _CleanServer) else _DeletingServer(value)

    fake = _InputSpy({NEWTON_ADDR: server(newton), ARCHIMEDES_ADDR: server(archimedes)})  # type: ignore[dict-item]
    monkeypatch.setattr(cli, "_run_ssh", fake)
    return fake


def _delete_calls(fake: _InputSpy) -> list[tuple[list[str], bytes | None, float | None]]:
    return [
        (argv, data, timeout)
        for argv, data, timeout in zip(fake.calls, fake.inputs, fake.timeouts, strict=True)
        if CLEAN_DELETED_MARKER in argv[-1]
    ]


def _local_state(root: Path) -> dict[str, bytes | str]:
    """手元のプロジェクトの一覧と内容(前後で比べる)."""
    state: dict[str, bytes | str] = {}
    for path in sorted(root.rglob("*")):
        rel = path.relative_to(root).as_posix()
        if path.is_symlink():
            state[rel] = "link"
        elif path.is_dir():
            state[rel] = "dir"
        else:
            state[rel] = path.read_bytes()
    return state


def _put_secret(project: Path) -> bytes:
    """手元と一致する,名前を出してはならないファイルを置き,その記録を返す."""
    _put_local(project, f"{CLEAN_SECRET}.txt", b"v")
    return file_record(f"{CLEAN_SECRET}.txt", b"v")


def _results_yaml_with_dir(results_dir: str) -> str:
    assert CLEAN_RESULTS_YAML.startswith("results:\n")
    return CLEAN_RESULTS_YAML.replace("results:\n", f"results:\n  dir: {results_dir}\n", 1)


class TestCleanDelete:
    def test_delete_command_and_stdin_match_judgement(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """送るのは 1 回,そのサーバの remote_dir・設定の結果の置き場・RUN_ID のコマンドで,
        標準入力は判定から作った一覧と同じ."""
        _put_matched(clean_project)
        fake = _delete_fake(monkeypatch, _matched_output())
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0
        ((argv, data, timeout),) = _delete_calls(fake)
        assert argv[-2] == "Newton"
        assert argv[-1] == build_clean_delete_command(
            "~/work/DemoProject", results_dir="runs", run_id=CLEAN_RUN_ID
        )
        (judgement,) = judged
        assert data == build_clean_expected_input(judgement, CLEAN_RUN_ID)
        # 標準入力を使う(-n を付けない)
        assert "-n" not in argv[:-2]
        # 一覧と同じく,他のサブコマンドより 600 秒長く待つ
        list_timeouts = [
            t for a, t in zip(fake.calls, fake.timeouts, strict=True) if CLEAN_BEGIN_MARKER in a[-1]
        ]
        assert list_timeouts and set(list_timeouts) == {timeout}

    def test_empty_run_dir_sends_end_record_only(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _delete_fake(monkeypatch, clean_output([]))
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0
        ((_, data, _),) = _delete_calls(fake)
        assert data == CLEAN_EXPECT_END_RECORD.encode("ascii") + b"\0"

    @pytest.mark.parametrize("server_option", [[], ["--server", "Archimedes"]])
    def test_delete_goes_to_the_server_that_was_judged(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        server_option: list[str],
    ) -> None:
        """判定したサーバへ,そのサーバの remote_dir と設定の結果の置き場で送る."""
        config = CONFIG_YAML_WITHOUT_RESULTS
        first = config.index("remote_dir: ~/work/DemoProject")
        second = config.index("remote_dir: ~/work/DemoProject", first + 1)
        config = config[:second] + config[second:].replace(
            "~/work/DemoProject", "~/work/OtherPlace", 1
        )
        (project / "labremote.yaml").write_text(
            config + _results_yaml_with_dir("output/runs"), encoding="utf-8"
        )
        local = project / "output" / "runs" / CLEAN_RUN_ID / "metrics.json"
        local.parent.mkdir(parents=True)
        local.write_bytes(b"{}")
        fake = _delete_fake(
            monkeypatch, _MISSING, clean_output([file_record("metrics.json", b"{}")])
        )
        assert cli.main(["clean", CLEAN_RUN_ID, *server_option]) == 0
        ((argv, _, _),) = _delete_calls(fake)
        assert argv[-2] == "Archimedes"
        assert argv[-1] == build_clean_delete_command(
            "~/work/OtherPlace", results_dir="output/runs", run_id=CLEAN_RUN_ID
        )
        assert local.read_bytes() == b"{}"

    # --- 消すコマンドを送らない場合 ---

    @pytest.mark.parametrize(
        ("newton", "archimedes"),
        [
            (_matched_output([file_record("extra.txt", b"e")]), _MISSING),
            (clean_output([file_record("metrics.json", b"[]")]), _MISSING),
            (_matched_output([other_record("link")]), _MISSING),
            (_matched_output([raw_file_record("1", sha(b"x"), f"./{CLEAN_RUN_ID}/../o")]),
             _MISSING),
            (_matched_output([file_record("checkpoints/best.pth", b"w")]), _MISSING),
            (_matched_output([nohash_record("x")]), _MISSING),
            (clean_output([], find_rc=1), _MISSING),
            (clean_output([], after=CLEAN_STATE_LINK), _MISSING),
            (clean_output([])[:-10], _MISSING),
            (b"garbage\n", _MISSING),
            (b"", _MISSING),
            (clean_output([]) + clean_output([]), _MISSING),
            (clean_state_output(CLEAN_STATE_LINK), _MISSING),
            (clean_state_output(CLEAN_STATE_NOT_DIR), _MISSING),
            (clean_state_output(CLEAN_STATE_UNREADABLE), _MISSING),
            (clean_state_output(CLEAN_STATE_RESULTS_LINK), _MISSING),
            (_MISSING, clean_state_output(CLEAN_STATE_RESULTS_LINK)),
            (_MISSING, _MISSING),
            (clean_output([]), clean_output([])),
        ],
        ids=[
            "not_local", "content_differs", "link_inside", "unsafe_path", "checkpoint",
            "nohash", "find_failed", "after_link", "truncated", "garbage", "empty_output",
            "twice", "run_dir_link", "run_dir_notdir", "run_dir_unreadable", "results_link",
            "results_link_on_other", "nowhere", "two_servers",
        ],
    )  # fmt: skip
    def test_no_delete_command_unless_deletable(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        newton: bytes,
        archimedes: bytes,
    ) -> None:
        """SPEC_03「clean」: 消せると判定したときだけ送る(--dry-run が無くても)."""
        caplog.set_level(logging.DEBUG)
        _put_matched(clean_project)
        before = _local_state(clean_project)
        fake = _delete_fake(monkeypatch, newton, archimedes)
        assert cli.main(["clean", CLEAN_RUN_ID]) != 0
        _assert_no_delete_commands(fake)
        assert _DELETED_LINE_WORD not in _all_output(capsys, caplog)
        assert _local_state(clean_project) == before

    def test_dry_run_sends_no_delete_command(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _put_matched(clean_project)
        fake = _delete_fake(monkeypatch, _matched_output())
        assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run", "--discard-checkpoints"]) == 0
        _assert_no_delete_commands(fake)

    @pytest.mark.parametrize(
        "run_id", ["..", "a/b", "-rf", "a;b", "$(x)", "*", f"{RUN_ID}\n", "x."]
    )
    def test_bad_run_id_connects_nowhere(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str
    ) -> None:
        fake = _delete_fake(monkeypatch, clean_output([]))
        try:
            rc = cli.main(["clean", "--", run_id])
        except SystemExit as exc:
            rc = exc.code
        assert rc not in (0, None)
        assert fake.calls == []

    @pytest.mark.parametrize("kind", ["symlink", "junction"])
    @pytest.mark.parametrize(
        ("results_dir", "linked"),
        [("runs", "runs"), ("output/runs", "output"), ("output/runs", "output/runs")],
    )
    def test_local_results_dir_link_connects_nowhere(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        tmp_path: Path,
        junction_or_skip: Callable[[Path, Path], None],
        kind: str,
        results_dir: str,
        linked: str,
    ) -> None:
        """SPEC_03「clean」: 手元の結果の置き場の途中がリンク等なら,接続せずに止まる."""
        _use_config(project, _results_yaml_with_dir(results_dir))
        target = tmp_path / "elsewhere"
        rest = results_dir[len(linked) :].lstrip("/")
        run_dir = (target / rest if rest else target) / CLEAN_RUN_ID
        run_dir.mkdir(parents=True)
        (run_dir / "metrics.json").write_bytes(b"{}")
        link = project / linked
        link.parent.mkdir(parents=True, exist_ok=True)
        if kind == "symlink":
            _symlink_or_skip(link, target)
        else:
            junction_or_skip(link, target)
        fake = _delete_fake(monkeypatch, clean_output([file_record("metrics.json", b"{}")]))
        for args in (["clean", CLEAN_RUN_ID], ["clean", CLEAN_RUN_ID, "--dry-run"]):
            assert cli.main(args) != 0
        assert fake.calls == []
        assert (run_dir / "metrics.json").read_bytes() == b"{}"

    def test_discard_checkpoints_decides_whether_to_send(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _put_matched(clean_project)
        weight = file_record("checkpoints/sub/e1.pth", b"w")
        fake = _delete_fake(monkeypatch, _matched_output([weight]))
        assert cli.main(["clean", CLEAN_RUN_ID]) != 0
        _assert_no_delete_commands(fake)
        fake = _delete_fake(monkeypatch, _matched_output([weight]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--discard-checkpoints"]) == 0
        ((_, data, _),) = _delete_calls(fake)
        assert data is not None and weight + b"\0" in data

    # --- サーバの応答ごとの表示と終了コード ---

    def test_success_shows_count_and_size(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        _put_matched(clean_project)
        _delete_fake(monkeypatch, _matched_output())
        judged = _spy_judgement(monkeypatch)
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0
        out = capsys.readouterr().out
        assert format_clean_deleted("Newton", CLEAN_RUN_ID, "runs", judged[0]) in out
        assert judged[0].total.count == 5

    def test_marker_after_login_banner_is_success(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        result = cli._SshResult(0, b"Welcome\n" + CLEAN_DELETED_MARKER.encode() + b"\n", b"")
        _delete_fake(monkeypatch, _DeletingServer(clean_output([]), delete_result=result))
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0

    @pytest.mark.parametrize(
        ("result", "words"),
        [
            (cli._SshResult(0, b"", b""), []),
            (cli._SshResult(0, b"", CLEAN_DELETED_MARKER.encode()), []),
            (cli._SshResult(0, CLEAN_DELETED_MARKER.encode()[:-1] + b"\n", b""), []),
            (cli._SshResult(0, b"x" + CLEAN_DELETED_MARKER.encode() + b"\n", b""), []),
            (cli._SshResult(1, CLEAN_DELETED_MARKER.encode() + b"\n", b""), []),
            (cli._SshResult(EXIT_CLEAN_MISMATCH, b"", b""), ["何も消していない", "もう一度"]),
            (cli._SshResult(EXIT_CLEAN_REMAINS, b"", b""), ["一部"]),
            (cli._SshResult(EXIT_NOT_FOUND, b"", b""), ["何も消していない"]),
            (cli._SshResult(EXIT_UNSAFE_PATH, b"", b""), ["何も消していない"]),
            (cli._SshResult(EXIT_REMOTE_DIR_MISSING, b"", b""), ["何も消していない"]),
            (cli._SshResult(SSH_FAILURE_RC, b"", b"ssh: connection reset"), ["ls"]),
            (cli._SshResult(cli._TIMEOUT_RC, b"", b""), ["ls"]),
            (cli._SshResult(126, b"", b""), []),
        ],
        ids=[
            "rc0_no_marker", "marker_only_in_stderr", "partial_marker", "marker_not_whole_line",
            "marker_with_rc1", "mismatch_96", "remains_97", "not_found_92", "unsafe_94",
            "no_remote_dir_90", "ssh_failed", "timeout", "unknown_rc",
        ],
    )  # fmt: skip
    def test_failure_is_not_reported_as_deleted(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        result: cli._SshResult,
        words: list[str],
    ) -> None:
        """SPEC_03「clean」: 終了コード 0 で目印があるときだけ「消した」.それ以外は 0 以外."""
        caplog.set_level(logging.DEBUG)
        secret_record = _put_secret(clean_project)
        before = _local_state(clean_project)
        # サーバの標準エラーにファイル名が混じっていても出さない(ssh 自身の失敗は除く)
        if result.rc != SSH_FAILURE_RC and not result.stderr:
            result = cli._SshResult(result.rc, result.stdout, f"rm: {CLEAN_SECRET}.txt".encode())
        server = _DeletingServer(clean_output([secret_record]), delete_result=result)
        _delete_fake(monkeypatch, server)
        rc = cli.main(["clean", CLEAN_RUN_ID])
        assert rc != 0
        output = _all_output(capsys, caplog)
        assert _DELETED_LINE_WORD not in output
        for word in words:
            assert word in output
        assert CLEAN_SECRET not in output
        assert _local_state(clean_project) == before

    def test_local_files_are_never_touched_on_success(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _put_matched(clean_project)
        secret_record = _put_secret(clean_project)
        before = _local_state(clean_project)
        _delete_fake(monkeypatch, _matched_output([secret_record]))
        assert cli.main(["clean", CLEAN_RUN_ID, "--discard-checkpoints"]) == 0
        assert _local_state(clean_project) == before

    def test_names_never_appear_on_success(
        self,
        clean_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        caplog.set_level(logging.DEBUG)
        secret_record = _put_secret(clean_project)
        result = cli._SshResult(0, _DELETED_OK.stdout, f"warning {CLEAN_SECRET}".encode())
        _delete_fake(
            monkeypatch, _DeletingServer(clean_output([secret_record]), delete_result=result)
        )
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0
        assert CLEAN_SECRET not in _all_output(capsys, caplog)


# ---------------------------------------------------------------------------
# clean --logs(SPEC_03「clean」の「ログの削除の細部」)
#
# 偽の ssh は,ls のコマンドには ls の出力を,ログを消すコマンドには指定の結果を返す.それ以外の
# コマンド(clean RUN_ID の一覧・削除,probe 等)が送られたら失敗にする.
# ---------------------------------------------------------------------------

_LOGS_DELETED_OK = cli._SshResult(0, CLEAN_LOGS_DELETED_MARKER.encode("ascii") + b"\n", b"")
# 消せたときに出る行の言葉(失敗のときに出てはならない)
_LOGS_DELETED_WORD = "ジョブのログを消した"
_REMOTE = "~/work/DemoProject"


def _logs_ls(logs: dict[str, int], running: tuple[str, ...] = ()) -> bytes:
    return ls_output(
        results=[dir_record(RUN_ID, 3, 8)],
        logs=[log_record(f"{name}.log", size) for name, size in logs.items()],
        jobs=[job_record(name) for name in running],
    )


class _LogsServer:
    """1 台のサーバの応答(ls には ls_stdout,ログを消すコマンドには delete_result)."""

    def __init__(
        self,
        ls_stdout: bytes | None,
        *,
        ls_rc: int = 0,
        delete_result: cli._SshResult = _LOGS_DELETED_OK,
    ) -> None:
        self.ls_stdout = ls_stdout
        self.ls_rc = ls_rc
        self.delete_result = delete_result

    def __call__(self, argv: list[str]) -> cli._SshResult:
        command = argv[-1]
        if CLEAN_LOGS_DELETED_MARKER in command:
            return self.delete_result
        if LS_BEGIN_MARKER in command:
            if self.ls_rc != 0 or self.ls_stdout is None:
                return cli._SshResult(self.ls_rc or 255, b"", b"ssh: connect to host: timed out")
            return cli._SshResult(0, self.ls_stdout, b"")
        raise AssertionError(f"clean --logs が想定外のコマンドを送った: {command[:80]}")


def _logs_fake(
    monkeypatch: pytest.MonkeyPatch,
    newton: _LogsServer,
    archimedes: _LogsServer | None = None,
) -> _TimeoutSpy:
    archimedes = archimedes or _LogsServer(ls_missing_remote_dir())
    fake = _TimeoutSpy({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: archimedes})  # type: ignore[dict-item]
    monkeypatch.setattr(cli, "_run_ssh", fake)
    return fake


def _log_deletes(fake: FakeSsh) -> list[tuple[str, str]]:
    return [(argv[-2], argv[-1]) for argv in fake.calls if CLEAN_LOGS_DELETED_MARKER in argv[-1]]


def _assert_no_log_delete(fake: FakeSsh) -> None:
    """送ったのは ls のコマンドだけで,消すコマンド(rm を含むもの)が無い."""
    for argv in fake.calls:
        command = argv[-1]
        assert CLEAN_LOGS_DELETED_MARKER not in command
        assert CLEAN_DELETED_MARKER not in command
        assert command == build_ls_command(_REMOTE, results_dir="runs") or (
            LS_BEGIN_MARKER in command
        )
        for word in _DELETE_WORDS:
            assert not re.search(rf"(^|[\s;(|&'\"]){word}(\s|$)", command), word


def _put_local_logs(project: Path) -> dict[str, bytes | str]:
    """手元の結果の置き場に,サーバと同じ名前のログ等を置き,その状態を返す."""
    for name in ("train1", "train2", "eval1"):
        path = project / "runs" / "_remote_logs" / f"{name}.log"
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(f"local {name}\n".encode())
    (project / "runs" / RUN_ID).mkdir(parents=True, exist_ok=True)
    (project / "runs" / RUN_ID / "train1.log").write_bytes(b"local run\n")
    return _local_state(project)


@pytest.fixture
def logs_project(project: Path) -> Path:
    """手元の結果の置き場に,サーバと同じ名前のログを置いたプロジェクト."""
    _put_local_logs(project)
    return project


class TestCleanLogsArgs:
    """SPEC_03「ログの削除の細部」の「引数」."""

    @pytest.mark.parametrize(
        ("argv", "logs", "server", "dry_run"),
        [
            (["clean", "--logs", "train1", "train2"], ["train1", "train2"], None, False),
            (["clean", "--logs"], [], None, False),
            (["clean", "--logs", "--server", "Newton"], [], "Newton", False),
            (["clean", "--logs", "train1", "--dry-run"], ["train1"], None, True),
            (["clean", "--dry-run", "--logs", "train1"], ["train1"], None, True),
            (["clean", "--server", "Newton", "--logs", "a1", "b2"], ["a1", "b2"], "Newton", False),
        ],
    )
    def test_parsed_as_intended(
        self, argv: list[str], logs: list[str], server: str | None, dry_run: bool
    ) -> None:
        args = cli._parse_args(argv)
        assert args.subcommand == "clean"
        assert args.run_id is None
        assert args.logs == logs
        assert args.server == server
        assert args.dry_run is dry_run
        assert not args.discard_checkpoints

    @pytest.mark.parametrize(
        "argv",
        [
            ["clean"],
            ["clean", "--dry-run"],
            ["clean", "--server", "Newton"],
            ["clean", "r1", "--logs"],
            ["clean", "r1", "--logs", "train1"],
            ["clean", "--logs", "train1", "r1", "--dry-run", "x"],
            ["clean", "--logs", "--discard-checkpoints"],
            ["clean", "--logs", "train1", "--discard-checkpoints"],
            ["clean", "--discard-checkpoints", "--logs", "train1"],
            ["clean", "--logs", "--dry-run", "train1"],
            ["clean", "--logs", "--server", "Newton", "train1"],
            ["clean", "--logs", "-rf"],
            ["clean", "--logs", "--help-me"],
        ],
        ids=lambda argv: " ".join(argv[1:]) or "nothing",
    )
    def test_bad_combinations_are_exit_2_without_connecting(
        self, logs_project: Path, monkeypatch: pytest.MonkeyPatch, argv: list[str]
    ) -> None:
        before = _local_state(logs_project)
        fake = _logs_fake(monkeypatch, _LogsServer(_logs_ls({"train1": 1})))
        with pytest.raises(SystemExit) as excinfo:
            cli.main(argv)
        assert excinfo.value.code == 2
        assert fake.calls == []
        assert _local_state(logs_project) == before

    @pytest.mark.parametrize(
        "names",
        [["a b"], ["a;b"], ["$(x)"], ["*"], ["train1\n"], ["a.log"], ["x" * 65], [".."],
         ["a/b"], ["train1", "train1"], ["train1", "ok2", "train1"], ["train1", "a b"]],
    )  # fmt: skip
    def test_bad_names_are_rejected_before_connecting(
        self, logs_project: Path, monkeypatch: pytest.MonkeyPatch, names: list[str]
    ) -> None:
        fake = _logs_fake(monkeypatch, _LogsServer(_logs_ls({"train1": 1})))
        assert cli.main(["clean", "--logs", *names]) != 0
        assert fake.calls == []

    def test_names_after_logs_are_not_run_ids(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """--logs の後の名前は,実験 ID として扱われない(実験フォルダの一覧・削除を送らない)."""
        _put_matched(clean_project)
        fake = _logs_fake(monkeypatch, _LogsServer(_logs_ls({CLEAN_RUN_ID: 1})))
        assert cli.main(["clean", "--logs", CLEAN_RUN_ID]) == 0
        assert len(_log_deletes(fake)) == 1
        for argv in fake.calls:
            assert CLEAN_BEGIN_MARKER not in argv[-1]
            assert CLEAN_DELETED_MARKER not in argv[-1]

    def test_run_id_does_not_send_log_delete(
        self, clean_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """clean RUN_ID では,ログを消すコマンドを送らない(逆の取り違え)."""
        _put_matched(clean_project)
        fake = _clean_fake(monkeypatch, _matched_output())
        assert cli.main(["clean", CLEAN_RUN_ID]) == 0
        assert fake.calls
        for argv in fake.calls:
            assert CLEAN_LOGS_DELETED_MARKER not in argv[-1]

    def test_help_mentions_logs(self, capsys: pytest.CaptureFixture[str]) -> None:
        out = _help_text(["clean", "--help"], capsys)
        assert "--logs" in out and "NAME" in out
        for word in PROJECT_WORDS:
            assert word not in out.lower()


class TestCleanLogsNoDelete:
    """SPEC_03: 消すコマンドを送るのは,候補が 1 つ以上あり --dry-run が無いときだけ."""

    def test_dry_run_shows_candidates_and_kept(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        before = _local_state(logs_project)
        fake = _logs_fake(
            monkeypatch,
            _LogsServer(_logs_ls({"train1": 2048, "train2": 10}, ("train2",))),
            _LogsServer(_logs_ls({"eval1": 5})),
        )
        assert cli.main(["clean", "--logs", "--dry-run"]) == 0
        _assert_no_log_delete(fake)
        out = capsys.readouterr().out
        assert "train1" in out and "train2" in out and "eval1" in out
        assert "Newton" in out and "Archimedes" in out
        assert _LOGS_DELETED_WORD not in out
        assert _local_state(logs_project) == before

    def test_dry_run_with_names(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        fake = _logs_fake(monkeypatch, _LogsServer(_logs_ls({"train1": 3, "train2": 4})))
        assert cli.main(["clean", "--logs", "train1", "--dry-run"]) == 0
        _assert_no_log_delete(fake)
        assert "train1" in capsys.readouterr().out

    @pytest.mark.parametrize(
        ("newton", "archimedes"),
        [
            (_logs_ls({"train1": 1, "train2": 2}, ("train1", "train2")), ls_missing_remote_dir()),
            (_logs_ls({}), _logs_ls({})),
            (ls_output(logs=None), ls_missing_remote_dir()),
            (_logs_ls({"train1": 1}, ("train1",)), _logs_ls({"eval1": 1}, ("eval1",))),
        ],
        ids=["all_running", "no_logs", "no_logs_dir", "all_running_two_servers"],
    )
    def test_no_candidates_is_zero_without_delete(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        newton: bytes,
        archimedes: bytes,
    ) -> None:
        before = _local_state(logs_project)
        fake = _logs_fake(monkeypatch, _LogsServer(newton), _LogsServer(archimedes))
        assert cli.main(["clean", "--logs"]) == 0
        _assert_no_log_delete(fake)
        out = capsys.readouterr().out
        assert "消すログは無い" in out
        assert _LOGS_DELETED_WORD not in out
        assert _local_state(logs_project) == before

    @pytest.mark.parametrize("dry_run", [False, True])
    @pytest.mark.parametrize(
        ("newton", "archimedes", "names"),
        [
            (_LogsServer(_logs_ls({"train1": 1}, ("train1",))), None, ["train1"]),
            (_LogsServer(_logs_ls({"train2": 1})), None, ["train1"]),
            (_LogsServer(_logs_ls({"train1": 1})), _LogsServer(_logs_ls({"train1": 2})),
             ["train1"]),
            (_LogsServer(_logs_ls({"train1": 1})), _LogsServer(_logs_ls({"train2": 2})),
             ["train1", "train2"]),
            (_LogsServer(_logs_ls({"train1": 1})), _LogsServer(None), ["train1"]),
            (_LogsServer(_logs_ls({"train1": 1})), _LogsServer(b"garbage"), ["train1"]),
            (_LogsServer(_logs_ls({"train1": 1, "train2": 1}, ("train2",))), None,
             ["train1", "train2"]),
            (_LogsServer(_logs_ls({"train1": 1, "train3": 1})), None,
             ["train1", "train2", "train3"]),
            (_LogsServer(None), _LogsServer(None), ["train1"]),
        ],
        ids=[
            "running", "missing", "two_servers", "split", "unreachable_other",
            "unreadable_other", "one_running", "one_missing", "all_unreachable",
        ],
    )  # fmt: skip
    def test_named_errors_send_no_delete(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        newton: _LogsServer,
        archimedes: _LogsServer | None,
        names: list[str],
        dry_run: bool,
    ) -> None:
        before = _local_state(logs_project)
        fake = _logs_fake(monkeypatch, newton, archimedes)
        argv = ["clean", "--logs", *names] + (["--dry-run"] if dry_run else [])
        assert cli.main(argv) != 0
        _assert_no_log_delete(fake)
        output = _all_output(capsys, caplog)
        assert _LOGS_DELETED_WORD not in output
        assert _local_state(logs_project) == before
        for word in PROJECT_WORDS:
            assert word not in output.lower()

    def test_all_unreachable_without_names_is_error(
        self, logs_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _logs_fake(monkeypatch, _LogsServer(None), _LogsServer(None))
        assert cli.main(["clean", "--logs"]) != 0
        _assert_no_log_delete(fake)


class TestCleanLogsDeleteFlow:
    """SPEC_03: 送る消すコマンドは,サーバごとに 1 回,そのサーバの候補だけ."""

    def test_command_per_server_with_its_candidates(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        before = _local_state(logs_project)
        fake = _logs_fake(
            monkeypatch,
            _LogsServer(_logs_ls({"train1": 300, "train2": 20, "old3": 1}, ("train2",))),
            _LogsServer(_logs_ls({"eval1": 5})),
        )
        assert cli.main(["clean", "--logs"]) == 0
        deletes = _log_deletes(fake)
        assert sorted(deletes) == sorted(
            [
                (
                    "Newton",
                    build_clean_logs_command(_REMOTE, results_dir="runs", names=["train1", "old3"]),
                ),
                (
                    "Archimedes",
                    build_clean_logs_command(_REMOTE, results_dir="runs", names=["eval1"]),
                ),
            ]
        )
        newton_command = dict(deletes)["Newton"]
        assert "train2" not in newton_command
        assert "eval1" not in newton_command
        out = capsys.readouterr().out
        assert _LOGS_DELETED_WORD in out
        assert "train1" in out and "eval1" in out
        assert _local_state(logs_project) == before

    def test_named_delete_on_the_server_that_has_it(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        fake = _logs_fake(
            monkeypatch,
            _LogsServer(_logs_ls({"train9": 1})),
            _LogsServer(_logs_ls({"train1": 3, "train2": 4, "train3": 5}, ("train3",))),
        )
        assert cli.main(["clean", "--logs", "train2", "train1"]) == 0
        deletes = _log_deletes(fake)
        assert len(deletes) == 1
        host, command = deletes[0]
        assert host == "Archimedes"
        names = sorted(["train1", "train2"])
        expected = {
            build_clean_logs_command(_REMOTE, results_dir="runs", names=order)
            for order in (names, names[::-1])
        }
        assert command in expected
        assert "train3" not in command and "train9" not in command

    def test_data_ready_false_servers_are_included(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _write_config_data(
            project, lambda data: [s.update(data_ready=False) for s in data["servers"]]
        )
        fake = _logs_fake(
            monkeypatch, _LogsServer(_logs_ls({"a1": 1})), _LogsServer(_logs_ls({"b2": 1}))
        )
        assert cli.main(["clean", "--logs"]) == 0
        assert sorted(host for host, _ in _log_deletes(fake)) == ["Archimedes", "Newton"]

    def test_server_option_only_that_server(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _logs_fake(
            monkeypatch, _LogsServer(_logs_ls({"a1": 1})), _LogsServer(_logs_ls({"a1": 1}))
        )
        assert cli.main(["clean", "--logs", "--server", "Archimedes"]) == 0
        assert {argv[-2] for argv in fake.calls} == {"Archimedes"}
        assert [host for host, _ in _log_deletes(fake)] == ["Archimedes"]

    def test_server_option_with_names(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        """同じ名前が 2 台にあっても,--server を付ければそのサーバだけで消す."""
        fake = _logs_fake(
            monkeypatch, _LogsServer(_logs_ls({"a1": 1})), _LogsServer(_logs_ls({"a1": 1}))
        )
        assert cli.main(["clean", "--logs", "a1", "--server", "Newton"]) == 0
        assert {argv[-2] for argv in fake.calls} == {"Newton"}
        assert _log_deletes(fake) == [
            ("Newton", build_clean_logs_command(_REMOTE, results_dir="runs", names=["a1"]))
        ]

    def test_remote_dir_and_results_dir_come_from_config(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        def mutate(data: dict) -> None:
            data["servers"][1]["remote_dir"] = "/srv/other place/Demo"
            data["results"]["dir"] = "output/runs"

        _write_config_data(project, mutate)
        fake = _logs_fake(
            monkeypatch, _LogsServer(_logs_ls({"a1": 1})), _LogsServer(_logs_ls({"b2": 1}))
        )
        assert cli.main(["clean", "--logs"]) == 0
        assert sorted(_log_deletes(fake)) == sorted(
            [
                (
                    "Newton",
                    build_clean_logs_command(_REMOTE, results_dir="output/runs", names=["a1"]),
                ),
                (
                    "Archimedes",
                    build_clean_logs_command(
                        "/srv/other place/Demo", results_dir="output/runs", names=["b2"]
                    ),
                ),
            ]
        )

    @pytest.mark.parametrize("rc", [255, cli._TIMEOUT_RC])
    def test_one_unreachable_continues_and_warns(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        rc: int,
    ) -> None:
        caplog.set_level(logging.WARNING)
        fake = _logs_fake(
            monkeypatch, _LogsServer(None, ls_rc=rc), _LogsServer(_logs_ls({"b2": 1}))
        )
        cli.main(["clean", "--logs"])
        assert [host for host, _ in _log_deletes(fake)] == ["Archimedes"]
        output = _all_output(capsys, caplog)
        assert _LOGS_DELETED_WORD in output
        warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
        assert any("Newton" in w and "確かめていない" in w for w in warnings), warnings

    def test_unreadable_server_continues_but_nonzero(
        self, logs_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _logs_fake(monkeypatch, _LogsServer(b"garbage"), _LogsServer(_logs_ls({"b2": 1})))
        assert cli.main(["clean", "--logs"]) != 0
        assert [host for host, _ in _log_deletes(fake)] == ["Archimedes"]


# 消すコマンドへの応答.どれも「消した」と表示せず,0 以外で終わる
_LOGS_BAD_RESULTS = {
    "rc0_no_marker": cli._SshResult(0, b"", b""),
    "rc0_other_output": cli._SshResult(0, b"done\n", b""),
    "rc0_clean_run_marker": cli._SshResult(0, CLEAN_DELETED_MARKER.encode() + b"\n", b""),
    "rc0_marker_with_prefix": cli._SshResult(
        0, b"x" + CLEAN_LOGS_DELETED_MARKER.encode() + b"\n", b""
    ),
    "rc0_marker_in_stderr": cli._SshResult(0, b"", CLEAN_LOGS_DELETED_MARKER.encode() + b"\n"),
    "rc98_with_marker": cli._SshResult(98, CLEAN_LOGS_DELETED_MARKER.encode() + b"\n", b""),
    "rc98": cli._SshResult(98, b"", b""),
    "rc92": cli._SshResult(EXIT_NOT_FOUND, b"", b""),
    "rc94": cli._SshResult(EXIT_UNSAFE_PATH, b"", b""),
    "rc97": cli._SshResult(EXIT_CLEAN_REMAINS, b"", b""),
    "rc90": cli._SshResult(EXIT_REMOTE_DIR_MISSING, b"", b""),
    "rc1": cli._SshResult(1, b"", b""),
    "rc255": cli._SshResult(SSH_FAILURE_RC, b"", b"Connection reset"),
    "timeout": cli._SshResult(cli._TIMEOUT_RC, b"", b""),
}


class TestCleanLogsResults:
    """SPEC_03「表示」「終了コード」: 手元が「消した」と表示するのは,0 で目印があるときだけ."""

    def test_success_is_zero_and_shows_names(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        before = _local_state(logs_project)
        _logs_fake(monkeypatch, _LogsServer(_logs_ls({"train1": 2048, "old3": 7})))
        assert cli.main(["clean", "--logs", "--server", "Newton"]) == 0
        out = capsys.readouterr().out
        deleted = out.split(_LOGS_DELETED_WORD, 1)[1]
        assert "train1" in deleted and "old3" in deleted
        assert "Newton" in out
        assert _local_state(logs_project) == before

    @pytest.mark.parametrize("case", list(_LOGS_BAD_RESULTS))
    def test_bad_results_are_nonzero_and_not_deleted(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        case: str,
    ) -> None:
        before = _local_state(logs_project)
        _logs_fake(
            monkeypatch,
            _LogsServer(_logs_ls({"train1": 5}), delete_result=_LOGS_BAD_RESULTS[case]),
        )
        assert cli.main(["clean", "--logs", "train1"]) != 0
        output = _all_output(capsys, caplog)
        assert _LOGS_DELETED_WORD not in output
        assert _local_state(logs_project) == before
        if case == "rc98":
            assert "何も消していない" in output
        if case in ("rc255", "timeout"):
            assert "ls" in output
            assert "確かめられなかった" in output or "分からない" in output

    @pytest.mark.parametrize("case", ["rc98", "rc94", "rc255", "rc0_no_marker"])
    def test_first_server_fails_second_is_still_shown(
        self,
        logs_project: Path,
        monkeypatch: pytest.MonkeyPatch,
        capsys: pytest.CaptureFixture[str],
        caplog: pytest.LogCaptureFixture,
        case: str,
    ) -> None:
        fake = _logs_fake(
            monkeypatch,
            _LogsServer(_logs_ls({"train1": 5}), delete_result=_LOGS_BAD_RESULTS[case]),
            _LogsServer(_logs_ls({"eval1": 6})),
        )
        assert cli.main(["clean", "--logs"]) != 0
        assert sorted(host for host, _ in _log_deletes(fake)) == ["Archimedes", "Newton"]
        out = capsys.readouterr().out
        assert f"[Archimedes] {_LOGS_DELETED_WORD}" in out
        assert f"[Newton] {_LOGS_DELETED_WORD}" not in out

    def test_marker_must_be_a_whole_line(
        self, logs_project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """ログインの挨拶等が前に出ても,目印の行があれば消せたとする."""
        result = cli._SshResult(0, b"welcome\n" + CLEAN_LOGS_DELETED_MARKER.encode() + b"\n", b"")
        _logs_fake(monkeypatch, _LogsServer(_logs_ls({"train1": 5}), delete_result=result))
        assert cli.main(["clean", "--logs", "train1"]) == 0