tests/conftest.py

"""Shared pytest fixtures for ez-agent integration tests."""

from __future__ import annotations

import os
import re
import shutil
import sys
import time
import subprocess
from pathlib import Path
from typing import Generator

import pytest
import yaml

TESTS_DIR = Path(__file__).parent
sys.path.insert(0, str(TESTS_DIR))

from client import SocketClient, find_frame, find_error  # noqa: E402

REPO_ROOT = TESTS_DIR.parent
BUILD_DIR = REPO_ROOT / "build"
BIN_AGENT = BUILD_DIR / "ez-agent"
BIN_SERVICE = BUILD_DIR / "ez-agent-service"
BIN_HELLO = BUILD_DIR / "ez-agent-hello"
BIN_BUILTIN = BUILD_DIR / "ez-agent-builtin"

LEAF_ID_RE = re.compile(r"Session (l_[a-f0-9]+)")


# PyYAML follows YAML 1.1, where bare `on`/`off`/`yes`/`no`/`true`/`false` are
# booleans. The ez-agent config uses bare `on`/`off` as string values inside
# `thinking_levels` (e.g. `thinking_levels: [on, off, low, ...]`), and the Go
# daemon's yaml.v3 decoder reads them as strings when the target field is
# []string. If the test rig round-trips the user config through vanilla
# yaml.safe_load/yaml.dump, `on` becomes Python True and is dumped as `true`,
# corrupting the config the daemon then sees (the daemon would resolve the
# default thinking level to "true" and send `reasoning_effort: "true"` to the
# LLM API, which 400s).
#
# Fix: subclass the Loader and replace pyyaml's bool implicit-resolver regex
# with a narrower one that still coerces `yes`/`no`/`true`/`false` (which the
# config uses as actual booleans for fields like `has_listing`/`zdr_supported`)
# but leaves `on`/`off` (any case) as strings. Round-tripping through this
# Loader/Dumper pair preserves the semantics the Go daemon expects, and the
# daemon's yaml.v3 accepts both the bare and single-quoted forms for both
# `bool` and `[]string` fields (verified).
_NARROW_BOOL_RE = re.compile(
    r"^(?:yes|Yes|YES|no|No|NO|true|True|TRUE|false|False|FALSE)$",
    re.VERBOSE,
)


class _NoOnOffLoader(yaml.SafeLoader):
    pass


_NoOnOffLoader.yaml_implicit_resolvers = {
    ch: [
        (tag, _NARROW_BOOL_RE if tag == "tag:yaml.org,2002:bool" else pat)
        for tag, pat in tags
    ]
    for ch, tags in yaml.SafeLoader.yaml_implicit_resolvers.items()
}


class _NoOnOffDumper(yaml.SafeDumper):
    pass


_NoOnOffDumper.yaml_implicit_resolvers = _NoOnOffLoader.yaml_implicit_resolvers


def _load_yaml_config(f):
    return yaml.load(f, Loader=_NoOnOffLoader) or {}


def _dump_yaml_config(cfg, f):
    yaml.dump(cfg, f, default_flow_style=False, Dumper=_NoOnOffDumper)


def _deep_merge(base, override):
    for key, val in override.items():
        if key in base and isinstance(base[key], dict) and isinstance(val, dict):
            _deep_merge(base[key], val)
        else:
            base[key] = val
    return base


def patch_config(config_path, overrides):
    with open(config_path) as f:
        cfg = _load_yaml_config(f)
    _deep_merge(cfg, overrides)
    with open(config_path, "w") as f:
        _dump_yaml_config(cfg, f)


def _suppress_auto_title(config_path):
    with open(config_path) as f:
        cfg = _load_yaml_config(f)
    defaults = cfg.setdefault("defaults", {})
    triggers = defaults.setdefault("triggers", {})
    on_idle = triggers.setdefault("on_idle", [])
    if "~builtin.auto_title" not in on_idle:
        on_idle.append("~builtin.auto_title")
    with open(config_path, "w") as f:
        _dump_yaml_config(cfg, f)


def _copy_real_config(dest_dir, model=None):
    real_config = Path.home() / ".config" / "ez-agent" / "config.yaml"
    if not real_config.exists():
        pytest.skip("Real config.yaml not found — needed for LLM provider settings")
    dest_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    # Subscription identity locks require a parent that only the owner can write.
    # chmod also covers directories already created by a fixture.
    dest_dir.chmod(0o700)
    shutil.copy2(real_config, dest_dir / "config.yaml")
    # Authentication remains external: record only its expected absolute path.
    # Never open, copy, parse, hash, print, or probe the auth file itself.
    auth_file = (Path.home() / ".config" / "ez-agent" / "auth.yaml").absolute()
    patch_config(dest_dir / "config.yaml", {"auth_file": str(auth_file)})
    if model:
        patch_config(dest_dir / "config.yaml", {"default_model": model})
    _suppress_auto_title(dest_dir / "config.yaml")


def _write_offline_config(dest_dir):
    """Write deterministic provider-free test config without reading user auth."""
    dest_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    dest_dir.chmod(0o700)
    config_path = dest_dir / "config.yaml"
    config_path.write_text(
        f"""auth_file: {dest_dir / "auth.yaml"}
providers:
  ollama:
    type: ollama
    base_url: http://127.0.0.1:1/v1
    models:
      - name: phi4
        max_context: 32768
        thinking_levels: [low, medium, high]
      - name: llama3.2
        max_context: 32768
        thinking_levels: [low, medium, high]
default_model: ollama/phi4
"""
    )
    _suppress_auto_title(config_path)


def _provider_is_openai_family(provider: object) -> bool:
    """Classify from provider metadata, never from a user-chosen alias."""
    if not isinstance(provider, dict):
        return False
    provider_type = str(provider.get("type", "")).strip().lower()
    if provider_type in {"openai", "openai_oauth"}:
        return True
    endpoint = str(provider.get("base_url", provider.get("endpoint", ""))).strip().lower().rstrip("/")
    return endpoint in {
        "https://api.openai.com/v1",
        "https://api.openai.com:443/v1",
        "https://chatgpt.com/backend-api/codex/responses",
        "https://chatgpt.com:443/backend-api/codex/responses",
    }


def _ordinary_model_policy(config_path: Path) -> tuple[str, set[str]]:
    """Return the copied default and aliases safe for opportunistic switching."""
    with open(config_path) as f:
        cfg = _load_yaml_config(f)
    providers = cfg.get("providers") or {}
    safe = {
        alias
        for alias, provider in providers.items()
        if isinstance(alias, str)
        and isinstance(provider, dict)
        and bool(str(provider.get("type", "")).strip())
        and not _provider_is_openai_family(provider)
    }
    return str(cfg.get("default_model", "")), safe


def start_daemon(config_dir: Path | None, tmp_path: Path, extra_env: dict | None = None) -> Generator:
    """Start the agent daemon with custom config, yield info dict, stop on teardown.

    Args:
        config_dir: Path to XDG_CONFIG_HOME-compatible config directory.
            If None, XDG_CONFIG_HOME is not set (daemon uses default ~/.config).
        tmp_path: Temp directory for runtime/state dirs.
        extra_env: Additional env vars to set before starting.

    Yields:
        dict with keys: pid, proc, socket_path, runtime_dir, state_dir,
        log_path, and config_dir (if provided).
    """
    runtime_dir = tmp_path / "runtime"
    state_dir = tmp_path / "state"
    runtime_dir.mkdir(exist_ok=True)
    state_dir.mkdir(exist_ok=True)

    log_path = tmp_path / "daemon.log"

    env_vars: dict[str, str] = {
        "XDG_RUNTIME_DIR": str(runtime_dir),
        "XDG_STATE_HOME": str(state_dir),
        "EZ_AGENT_LOG_FILE": str(log_path),
        "EZ_AGENT_LOG_LEVEL": "debug",
        "EZ_AGENT_LOG_FORMAT": "json",
    }
    if config_dir is not None:
        env_vars["XDG_CONFIG_HOME"] = str(config_dir)
    if extra_env:
        env_vars.update(extra_env)

    old_env: dict[str, str | None] = {}
    for key, val in env_vars.items():
        old_env[key] = os.environ.get(key)
        os.environ[key] = val

    socket_path = runtime_dir / "ez-agent" / "ez-agent.sock"

    if not BIN_SERVICE.exists():
        for key, old_val in old_env.items():
            if old_val is not None:
                os.environ[key] = old_val
            else:
                os.environ.pop(key, None)
        pytest.skip(f"ez-agent-service not found at {BIN_SERVICE}. Run 'just build'.")

    proc = subprocess.Popen(
        [str(BIN_SERVICE)],
        cwd=str(runtime_dir),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    deadline = time.monotonic() + 10.0
    last_probe = None
    while time.monotonic() < deadline:
        if socket_path.exists():
            # Maintenance accepts connections but replies ready:false and closes.
            # Wait for a ready handshake, not merely an accepting listener.
            client = SocketClient(socket_path)
            try:
                client.connect(timeout=max(0.0, min(0.1, deadline - time.monotonic())))
                client.send({"type": "hello", "protocol": 1, "name": "fixture-readiness"})
                ack = client.recv_frame(
                    timeout=max(0.0, min(0.1, deadline - time.monotonic()))
                )
                last_probe = ack
                if ack and ack.get("type") == "hello_ack" and ack.get("ready") is True:
                    break
            except (ConnectionError, OSError) as exc:
                last_probe = repr(exc)
            finally:
                client.close()
        if proc.poll() is not None:
            proc.kill()
            proc.wait()
            stdout = proc.stdout.read().decode(errors="replace") if proc.stdout else ""
            stderr = proc.stderr.read().decode(errors="replace") if proc.stderr else ""
            for key, old_val in old_env.items():
                if old_val is not None:
                    os.environ[key] = old_val
                else:
                    os.environ.pop(key, None)
            pytest.fail(
                f"Daemon process died during startup.\nstdout: {stdout}\nstderr: {stderr}"
            )
        time.sleep(max(0.0, min(0.1, deadline - time.monotonic())))
    else:
        proc.kill()
        proc.wait()
        for key, old_val in old_env.items():
            if old_val is not None:
                os.environ[key] = old_val
            else:
                os.environ.pop(key, None)
        pytest.fail(
            f"Daemon did not become ready within 10s at {socket_path}. "
            f"Last readiness probe: {last_probe!r}"
        )

    result: dict = {
        "pid": proc.pid,
        "proc": proc,
        "socket_path": socket_path,
        "runtime_dir": runtime_dir,
        "state_dir": state_dir,
        "log_path": log_path,
    }
    if config_dir is not None:
        result["config_dir"] = config_dir
    yield result

    proc = result.get("proc", proc)
    stop_failure = None
    try:
        stop_result = subprocess.run(
            [str(BIN_AGENT), "--no-autolaunch", "--stop"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if stop_result.returncode != 0:
            stop_failure = (
                f"Daemon stop failed ({stop_result.returncode}).\n"
                f"stdout: {stop_result.stdout}\nstderr: {stop_result.stderr}"
            )
        else:
            try:
                proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                stop_failure = "Daemon acknowledged stop but did not exit within 5s"
    except subprocess.TimeoutExpired:
        stop_failure = "Daemon stop command timed out after 5s"

    result["clean_stop"] = stop_failure is None and proc.poll() is not None
    if proc.poll() is None:
        proc.kill()
        proc.wait()

    for key, old_val in old_env.items():
        if old_val is not None:
            os.environ[key] = old_val
        else:
            os.environ.pop(key, None)
    if stop_failure is not None:
        pytest.fail(stop_failure)


def restart_daemon(info: dict, timeout: float = 10.0) -> dict:
    """Cleanly restart an isolated daemon and prove the new listener is ready."""
    old_proc = info["proc"]
    stop = subprocess.run(
        [str(BIN_AGENT), "--no-autolaunch", "--stop"],
        capture_output=True,
        text=True,
        timeout=5,
    )
    assert stop.returncode == 0, (
        f"Daemon stop failed ({stop.returncode}).\nstdout: {stop.stdout}\nstderr: {stop.stderr}"
    )
    try:
        old_proc.wait(timeout=5)
    except subprocess.TimeoutExpired as exc:
        raise AssertionError("Daemon acknowledged stop but did not exit") from exc

    socket_path = info["socket_path"]
    proc = subprocess.Popen(
        [str(BIN_SERVICE)],
        cwd=str(info["runtime_dir"]),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    info["proc"] = proc
    info["pid"] = proc.pid

    deadline = time.monotonic() + timeout
    last_error: Exception | None = None
    while time.monotonic() < deadline:
        if proc.poll() is not None:
            stdout = proc.stdout.read().decode(errors="replace") if proc.stdout else ""
            stderr = proc.stderr.read().decode(errors="replace") if proc.stderr else ""
            pytest.fail(
                f"Daemon died during restart ({proc.returncode}).\n"
                f"stdout: {stdout}\nstderr: {stderr}"
            )
        if socket_path.exists():
            try:
                with SocketClient(socket_path):
                    return info
            except (ConnectionError, OSError) as exc:
                last_error = exc
        time.sleep(0.05)

    proc.kill()
    proc.wait()
    pytest.fail(f"Daemon restart listener was not ready at {socket_path}: {last_error}")


def read_frame(proc, timeout=5.0):
    """Read one JSONL frame, retaining batched frames and incomplete lines."""
    import json as _json
    import select as _select

    # Buffered readline can hide later frames from select and can block past
    # the deadline on a partial line. Read the fd directly and own the buffer.
    pending = getattr(proc, "_jsonl_stdout_pending", None)
    if pending is None:
        pending = proc._jsonl_stdout_pending = bytearray()
    deadline = time.monotonic() + timeout
    while True:
        newline = pending.find(b"\n")
        if newline >= 0:
            line = bytes(pending[:newline]).strip()
            del pending[:newline + 1]
            if not line:
                continue
            try:
                return _json.loads(line)
            except _json.JSONDecodeError:
                continue
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return None
        try:
            ready, _, _ = _select.select([proc.stdout], [], [], remaining)
            if not ready:
                return None
            chunk = os.read(proc.stdout.fileno(), 65536)
        except (OSError, ValueError):
            return None
        if not chunk:
            # Preserve readline's support for a final line without a newline.
            line = bytes(pending).strip()
            pending.clear()
            if line:
                try:
                    return _json.loads(line)
                except _json.JSONDecodeError:
                    pass
            return None
        pending.extend(chunk)


def send_frame(proc, msg: dict):
    """Send a JSONL frame to a subprocess stdin."""
    import json as _json

    data = _json.dumps(msg) + "\n"
    proc.stdin.write(data.encode())
    proc.stdin.flush()


def pytest_addoption(parser):
    parser.addoption("--live-claude", action="store_true", default=False,
                     help="Run bounded real two-daemon Claude subscription acceptance")
    parser.addoption("--live-muse", action="store_true", default=False,
                     help="Run real local and credential-free AF_UNIX Muse Spark acceptance")
    parser.addoption("--muse-command", default="/home/developer/.local/bin/muse",
                     help="Absolute installed official Muse launcher for live acceptance")
    parser.addoption("--muse-native-config-home", default=str(Path.home() / ".config"),
                     help="Native Muse config home with existing login; never the EzAgent runtime")
    parser.addoption(
        "--no-llm",
        action="store_true",
        default=False,
        help="Skip tests that require an LLM provider",
    )
    parser.addoption(
        "--live-openai",
        action="store_true",
        default=False,
        help="Run opt-in live acceptance of the public OpenAI Responses runtime",
    )
    parser.addoption(
        "--live-openai-config-home",
        default=None,
        help="Source XDG config home; defaults to inherited XDG_CONFIG_HOME or ~/.config",
    )
    for route in ("subscription", "api", "http"):
        parser.addoption(
            f"--live-openai-{route}-ref",
            action="append",
            default=[],
            help=f"Configured {route} provider/model ref; repeat for each model",
        )
    parser.addoption(
        "--live-openai-subscription-provider",
        default="openai",
        help="Fallback subscription alias or ref for gpt-6-luna; empty disables fallback",
    )
    parser.addoption(
        "--live-openai-api-provider",
        default=None,
        help="Optional fallback API-key alias or ref for gpt-6-luna",
    )
    parser.addoption(
        "--model",
        action="store",
        default=None,
        help="Override the model (e.g. ollama/llama3.2)",
    )


def pytest_configure(config):
    config.addinivalue_line("markers", "llm: marks tests that require an LLM provider")
    config.addinivalue_line("markers", "quick: provider-free tests run by test-quick")
    config.addinivalue_line("markers", "full_offline: provider-free tests reserved for test-full-offline")
    config.addinivalue_line("markers", "live_openai: opt-in live OpenAI route acceptance")
    config.addinivalue_line("markers", "live_muse: opt-in real local and relayed Muse Spark acceptance")
    config.addinivalue_line("markers", "live_claude: opt-in real two-daemon Claude acceptance")


def pytest_collection_modifyitems(config, items):
    conflicts = [
        item.nodeid
        for item in items
        if "llm" in item.keywords and ({"quick", "full_offline"} & set(item.keywords))
    ]
    if conflicts:
        joined = "\n  ".join(conflicts)
        raise pytest.UsageError(f"LLM tests cannot be marked quick or full_offline:\n  {joined}")
    if not config.getoption("--live-openai"):
        skip_live = pytest.mark.skip(reason="requires explicit --live-openai")
        for item in items:
            if "live_openai" in item.keywords:
                item.add_marker(skip_live)
    if not config.getoption("--live-muse"):
        skip_live = pytest.mark.skip(reason="requires explicit --live-muse")
        for item in items:
            if "live_muse" in item.keywords:
                item.add_marker(skip_live)
    if not config.getoption("--live-claude"):
        skip_live = pytest.mark.skip(reason="requires explicit --live-claude")
        for item in items:
            if "live_claude" in item.keywords:
                item.add_marker(skip_live)
    if config.getoption("--no-llm"):
        skip_llm = pytest.mark.skip(reason="--no-llm: skipping LLM tests")
        for item in items:
            if "llm" in item.keywords and "no_llm" not in item.keywords:
                item.add_marker(skip_llm)


@pytest.fixture(scope="session")
def model_override(request):
    """Return model override from CLI --model option, or None to use default."""
    return request.config.getoption("--model")


@pytest.fixture
def tmp_env(tmp_path):
    """Create isolated XDG runtime/state directories for a test."""
    runtime_dir = tmp_path / "runtime"
    state_dir = tmp_path / "state"
    runtime_dir.mkdir(exist_ok=True)
    state_dir.mkdir(exist_ok=True)

    old_runtime = os.environ.get("XDG_RUNTIME_DIR")
    old_state = os.environ.get("XDG_STATE_HOME")

    os.environ["XDG_RUNTIME_DIR"] = str(runtime_dir)
    os.environ["XDG_STATE_HOME"] = str(state_dir)

    yield {
        "runtime_dir": runtime_dir,
        "state_dir": state_dir,
        "socket_path": runtime_dir / "ez-agent" / "ez-agent.sock",
    }

    if old_runtime is not None:
        os.environ["XDG_RUNTIME_DIR"] = old_runtime
    else:
        os.environ.pop("XDG_RUNTIME_DIR", None)
    if old_state is not None:
        os.environ["XDG_STATE_HOME"] = old_state
    else:
        os.environ.pop("XDG_STATE_HOME", None)


@pytest.fixture
def daemon(tmp_path, model_override, request):
    """Start the agent daemon with default config, yield info dict, stop on teardown."""
    config_dir = tmp_path / "config"
    ez_config_dir = config_dir / "ez-agent"
    if "llm" in request.node.keywords and "quick" not in request.node.keywords and "full_offline" not in request.node.keywords:
        _copy_real_config(ez_config_dir, model=model_override)
    else:
        _write_offline_config(ez_config_dir)
    yield from start_daemon(config_dir=config_dir, tmp_path=tmp_path)


def _live_openai_cases(config):
    """Collect explicit refs independently; provider aliases are only fallbacks."""
    cases = []
    for route in ("subscription", "api", "http"):
        refs = list(config.getoption(f"--live-openai-{route}-ref"))
        if not refs and route != "http":
            provider = config.getoption(f"--live-openai-{route}-provider")
            if provider:
                refs = [provider if "/" in provider else f"{provider}/gpt-6-luna"]
        for index, ref in enumerate(refs):
            cases.append(pytest.param(
                (ref, "http" if route == "http" else "websocket"),
                id=f"{route}-{index + 1}",
            ))
    return cases


def pytest_generate_tests(metafunc):
    if "live_openai_case" in metafunc.fixturenames:
        cases = _live_openai_cases(metafunc.config)
        metafunc.parametrize("live_openai_case", cases)


def _copy_live_openai_config(source_home: Path, config_home: Path):
    """Copy only non-secret config; leave authentication to the protected loader."""
    source_dir = source_home.expanduser().absolute() / "ez-agent"
    source_config = source_dir / "config.yaml"
    if not source_config.is_file():
        pytest.skip("external prerequisite: source ez-agent/config.yaml required")
    config_home.mkdir(mode=0o700, parents=True, exist_ok=True)
    config_home.chmod(0o700)
    dest_dir = config_home / "ez-agent"
    dest_dir.mkdir(mode=0o700, exist_ok=True)
    dest_dir.chmod(0o700)
    dest_config = dest_dir / "config.yaml"
    shutil.copy2(source_config, dest_config)
    with dest_config.open() as stream:
        cfg = _load_yaml_config(stream)
    supplied = cfg.get("auth_file")
    if supplied:
        supplied = str(supplied).replace("%USER_CONFIG_DIR%", str(source_dir))
        auth_path = Path(os.path.expandvars(supplied)).expanduser()
    else:
        auth_path = source_dir / "auth.yaml"
    if not auth_path.is_absolute():
        auth_path = source_dir / auth_path
    cfg["auth_file"] = str(auth_path.absolute())
    with dest_config.open("w") as stream:
        _dump_yaml_config(cfg, stream)


@pytest.fixture
def live_openai_daemon(tmp_path, request):
    """Isolate all XDG paths while the service loads external auth normally."""
    if not request.config.getoption("--live-openai"):
        pytest.skip("requires explicit --live-openai")
    source_home = Path(
        request.config.getoption("--live-openai-config-home")
        or os.environ.get("XDG_CONFIG_HOME")
        or Path.home() / ".config"
    ).expanduser().absolute()
    config_home = tmp_path / "config"
    _copy_live_openai_config(source_home, config_home)
    yield from start_daemon(config_dir=config_home, tmp_path=tmp_path)


@pytest.fixture
def ordinary_model_policy(daemon):
    """Copied non-secret config policy for tests that select alternate models."""
    return _ordinary_model_policy(daemon["config_dir"] / "ez-agent" / "config.yaml")


@pytest.fixture
def client(daemon):
    """Create a connected SocketClient to the daemon."""
    c = SocketClient(daemon["socket_path"])
    c.connect()
    yield c
    c.close()


@pytest.fixture
def hello_client(client):
    """Create a connected and handshaked SocketClient."""
    ack = client.hello(name="pytest")
    assert ack is not None, "No hello_ack received"
    assert ack.get("type") == "hello_ack", f"Expected hello_ack, got {ack}"
    return client


@pytest.fixture
def db_path(daemon):
    """Return the path to the SQLite database."""
    p = daemon["state_dir"] / "ez-agent" / "ez-agent.db"
    assert p.exists(), f"Database not found at {p}"
    return p


def extract_leaf_id(output: str) -> str | None:
    """Extract leaf ID from CLI output like 'Session l_abc123'."""
    m = LEAF_ID_RE.search(output)
    return m.group(1) if m else None


def get_leaf_turn_ids(db, leaf_id):
    """Walk the parent chain from a leaf's tip to return ordered turn IDs."""
    cur = db.execute("SELECT turn_id FROM leaves WHERE id = ?", (leaf_id,))
    row = cur.fetchone()
    if not row or not row[0]:
        return []
    turn_ids = []
    current = row[0]
    while current:
        cur = db.execute("SELECT parent_id, kind, other_meta FROM turns WHERE id = ?", (current,))
        row = cur.fetchone()
        if not row:
            break
        parent_id, kind, other_meta = row
        turn_ids.insert(0, current)
        if kind == "virtual_root":
            # Virtual root is a walk boundary — stop here
            break
        current = parent_id
    return turn_ids


DAEMON_LOG_TAIL = 80


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    if report.when == "call" and report.failed:
        daemon_fixture = getattr(item, "funcargs", {}).get("daemon")
        if daemon_fixture and "log_path" in daemon_fixture:
            log_path = daemon_fixture["log_path"]
            if log_path.exists():
                lines = log_path.read_text(errors="replace").splitlines()
                tail = lines[-DAEMON_LOG_TAIL:] if len(lines) > DAEMON_LOG_TAIL else lines
                report.sections.append(
                    ("Daemon Log (last {} lines)".format(len(tail)), "\n".join(tail))
                )


@pytest.fixture
def run_agent(daemon):
    """Run the ez-agent CLI and return (exit_code, output, leaf_id)."""
    def _run(*args: str) -> tuple[int, str, str | None]:
        cmd = [str(BIN_AGENT), "--no-autolaunch"] + list(args)
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
        leaf_id = extract_leaf_id(result.stdout + result.stderr)
        return result.returncode, result.stdout + result.stderr, leaf_id

    return _run