Newer
Older
TongueSegModel / tests / cli / test_remote.py
"""tsm-remote CLI のテスト(SPEC_03).ssh はすべてモックし,実サーバに接続しない.

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

TIASJudgeModel の tests/cli/test_remote.py の移植.本リポジトリの configs/remote.yaml と同じく
設定に address・user を書かず,ssh の接続先はサーバ名(~/.ssh/config の Host 名)になる.
回収ホワイトリストは本リポジトリの SPEC_01 に合わせた.
"""

from __future__ import annotations

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

import pytest

import tongue_seg_model.cli.remote as cli
from tongue_seg_model.remote.commands import (
    EXIT_NOT_FOUND,
    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,
)
from tongue_seg_model.remote.gpu import GpuState

# 設定に address を書かないため,ssh の接続先はサーバ名になる
NEWTON_ADDR = "Newton"
ARCHIMEDES_ADDR = "Archimedes"
RUN_ID = "20261119-120000_resunet_abc1234"

CONFIG_YAML = """\
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/TongueSegModel
    uv: ~/.local/bin/uv
    data_ready: true
  - name: Archimedes
    priority: 2
    remote_dir: ~/work/TongueSegModel
    uv: ~/.local/bin/uv
    data_ready: true
"""


def _probe_stdout(gpus: list[tuple[int, int, int]], apps: list[str] | None = None) -> bytes:
    """probe の出力(gpus は (index, 使用中メモリ, 使用率) のリスト.観測サンプルも同じ値)."""
    lines = [f"{PROBE_USER_PREFIX}hasegawa", 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` が手元で求める TSM_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 は一切起動させない)."""
    root = tmp_path / "proj"
    (root / "src" / "tongue_seg_model").mkdir(parents=True)
    (root / "src" / "tongue_seg_model" / "__init__.py").write_bytes(b"")
    (root / "pyproject.toml").write_bytes(b"[project]\nname = 'x'\n")
    (root / "configs").mkdir()
    (root / "configs" / "remote.yaml").write_text(CONFIG_YAML, encoding="utf-8")
    monkeypatch.chdir(root)
    for var in ("TSM_REMOTE_JUMP", "TSM_REMOTE_ALLOW_SELF"):
        monkeypatch.delenv(var, raising=False)
    monkeypatch.setenv("TSM_REMOTE_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("TSM_REMOTE_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("TSM_REMOTE_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/ResUNet.onnx",
]
ALLOWED = LISTING_NAMES[:6]
CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/ResUNet.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:
        for rel in [
            "data/synthetic/manifest.csv",
            "runs/x/metrics.json",
            ".claude/a.md",
            "legacy/source/main.py",
            "src/tongue_seg_model/models/best.pth",
            "configs/ResUNet.ONNX",
            ".env",
            "src/tongue_seg_model/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
        assert "configs/remote.yaml" in out
        assert "data/synthetic" not in out
        assert "runs/x" not in out
        assert ".claude" not in out
        assert "legacy" not in out
        assert "best.pth" not in out
        assert "ResUNet.ONNX" not in out
        assert ".env" not in out
        # data/ の除外は直下だけ(パッケージの data/ は送る)
        assert "src/tongue_seg_model/data/bundle.py" in out
        assert fake.calls == []


# ---------------------------------------------------------------------------
# run: TSM_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


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"]["TSM_GIT_COMMIT"] == "abc1234"
        # ジョブのスクリプトに実際に export される
        assert "export TSM_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/tongue_seg_model/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"]["TSM_GIT_COMMIT"] == "abc1234-dirty"
        assert "export TSM_GIT_COMMIT=abc1234-dirty" in capsys.readouterr().out

    @pytest.mark.parametrize("failure", ["missing", "not_repo", "status_fails"])
    def test_git_unavailable_does_not_set_variable(
        self,
        project: Path,
        monkeypatch: pytest.MonkeyPatch,
        fake_git: FakeGit,
        capsys: pytest.CaptureFixture[str],
        failure: str,
    ) -> None:
        if failure == "missing":
            fake_git.missing = True
        elif failure == "not_repo":
            fake_git.head = None
        else:
            fake_git.status = None
        _free_everywhere(monkeypatch)
        captured = _spy_job_script(monkeypatch)
        # git が使えなくてもジョブは起動できる(ジョブ側は nogit になる)
        assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0
        assert "TSM_GIT_COMMIT" not in captured[0]["env"]
        assert "TSM_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", "TSM_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 / "configs" / "remote.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", "--", "tsm-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["TSM_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"] == ""


# ---------------------------------------------------------------------------
# 本リポジトリで足した確認
# ---------------------------------------------------------------------------

# シェルが特別に解釈する文字を含むコマンド引数
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 = ["tsm-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_without_user(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        fake = _free_everywhere(monkeypatch)
        assert cli.main(["run", "--name", "train1", "--no-push", "--", "tsm-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", "TIASDATA_BUNDLES=data/synthetic"]
        assert cli.main([*args, "--", "tsm-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 TSM_GIT_COMMIT=abc1234",
            "export TIASDATA_BUNDLES=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",
            "TSM_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", "--", "tsm-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"tsm-remote: 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 == []

    def test_make_run_id_is_accepted_by_pull(
        self, project: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """`tsm-train` の実験 ID(-dirty 付き)で pull できる."""
        from datetime import datetime

        from tongue_seg_model.training.run_artifacts import make_run_id

        run_id = make_run_id(datetime(2026, 11, 19, 1, 2, 3), "synthetic-gpu", "abc1234-dirty")
        listing = f"f {run_id}/config.yaml\0f {run_id}/split.json\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]) == 0
        assert receive.requested == [f"{run_id}/config.yaml"]
        assert (project / "runs" / run_id / "config.yaml").is_file()
        assert not (project / "runs" / run_id / "split.json").exists()


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)


# ---------------------------------------------------------------------------
# 安全策の補強: 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", "TIASDATA_BUNDLES=\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"