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 を空文字で渡す

TIASJudgeModel の tests/cli/test_remote.py の移植.設定(labremote.yaml)にアドレス・ユーザー名を
書くキーは無く,ssh の接続先はサーバ名(~/.ssh/config の Host 名)になる.
回収ホワイトリストはTongueSegModel の 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 importlib.metadata import entry_points
from pathlib import Path

import pytest
import yaml

import labremote.cli as cli
from labremote.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 labremote.gpu import GpuState

# 設定にアドレスを書くキーは無いため,ssh の接続先はサーバ名になる
NEWTON_ADDR = "Newton"
ARCHIMEDES_ADDR = "Archimedes"
RUN_ID = "20261119-120000_resunet_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/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}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/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:
        # data・legacy・重みは設定の push に書いたときに送られない(SPEC_02「`push`」)
        _write_config_data(
            project,
            lambda data: data.update(
                push={"exclude_root": ["data", "legacy"], "exclude_suffixes": [".pth", ".onnx"]}
            ),
        )
        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
        # 設定ファイルはサーバで使わないため送らない(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 "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: 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


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/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"]["LABREMOTE_GIT_COMMIT"] == "abc1234-dirty"
        assert "export LABREMOTE_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 "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", "--", "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["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"] == ""


# ---------------------------------------------------------------------------
# TongueSegModel で足した確認
# ---------------------------------------------------------------------------

# シェルが特別に解釈する文字を含むコマンド引数
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_only(
        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 LABREMOTE_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",
            "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", "--", "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"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 == []

    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

        make_run_id = pytest.importorskip("tongue_seg_model.training.run_artifacts").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"


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

# 今のステップで動くサブコマンド(ls・clean は後のステップで足す)
SUBCOMMANDS = ["gpus", "status", "push", "run", "logs", "kill", "pull"]
# 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_tsm_remote_jump_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_tsm_remote_ssh_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_tsm_remote_allow_self_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 == []