tests/suites/test_agenthub_process.py

"""Shipped AgentHub journey; the standard fixture owns the isolated daemon."""

import os
import subprocess
import sys

import pytest

from conftest import BUILD_DIR, REPO_ROOT

pytestmark = pytest.mark.full_offline


@pytest.mark.skipif(sys.platform != "linux", reason="real client PTY driver is Linux-owned")
def test_agenthub_shipped_journey(daemon):
    for name in ("ez-agent", "ez-agent-hub", "ez-agent-service"):
        assert (BUILD_DIR / name).is_file(), "Run just test-agenthub-e2e to build the binaries"
    env = os.environ.copy()  # daemon fixture has installed all three private XDG homes
    env["EZ_AGENT_E2E_BUILD"] = str(BUILD_DIR)
    env["EZ_AGENT_E2E_SOCKET"] = str(daemon["socket_path"])
    result = subprocess.run(
        ["go", "test", "-count=1", "-timeout=150s", "-tags=agenthub_e2e",
         "./internal/frontend", "-run", "^TestAgentHubShippedJourney$", "-v"],
        cwd=REPO_ROOT, env=env, capture_output=True, text=True, timeout=170,
    )
    # The Go driver never emits dashboard/client transcripts or invitation input.
    assert result.returncode == 0, result.stdout + result.stderr


@pytest.mark.skipif(sys.platform != "linux", reason="private Hub socket is Linux-owned")
def test_agenthub_typed_migration_process():
    """Shipped Hub child; the Go driver isolates all three XDG homes."""
    assert (BUILD_DIR / "ez-agent-hub").is_file(), "Build shipped binaries first"
    env = os.environ.copy()
    env["EZ_AGENT_E2E_BUILD"] = str(BUILD_DIR)
    result = subprocess.run(
        ["go", "test", "-count=1", "-timeout=45s", "-tags=agenthub_e2e",
         "./internal/frontend", "-run", "^TestAgentHubTypedMigrationProcess$", "-v"],
        cwd=REPO_ROOT, env=env, capture_output=True, text=True, timeout=60,
    )
    assert result.returncode == 0, result.stdout + result.stderr


@pytest.mark.skipif(sys.platform != "linux", reason="Hub public listener is Linux-owned")
def test_agenthub_two_hub_pairing_shipped():
    """Two empty shipped Hubs; only the dashboard supplies trust and JOIN WORDS."""
    import re
    import socket
    import tempfile
    import time
    import shlex
    from pathlib import Path
    import json

    def visible(stage, inviting_phase, joining_phase):
        if os.getenv("AGENTHUB_TMUX_ACCEPTANCE") == "1":
            print(f"{stage}: inviting={inviting_phase}, joining={joining_phase}", flush=True)

    def visible_dashboards(stage, inviting_env, joining_env):
        if os.getenv("AGENTHUB_TMUX_ACCEPTANCE") != "1":
            return
        evidence = os.getenv("AGENTHUB_TMUX_EVIDENCE")
        if not evidence:
            return
        session = os.getenv("AGENTHUB_TMUX_SESSION")
        if not session:
            pytest.fail("AGENTHUB_TMUX_SESSION must name an owned test session", pytrace=False)
        path = Path(evidence)
        for side, env, pane in (("inviting", inviting_env, f"{session}:1.0"),
                                ("joining", joining_env, f"{session}:2.0")):
            # Status is an actual shipped dashboard read, never a card display.
            # Redact even the explanatory mention of the secret's name.
            screen = re.sub(r"JOIN WORDS[^\n]*", "card secret cannot be repeated.", status(env))
            snapshot = path / f"{stage}-{side}-dashboard.txt"
            snapshot.write_text(screen)
            subprocess.run(["tmux", "send-keys", "-t", pane,
                            "clear; cat " + shlex.quote(str(snapshot)), "Enter"], check=True)
            time.sleep(0.1)
            capture = subprocess.run(["tmux", "capture-pane", "-p", "-t", pane],
                                     check=True, text=True, capture_output=True)
            (path / f"{stage}-{side}-capture.txt").write_text(
                re.sub(r"JOIN WORDS[^\n]*", "card secret cannot be repeated.", capture.stdout))

    run_root = tempfile.TemporaryDirectory(prefix="agenthub-process-")
    tmp_path = Path(run_root.name)
    hub = BUILD_DIR / "ez-agent-hub"
    assert hub.is_file(), "Run just test-agenthub-e2e to build the binaries"
    processes = []

    def home(name):
        base = tmp_path / name
        env = os.environ.copy()
        for key, part in (("XDG_CONFIG_HOME", "config"),
                          ("XDG_STATE_HOME", "state"),
                          ("XDG_RUNTIME_DIR", "run")):
            path = base / part
            path.mkdir(parents=True, mode=0o700)
            env[key] = str(path)
        return base, env

    dashboard_calls = 0

    def dashboard(env, command, expect_failure=False):
        nonlocal dashboard_calls
        deadline = time.monotonic() + 20
        authority = None
        for attempt in range(3):
            dashboard_calls += 1
            result = subprocess.run([str(hub), "--config"], input=command + "\nquit\n",
                                    text=True, capture_output=True, env=env,
                                    timeout=max(0.01, deadline - time.monotonic()))
            # Never include raw stdout/stderr in an assertion: the card is secret.
            failed = result.returncode != 0 or bool(result.stderr)
            current = re.search(r"Authority fingerprint: ([0-9a-f]{64})", result.stdout)
            if authority is not None and (current is None or current.group(1) != authority):
                pytest.fail("dashboard authority changed between decisions", pytrace=False)
            if failed == expect_failure:
                if expect_failure:
                    assert "conflicted" not in (result.stdout + result.stderr).lower()
                    assert "compromised" not in (result.stdout + result.stderr).lower()
                return result.stdout
            # Simulate a fresh operator decision only for definite local
            # conflicts, never Add Hub/TLS, uncertainty, or an unjoined call.
            conflict = "operation failed: conflict\n" in result.stderr
            unsent = "reviewed revision or authority changed; command not sent" in result.stderr
            local = command.split()[0] in ("invite", "approve", "cancel", "remove")
            if (not expect_failure and attempt < 2 and result.returncode == 0 and
                    current is not None and local and (conflict or unsent) and
                    "remote retirement was not acknowledged" not in result.stderr and
                    time.monotonic() < deadline):
                authority = current.group(1)
                continue
            operation = " ".join(command.split()[:2])
            pytest.fail(f"Hub dashboard operation {operation!r} at step {dashboard_calls}: failed={failed}, expected_failure={expect_failure} (transcript withheld)", pytrace=False)

    def field(text, pattern):
        match = re.search(pattern, text)
        if match is None:
            pytest.fail(f"expected dashboard field {pattern!r} missing at step {dashboard_calls} (transcript withheld)", pytrace=False)
        return match.group(1)

    def status(env):
        return dashboard(env, "status")

    def start(base, env, address):
        config = base / "config/ez-agent/hub/config.yaml"
        config.parent.mkdir(parents=True, exist_ok=True)
        config.write_text(f"version: 1\ninbound:\n  enabled: true\n  listen: {address}\n  address: {address}\n")
        process = subprocess.Popen([str(hub)], env=env, stdout=subprocess.DEVNULL,
                                   stderr=subprocess.DEVNULL)
        processes.append(process)
        evidence = os.getenv("AGENTHUB_TMUX_EVIDENCE")
        if evidence:
            # PIDs and roots are operational evidence, not pairing secrets.
            with open(Path(evidence) / "exact-stop-commands.txt", "a", encoding="utf-8") as record:
                record.write(f"env XDG_CONFIG_HOME={env['XDG_CONFIG_HOME']} "
                             f"XDG_STATE_HOME={env['XDG_STATE_HOME']} "
                             f"XDG_RUNTIME_DIR={env['XDG_RUNTIME_DIR']} "
                             f"/usr/bin/kill -TERM {process.pid}\n")
        control = base / "run/ez-agent/hub/control.sock"
        for _ in range(300):
            if process.poll() is not None:
                break
            if control.exists():
                try:
                    # The shipped client must complete hello and typed status.
                    # A successful connect alone did not prove API readiness.
                    result = subprocess.run(
                        [str(hub), "--config"], input="status\nquit\n",
                        text=True, capture_output=True, env=env, timeout=1,
                    )
                    if (result.returncode == 0 and not result.stderr and
                            "Authority fingerprint:" in result.stdout):
                        return process
                except (OSError, subprocess.TimeoutExpired):
                    pass
            time.sleep(0.05)
        pytest.fail("Hub listener failed to start (logs withheld)")

    def stop(process):
        process.terminate()  # exact isolated PID; the Hub has no --stop command
        try:
            process.wait(timeout=8)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait(timeout=5)
        processes.remove(process)

    def wait(env, pattern):
        for _ in range(100):
            output = status(env)
            if re.search(pattern, output):
                return output
            time.sleep(0.1)
        pytest.fail("pairing phase not reached (transcripts withheld)")

    def open_pairing_view(env):
        view = subprocess.Popen(
            [str(hub), "--config"], env=env, stdin=subprocess.PIPE,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)
        processes.append(view)
        view.stdin.write("pairing open\n")
        view.stdin.flush()
        return view

    def close_pairing_view(view):
        view.stdin.write("pairing close\nquit\n")
        view.stdin.flush()
        view.wait(timeout=8)
        assert view.returncode == 0
        processes.remove(view)

    def accepted_with_view(env):
        view = open_pairing_view(env)
        try:
            return wait(env, r"Hub pairing accepted mode=direct")
        finally:
            close_pairing_view(view)

    try:
        inviting, a = home("inviting")
        joining, b = home("joining")
        dashboard(a, "bootstrap")
        dashboard(b, "bootstrap")
        with socket.socket() as sock:
            sock.bind(("127.0.0.1", 0))
            address = f"127.0.0.1:{sock.getsockname()[1]}"
        target = start(inviting, a, address)
        with socket.socket() as sock:
            sock.bind(("127.0.0.1", 0))
            joining_address = f"127.0.0.1:{sock.getsockname()[1]}"
        joining_process = start(joining, b, joining_address)
        joining_status = status(b)
        join_fingerprint = field(joining_status, r"Authority fingerprint: ([0-9a-f]{64})")
        target_status = status(a)
        target_fingerprint = field(target_status, r"Authority fingerprint: ([0-9a-f]{64})")
        visible("two empty Hubs bootstrapped; offline authority checks displayed", "empty", "empty")
        visible_dashboards("01-empty", a, b)
        card = dashboard(a, f"invite pairing direct {join_fingerprint}")
        words = field(card, r"JOIN WORDS \(displayed once\): ([^\n]+)")
        assert "JOIN WORDS (displayed once)" not in status(a)
        visible("locked one-time card delivered privately (capture paused)", "unclaimed", "empty")
        visible_dashboards("02-card", a, b)
        try:
            dashboard(b, f"add hub direct {address} {target_fingerprint} {words}")
        finally:
            words = None
            card = None
        # Add Hub may durably return Prepared if the initial carrier ends
        # before Context. Only an open shipped view may recover that exact Q;
        # passive status polling must not be expected to advance it.
        pairing_screen = open_pairing_view(b)
        accepted = wait(b, r"Hub pairing accepted mode=direct")
        remote = field(accepted, r"Hub pairing accepted mode=direct request=[0-9a-f]{32} remote=([0-9a-f]{64})")
        request = field(accepted, r"Hub pairing accepted mode=direct request=([0-9a-f]{32})")
        assert "Peers: 0" in accepted
        assert "Waiting for joining approval" in wait(a, r"Hub pairing accepted mode=direct")
        visible("identities confirmed; no peer privilege", "accepted", "accepted")
        visible_dashboards("03-accepted", a, b)
        # A fresh dashboard observes Context before the local decision. The
        # open screen remains the explicit owner of remote delivery/recovery.
        dashboard(b, f"approve joining {remote} {request}")
        pairing_screen.stdin.write("pairing open\n")
        pairing_screen.stdin.flush()
        wait(a, r"Hub pairing remote-approved mode=direct")
        visible("joining approval; no peer privilege", "remote-approved", "local-approved")
        visible_dashboards("04-joining-approved", a, b)
        stop(target)
        target = start(inviting, a, address)
        assert "remote-approved" in status(a)
        # Restart also clamps runtime security time to the reserved horizon.
        # Reopen the other isolated owner before the later fresh ceremonies,
        # rather than expecting its still-running wall clock to accept a target
        # claim from that future restart floor. Keep the exact pending Q.
        close_pairing_view(pairing_screen)
        stop(joining_process)
        joining_process = start(joining, b, joining_address)
        assert f"Hub pairing local-approved mode=direct request={request}" in status(b)
        pairing_screen = open_pairing_view(b)
        visible("inviting Hub restarted; pending approval recovered", "remote-approved", "local-approved")
        visible_dashboards("05-restarted", a, b)
        dashboard(a, f"approve inviting {join_fingerprint} {request}")
        active_a = wait(a, r"Hub pairing active mode=direct")
        active_b = wait(b, r"Hub pairing active mode=direct")
        assert "Peers: 1" in active_a and "Peers: 1" in active_b
        # Exact signed-byte assertions run below after the journey's ordinary
        # shutdown. Private dashboard reads intentionally redact those bytes;
        # the original state.yaml checkpoint is not the current live state.
        close_pairing_view(pairing_screen)
        visible("open screen retrieved Completion; bilateral Peer active", "active", "active")
        visible_dashboards("06-active", a, b)
        card = dashboard(a, f"invite pairing direct {join_fingerprint}")
        row = field(status(a), r"Pairing card unclaimed row=([0-9a-f]{32})")
        card = None
        dashboard(a, f"cancel card {row}")
        assert f"Pairing card unclaimed row={row}" not in status(a)
        visible("unused card cancelled", "active", "active")
        visible_dashboards("07-card-cancelled", a, b)
        dashboard(a, f"remove peer {join_fingerprint} {request}")
        removed_a = status(a)
        assert "Hub pairing removed" in removed_a and "Peers: 0" in removed_a
        visible("peer removed", "removed", "active until independently removed")
        visible_dashboards("08-removed", a, b)
        dashboard(b, f"remove peer {target_fingerprint} {request}")
        removed_b = status(b)
        assert "Hub pairing removed" in removed_b and "Peers: 0" in removed_b
        # A second independent card and request exercise explicit pairing
        # cancellation, not just unclaimed-card cancellation.
        card = dashboard(a, f"invite pairing direct {join_fingerprint}")
        words = field(card, r"JOIN WORDS \(displayed once\): ([^\n]+)")
        dashboard(b, f"add hub direct {address} {target_fingerprint} {words}")
        second = accepted_with_view(b)
        second_request = field(second, r"Hub pairing accepted mode=direct request=([0-9a-f]{32})")
        assert second_request != request
        words = None
        card = None
        dashboard(b, f"cancel pairing {remote} {second_request}")
        assert f"Hub pairing cancelled mode=direct request={second_request}" in status(b)
        assert f"Hub pairing cancelled mode=direct request={second_request}" in wait(
            a, rf"Hub pairing cancelled mode=direct request={second_request}")
        visible("separate pending pairing cancelled", "cancelled", "cancelled")
        visible_dashboards("09-cancelled", a, b)
        # Two shipped Add Hub operations preserve the same card but generate
        # different requests. No custom protocol caller or state injection.
        card = dashboard(a, f"invite pairing direct {join_fingerprint}")
        words = field(card, r"JOIN WORDS \(displayed once\): ([^\n]+)")
        dashboard(b, f"add hub direct {address} {target_fingerprint} {words}")
        accepted_with_view(b)
        third_accepted = wait(a, r"Hub pairing accepted mode=direct")
        third_request = field(third_accepted, r"Hub pairing accepted mode=direct request=([0-9a-f]{32})")
        # Release the initial decision connection through an ordinary restart.
        # The first durable request survives; the next Add Hub creates another.
        stop(joining_process)
        joining_process = start(joining, b, joining_address)
        prepared = dashboard(b, f"add hub direct {address} {target_fingerprint} {words}")
        prepared_request = field(
            prepared,
            r"Pairing request ([0-9a-f]{32}) for the displayed Hub saved for recovery at revision [0-9]+\. "
            r"Signed Context is not yet durable; no approval is available\.",
        )
        assert prepared_request not in (request, second_request, third_request)
        if (field(prepared, r"Independently entered fingerprint \(matched\): ([0-9a-f]{64})") != target_fingerprint or
                field(prepared, r"Candidate KEY CHECK \(diagnostic only\): ([^\n]+)") != field(
                    target_status, r"Authority KEY CHECK: ([^\n]+)") or
                field(prepared, r"Candidate check byte \(diagnostic only\): ([0-9a-f]{2})") != field(
                    target_status, r"Authority check byte: ([0-9a-f]{2})")):
            pytest.fail("Prepared recovery displayed incorrect identity checks (transcript withheld)", pytrace=False)
        if f"approve joining {target_fingerprint} {prepared_request}" in prepared:
            pytest.fail("Prepared recovery offered premature approval (transcript withheld)", pytrace=False)
        if words in prepared:
            pytest.fail("Prepared recovery disclosed JOIN words (transcript withheld)", pytrace=False)
        words = None
        card = None
        conflicted = wait(a, rf"Hub pairing conflicted mode=direct request={third_request} remote={join_fingerprint}")
        joining_prepared = status(b)
        assert f"Hub pairing prepared mode=direct request={prepared_request} remote={target_fingerprint}" in joining_prepared
        assert "Hub pairing conflicted" not in joining_prepared
        assert "Peers: 0" in conflicted and "Peers: 0" in joining_prepared
        visible("changed-request conflict stays local to inviter", "conflicted", "prepared for recovery")
        # One normal joined shutdown, not a healing operation per assertion.
        # The Go verifier takes the real lifetime locks and uses production
        # selector/WAL validation. No private state or signed bytes leave it.
        for process in list(reversed(processes)):
            stop(process)
        inspect_env = b.copy()  # retain this fixture's isolated three XDG homes
        inspect_env["EZ_AGENT_E2E_PAIRING_STATE"] = json.dumps({
            "inviting_root": str(inviting / "state/ez-agent/hub"),
            "joining_root": str(joining / "state/ez-agent/hub"),
            "active_request": request,
            "prepared_request": prepared_request,
            "target": target_fingerprint,
        })
        checked = subprocess.run(
            ["go", "test", "-count=1", "-timeout=30s", "-tags=agenthub_e2e",
             "./internal/frontend", "-run", "^TestAgentHubPairingCommittedState$", "-v"],
            cwd=REPO_ROOT, env=inspect_env, capture_output=True, text=True, timeout=60,
        )
        # This helper emits only closed diagnostics, never transcripts/state.
        assert checked.returncode == 0, checked.stdout + checked.stderr
        assert re.search(r"(?m)^--- PASS: TestAgentHubPairingCommittedState \(", checked.stdout), (
            checked.stdout + checked.stderr
        )
    finally:
        for process in list(reversed(processes)):
            stop(process)
        run_root.cleanup()