diff --git a/.github/workflows/mvp-ic1-windows-workloads.yml b/.github/workflows/mvp-ic1-windows-workloads.yml index 80f1cd30..ae89d597 100644 --- a/.github/workflows/mvp-ic1-windows-workloads.yml +++ b/.github/workflows/mvp-ic1-windows-workloads.yml @@ -8,6 +8,9 @@ on: - '.github/workflows/mvp-ic1-windows-workloads.yml' - 'scripts/ci/qualify-mvp-windows-workloads.sh' - 'scripts/ci/qualify-mvp-broker-real-keyboard.py' + - 'tests/test_wininspect_daemon_launch.py' + - 'api/core/wininspect.py' + - 'scripts/ci/qualify-mvp-wininspect-live.py' permissions: contents: read concurrency: @@ -33,6 +36,20 @@ jobs: persist-credentials: false ref: 8c5ed8019a3518cf534b158662755172bfce7c59 path: wine11-candidate + - name: Fail early on the known-unqualified WinInspect observer binary + working-directory: layered + shell: bash + run: | + set -euo pipefail + # Only the optional live observer path is blocked. The owning MVP + # without this harness must retain its normal real-Wine acceptance. + if test -f scripts/ci/qualify-mvp-wininspect-live.py && + { grep -Fq 'WinInspectPortable-v0.4.4.zip' docker/Dockerfile || + grep -Fq '6ac0a65f774ffe69672f1c459254931ebfddb1e52c9fbec14b5db1348ccaad04' docker/Dockerfile; }; then + echo 'IC1_OBSERVER_CAUSE=upstream_binary_unqualified' + echo 'IC1_OBSERVER_GATE=await_corrected_source_qualified_artifact' + exit 1 + fi - name: Reclaim disposable standard-runner disk run: | sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /usr/share/swift @@ -90,6 +107,7 @@ jobs: working-directory: layered run: | bash -n scripts/ci/qualify-mvp-windows-workloads.sh + python3 -m py_compile scripts/ci/qualify-mvp-wininspect-live.py # Reject accidentally appended/duplicated workload segments before # spending minutes rebuilding the pinned Wine and Windows fixtures. test "$(grep -Fc "echo 'MVP_WORKLOAD stage=bounded_qualification_pass'" scripts/ci/qualify-mvp-windows-workloads.sh)" -eq 1 diff --git a/api/core/wininspect.py b/api/core/wininspect.py index c8e8c649..f1196155 100644 --- a/api/core/wininspect.py +++ b/api/core/wininspect.py @@ -14,6 +14,9 @@ DEFAULT_HOST = "127.0.0.1" DEFAULT_PORT = 1985 +# Upstream WinInspect product v0.4.0 still speaks TCP protocol v0.3.0. +# Keep wire protocol version independent from the product release version. +WININSPECT_PROTOCOL_VERSION = "0.3.0" DEFAULT_TIMEOUT_SECONDS = 3.0 MAX_MESSAGE_SIZE = 10 * 1024 * 1024 READ_ONLY_METHODS = { @@ -172,7 +175,15 @@ def ensure_daemon(start: bool = True) -> dict[str, Any]: log_file = open(_log_path(), "ab") try: proc = subprocess.Popen( - ["wine", str(daemon_exe())], + # WinInspect tray mode can exit under headless Wine before + # its background TCP listener becomes available. The WineBot + # adapter is a service endpoint, so require the daemon's + # upstream-supported blocking/headless TCP mode explicitly. + # Match the adapter's loopback RPC endpoint explicitly. + # WinInspect's persisted Wine config and IPv6 defaults must + # not silently bind a different address or TCP port. + ["wine", str(daemon_exe()), "--headless", + "--bind", "127.0.0.1", "--port", str(port())], stdout=log_file, stderr=subprocess.STDOUT, start_new_session=True, @@ -252,9 +263,13 @@ def _read_frame(sock: socket.socket) -> dict[str, Any]: raise WinInspectError(f"WinInspect frame too large: {length}") payload = _recv_exact(sock, length) try: - return json.loads(payload.decode("utf-8")) - except json.JSONDecodeError as exc: - raise WinInspectError(f"invalid WinInspect JSON frame: {exc}") from exc + decoded = json.loads(payload.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + # Never expose arbitrary malformed daemon content in API errors. + raise WinInspectError("invalid WinInspect JSON frame") from exc + if not isinstance(decoded, dict): + raise WinInspectError("invalid WinInspect JSON frame root") + return decoded def _write_frame(sock: socket.socket, payload: dict[str, Any]) -> None: @@ -276,22 +291,35 @@ def request(method: str, params: dict[str, Any] | None = None) -> dict[str, Any] "id": request_id, "method": method, "params": { - "protocol_version": "0.4.0", **(params or {}), + # The caller may not downgrade or substitute the wire protocol. + "protocol_version": WININSPECT_PROTOCOL_VERSION, }, } with socket.create_connection((host(), port()), timeout=timeout_seconds()) as sock: sock.settimeout(timeout_seconds()) hello = _read_frame(sock) + if ( + hello.get("type") != "hello" + or hello.get("version") != WININSPECT_PROTOCOL_VERSION + ): + raise WinInspectError("WinInspect hello protocol mismatch") _write_frame(sock, payload) response = _read_frame(sock) if response.get("id") != request_id: # Never expose untrusted daemon hello identity in API-visible errors. raise WinInspectError("WinInspect response correlation failed") - if not response.get("ok"): - error = response.get("error") or {} - raise WinInspectError(str(error.get("message") or error or "WinInspect request failed")) + if type(response.get("ok")) is not bool: + raise WinInspectError("WinInspect response status invalid") + if response["ok"] is False: + error = response.get("error") + if not isinstance(error, dict): + raise WinInspectError("WinInspect response error invalid") + message = error.get("message") + if not isinstance(message, str) or not message: + raise WinInspectError("WinInspect request failed") + raise WinInspectError(message) return { "result": response.get("result"), "metrics": response.get("metrics"), diff --git a/docker/Dockerfile b/docker/Dockerfile index b8576012..09f42d34 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -40,6 +40,11 @@ RUN bash /download_tool.sh "WinInspect" \ "https://github.com/SemperSupra/WinInspect/releases/download/v0.4.4/WinInspectPortable-v0.4.4.zip" \ "6ac0a65f774ffe69672f1c459254931ebfddb1e52c9fbec14b5db1348ccaad04" \ "/opt/winebot/windows-tools/WinSpy" \ + && for binary in wininspectd.exe wininspect.exe wininspect-gui.exe; do \ + test -s "/opt/winebot/windows-tools/WinSpy/App/WinInspect/$binary" || exit 1; \ + cp "/opt/winebot/windows-tools/WinSpy/App/WinInspect/$binary" \ + "/opt/winebot/windows-tools/WinSpy/$binary" || exit 1; \ + done \ && find /opt/winebot/windows-tools -name "*.txt" -delete # --- Stage 2: Base System (From pre-built base) --- diff --git a/scripts/ci/qualify-mvp-windows-workloads.sh b/scripts/ci/qualify-mvp-windows-workloads.sh index 1a9c721a..09e3a116 100644 --- a/scripts/ci/qualify-mvp-windows-workloads.sh +++ b/scripts/ci/qualify-mvp-windows-workloads.sh @@ -116,6 +116,25 @@ docker compose -f compose/layered.yml exec -T winebot-interactive /bin/bash -euo fail editor_gui_save } echo 'MVP_WORKLOAD stage=real_windows_editor_gui_save' +# Require Windows-native read-only observation of this actual Wine GUI. +# Only allowlisted stage categories leave the disposable runner. +docker compose -f compose/layered.yml exec -T \ + -e GITHUB_ACTIONS=true -e GITHUB_EVENT_NAME=pull_request \ + -e PYTHONPATH=/ \ + winebot-interactive python3 /scripts/ci/qualify-mvp-wininspect-live.py \ + >"$RUNNER_TEMP/ic1-observer-local.log" 2>&1 || { + cause="$(grep -Eo 'IC1_OBSERVER_CAUSE=(unqualified_venue|binary_missing|daemon_unavailable|capabilities_missing|capabilities_unavailable|rpc_timeout|rpc_connection_error|rpc_version_rejected|rpc_correlation_rejected|rpc_connection_closed|rpc_unsupported_compression|rpc_daemon_rejected|rpc_transport_or_decode_error|observer_rpc_error|window_info_rpc_error|real_window_not_observed|daemon_exception|daemon_exited|daemon_tcp_timeout|daemon_log_unavailable|tcp_winsock_unavailable|tcp_no_sockets|tcp_bind_or_listen_failed|tcp_listener_reported_unreachable|tcp_start_requested_no_listener|daemon_initialized_no_tcp|daemon_no_output|daemon_log_preinit_only|unexpected_harness_exception)' "$RUNNER_TEMP/ic1-observer-local.log" | tail -1 || true)" + case "$cause" in + IC1_OBSERVER_CAUSE=*) printf '%s\n' "$cause" ;; + *) echo 'IC1_OBSERVER_CAUSE=unclassified' ;; + esac + fail wininspect_live_observation + } +grep -Fq 'IC1_OBSERVER=real_notepad_hwnd_readonly_pass' \ + "$RUNNER_TEMP/ic1-observer-local.log" || fail observer_receipt_missing +echo 'MVP_WORKLOAD stage=wininspect_real_notepad_observed' + + # Exercise real FastAPI broker policy and real X11→Wine keyboard dispatch. # The Python harness isolates ONLY session metadata/evidence writers, never # _send_keys or the X11 command. Do not publish private Wine/desktop traces. diff --git a/scripts/ci/qualify-mvp-wininspect-live.py b/scripts/ci/qualify-mvp-wininspect-live.py new file mode 100644 index 00000000..3b008c3d --- /dev/null +++ b/scripts/ci/qualify-mvp-wininspect-live.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Read-only Windows HWND observation of an actual running Notepad++ in Wine. + +Designed for the isolated IC1 public-hosted runner. Do not publish application +titles, screenshots, registry, user paths or raw WinInspect RPC responses. +""" +import os +import time + +from api.core import wininspect + + +def fail(stage: str) -> None: + raise RuntimeError("IC1_OBSERVER_CAUSE=" + stage) + + +def classify_daemon_startup() -> str: + """Reduce a local daemon log to a fixed, non-identifying public cause.""" + try: + # Never include log content or paths in a public CI result. + raw = wininspect._log_path() + with open(raw, "rb") as handle: + data = handle.read(131072).decode("utf-8", errors="replace") + except (OSError, ValueError): + return "daemon_log_unavailable" + if "TCP Server: Winsock not initialized" in data: + return "tcp_winsock_unavailable" + if "TCP Server: No sockets could be bound" in data: + return "tcp_no_sockets" + if "TCP Server: bind failed" in data or "TCP Server: listen failed" in data: + return "tcp_bind_or_listen_failed" + if "TCP Server listening on [" in data: + return "tcp_listener_reported_unreachable" + if "Starting TCP Server" in data: + return "tcp_start_requested_no_listener" + if "WinInspect Daemon " in data: + return "daemon_initialized_no_tcp" + if not data: + return "daemon_no_output" + return "daemon_log_preinit_only" + + + +def qualified_notepad_window(match: object, info: object) -> bool: + """Bind a read-only WinInspect lookup to the same visible Notepad++ HWND. + + The exact source-defined getInfo response has hwnd/title/visible/pid. + Never accept an adapter fallback such as {"hwnd": ..., "raw": ...}. + """ + if not isinstance(match, dict) or not isinstance(info, dict): + return False + hwnd = match.get("hwnd") + if not isinstance(hwnd, str) or not hwnd.startswith("0x"): + return False + try: + numeric_hwnd = int(hwnd[2:], 16) + except ValueError: + return False + if numeric_hwnd == 0 or info.get("hwnd") != hwnd: + return False + title = info.get("title") + pid = info.get("pid") + return ( + isinstance(title, str) + and "Notepad++" in title + and info.get("visible") is True + and type(pid) in (int, float) + and 0 < pid < 2**32 + ) + + +def main() -> None: + if os.environ.get("GITHUB_ACTIONS") != "true" or os.environ.get("GITHUB_EVENT_NAME") != "pull_request" or os.environ.get("WINEBOT_STATE_MODEL") != "layered": + fail("unqualified_venue") + if not wininspect.installed(): + fail("binary_missing") + # First Wine 11 process launch on a fresh disposable prefix can be slower + # than the adapter's interactive 10-second default. Bound the RDTE window, + # retain fail-closed TCP readiness and classify process exit vs timeout. + os.environ["WINEBOT_WININSPECT_START_TIMEOUT_SECONDS"] = "35" + try: + state = wininspect.ensure_daemon(start=True) + except Exception: + fail("daemon_exception") + if not state.get("running"): + if "exit_code" in state: + fail("daemon_exited") + if state.get("started"): + fail(classify_daemon_startup()) + fail("daemon_unavailable") + try: + capabilities = wininspect.capabilities() + except TimeoutError: + fail("rpc_timeout") + except ConnectionError: + fail("rpc_connection_error") + except wininspect.WinInspectError as exc: + # Only report fixed protocol/transport classes; never forward daemon + # strings, identity, application titles or arbitrary error details. + reason = str(exc) + if "E_PROTOCOL_VERSION" in reason or ( + "expected " in reason and " got " in reason + ): + fail("rpc_version_rejected") + if "response correlation failed" in reason: + fail("rpc_correlation_rejected") + if "connection closed while reading frame" in reason: + fail("rpc_connection_closed") + if "compressed WinInspect frames" in reason: + fail("rpc_unsupported_compression") + fail("rpc_daemon_rejected") + except (OSError, ValueError, KeyError, TypeError): + fail("rpc_transport_or_decode_error") + if not isinstance(capabilities, dict) or not capabilities: + fail("capabilities_missing") + + deadline = time.monotonic() + 25 + while time.monotonic() < deadline: + try: + matches = wininspect.find_windows(title_regex=r"Notepad[+][+]") + except Exception: + fail("observer_rpc_error") + for match in matches: + if not isinstance(match, dict): + continue + hwnd = match.get("hwnd") + if not isinstance(hwnd, str) or not hwnd.startswith("0x"): + continue + try: + info = wininspect.window_info(hwnd) + except Exception: + fail("window_info_rpc_error") + if qualified_notepad_window(match, info): + print("IC1_OBSERVER=real_notepad_hwnd_readonly_pass") + return + time.sleep(1) + fail("real_window_not_observed") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + if isinstance(exc, RuntimeError) and str(exc).startswith("IC1_OBSERVER_CAUSE="): + print(str(exc)) + else: + # Never publish Wine/desktop responses, paths or raw tracebacks. + print("IC1_OBSERVER_CAUSE=unexpected_harness_exception") + raise SystemExit(1) from None diff --git a/scripts/ci/test.sh b/scripts/ci/test.sh index d6811633..3c768798 100755 --- a/scripts/ci/test.sh +++ b/scripts/ci/test.sh @@ -31,7 +31,9 @@ pytest \ tests/test_ci_public_conformance_summary.py \ tests/test_ci_unit_isolation.py \ tests/test_winepath_startup_retry.py \ + tests/test_wininspect.py \ tests/test_wininspect_error_redaction.py \ + tests/test_wininspect_daemon_launch.py \ tests/test_ci_vnext_evidence.py \ tests/test_lifecycle_cancel_window.py \ tests/test_health_system_memory.py \ diff --git a/tests/test_wininspect.py b/tests/test_wininspect.py index 52a3024c..45c975fa 100644 --- a/tests/test_wininspect.py +++ b/tests/test_wininspect.py @@ -73,6 +73,173 @@ def test_wininspect_request_uses_length_prefixed_json(): assert sent_payload["params"]["protocol_version"] == "0.3.0" + +@pytest.mark.parametrize( + "reply", + [ + {"id": "", "ok": True, "result": {"features": {}}}, + {"ok": True, "result": {"features": {}}}, + {"id": "other-actor-request", "ok": True, "result": {"features": {}}}, + {"id": "", "ok": False, "error": {"code": "E_BAD_METHOD"}}, + {"id": "other-actor-request", "ok": False, "error": {"code": "E_BAD_METHOD"}}, + ], +) +def test_wininspect_fails_closed_on_missing_or_foreign_rpc_correlation(reply): + """A real daemon's empty handler ID must never be accepted or leaked.""" + fake = FakeSocket([{"type": "hello", "version": "0.3.0"}, reply]) + with ( + patch("api.core.wininspect.ensure_daemon", return_value={"running": True}), + patch("api.core.wininspect.uuid.uuid4") as mock_uuid, + patch("api.core.wininspect.socket.create_connection", return_value=fake), + ): + mock_uuid.return_value.hex = "abc1234567890" + with pytest.raises(wininspect.WinInspectError, match="response correlation failed") as err: + wininspect.request("daemon.capabilities") + assert "other-actor-request" not in str(err.value) + assert fake.sent + + +def test_wininspect_accepts_exact_correlation_on_failed_rpc_before_returning_error(): + fake = FakeSocket( + [ + {"type": "hello", "version": "0.3.0"}, + {"id": "winebot-abc123456789", "ok": False, + "error": {"code": "E_BAD_REQUEST", "message": "synthetic-denial"}}, + ] + ) + with ( + patch("api.core.wininspect.ensure_daemon", return_value={"running": True}), + patch("api.core.wininspect.uuid.uuid4") as mock_uuid, + patch("api.core.wininspect.socket.create_connection", return_value=fake), + ): + mock_uuid.return_value.hex = "abc1234567890" + with pytest.raises(wininspect.WinInspectError, match="synthetic-denial"): + wininspect.request("daemon.capabilities") + + + +@pytest.mark.parametrize( + "body", + [b"[]", b"null", b"true", b'"raw"', b"12", b"not-json", bytes([255])], +) +def test_wininspect_rejects_untrusted_nonobject_or_malformed_rpc_frames(body): + """A malformed daemon frame cannot turn into an uncaught API exception.""" + framed = struct.pack("!I", len(body)) + body + + class OneFrameSocket: + def __init__(self): + self.data = bytearray(framed) + + def recv(self, size): + chunk = bytes(self.data[:size]) + del self.data[:size] + return chunk + with pytest.raises(wininspect.WinInspectError, match="invalid WinInspect JSON frame"): + wininspect._read_frame(OneFrameSocket()) + + +def test_wininspect_rejects_truncated_rpc_frame_without_payload_disclosure(): + class TruncatedSocket: + def __init__(self): + self.data = bytearray(struct.pack("!I", 4) + b"{") + + def recv(self, size): + chunk = bytes(self.data[:size]) + del self.data[:size] + return chunk + with pytest.raises(wininspect.WinInspectError, match="connection closed while reading frame"): + wininspect._read_frame(TruncatedSocket()) + + + +@pytest.mark.parametrize( + "hello", + [ + {"type": "unexpected", "version": "0.3.0"}, + {"type": "hello", "version": "0.4.0"}, + {"type": "hello"}, + {"version": "0.3.0"}, + {}, + ], +) +def test_wininspect_rejects_invalid_daemon_hello_before_sending_request(hello): + fake = FakeSocket([hello]) + with ( + patch("api.core.wininspect.ensure_daemon", return_value={"running": True}), + patch("api.core.wininspect.socket.create_connection", return_value=fake), + ): + with pytest.raises(wininspect.WinInspectError, match="hello protocol mismatch"): + wininspect.request("daemon.capabilities") + assert fake.sent == b"" + + +def test_wininspect_caller_cannot_override_pinned_rpc_protocol_version(): + fake = FakeSocket( + [ + {"type": "hello", "version": "0.3.0"}, + {"id": "winebot-abc123456789", "ok": True, "result": {"features": {}}}, + ] + ) + with ( + patch("api.core.wininspect.ensure_daemon", return_value={"running": True}), + patch("api.core.wininspect.uuid.uuid4") as mock_uuid, + patch("api.core.wininspect.socket.create_connection", return_value=fake), + ): + mock_uuid.return_value.hex = "abc1234567890" + result = wininspect.request( + "daemon.capabilities", {"protocol_version": "0.4.0"} + ) + assert result["result"] == {"features": {}} + sent_length = struct.unpack("!I", fake.sent[:4])[0] + sent_payload = json.loads(fake.sent[4 : 4 + sent_length].decode("utf-8")) + assert sent_payload["params"]["protocol_version"] == "0.3.0" + + + +@pytest.mark.parametrize( + "reply", + [ + {"ok": "false", "result": {}}, + {"ok": 1, "result": {}}, + {"ok": None, "result": {}}, + {"result": {}}, + ], +) +def test_wininspect_refuses_nonboolean_or_missing_rpc_status(reply): + response = {"id": "winebot-abc123456789", **reply} + fake = FakeSocket([{"type": "hello", "version": "0.3.0"}, response]) + with ( + patch("api.core.wininspect.ensure_daemon", return_value={"running": True}), + patch("api.core.wininspect.uuid.uuid4") as mock_uuid, + patch("api.core.wininspect.socket.create_connection", return_value=fake), + ): + mock_uuid.return_value.hex = "abc1234567890" + with pytest.raises(wininspect.WinInspectError, match="response status invalid"): + wininspect.request("daemon.capabilities") + + +@pytest.mark.parametrize( + "error", + [None, [], "unexpected raw daemon error", 0, {"message": ["unexpected"]}], +) +def test_wininspect_refuses_malformed_rpc_error_envelope(error): + reply = {"id": "winebot-abc123456789", "ok": False, "error": error} + fake = FakeSocket([{"type": "hello", "version": "0.3.0"}, reply]) + with ( + patch("api.core.wininspect.ensure_daemon", return_value={"running": True}), + patch("api.core.wininspect.uuid.uuid4") as mock_uuid, + patch("api.core.wininspect.socket.create_connection", return_value=fake), + ): + mock_uuid.return_value.hex = "abc1234567890" + with pytest.raises(wininspect.WinInspectError) as exc: + wininspect.request("daemon.capabilities") + assert str(exc.value) in { + "WinInspect response error invalid", + "WinInspect request failed", + } + assert "unexpected" not in str(exc.value) + + def test_wininspect_blocks_mutating_methods(): with pytest.raises(wininspect.WinInspectError): wininspect.request("input.text", {"text": "blocked"}) diff --git a/tests/test_wininspect_daemon_launch.py b/tests/test_wininspect_daemon_launch.py new file mode 100644 index 00000000..1b340f8e --- /dev/null +++ b/tests/test_wininspect_daemon_launch.py @@ -0,0 +1,88 @@ +"""WineBot's WinInspect adapter must use headless TCP daemon mode. + +Synthetic subprocess only: no real Wine process, network port or user files. +""" +import runpy +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from api.core import wininspect as wi + + +def test_rpc_daemon_uses_upstream_headless_mode(tmp_path): + fake = SimpleNamespace(pid=42, poll=lambda: None) + with ( + patch.object(wi, "_daemon_proc", None), + patch.object(wi, "enabled", return_value=True), + patch.object(wi, "installed", return_value=True), + patch.object(wi, "_tcp_ready", side_effect=[False, False, True]), + patch.object(wi, "daemon_exe", return_value=Path("/synthetic/wininspectd.exe")), + patch.object(wi, "_log_path", return_value=str(tmp_path / "wininspectd.log")), + patch.object(wi.subprocess, "Popen", return_value=fake) as launch, + patch.object(wi, "manage_process"), + ): + result = wi.ensure_daemon(start=True) + assert result["running"] is True + assert result["started"] is True + assert launch.call_args.args[0] == [ + "wine", + "/synthetic/wininspectd.exe", + "--headless", + "--bind", "127.0.0.1", "--port", str(wi.DEFAULT_PORT), + ] + + +def test_real_wine_workflow_refuses_known_unqualified_observer_binary_early(): + """The observer must not burn a Wine build on a known-failing native ZIP.""" + repo = Path(__file__).resolve().parents[1] + workflow = (repo / ".github/workflows/mvp-ic1-windows-workloads.yml").read_text() + gate = "Fail early on the known-unqualified WinInspect observer binary" + assert workflow.count(gate) == 1 + assert workflow.index(gate) < workflow.index("Reclaim disposable standard-runner disk") + assert "test -f scripts/ci/qualify-mvp-wininspect-live.py" in workflow + assert "WinInspectPortable-v0.4.4.zip" in workflow + # A superficial rename must not evade the known bad archive digest. + assert "6ac0a65f774ffe69672f1c459254931ebfddb1e52c9fbec14b5db1348ccaad04" in workflow + assert "IC1_OBSERVER_CAUSE=upstream_binary_unqualified" in workflow + assert "exit 1" in workflow[workflow.index(gate):workflow.index("Reclaim disposable standard-runner disk")] + +@pytest.mark.parametrize( + ("match", "info", "expected"), + [ + ( + {"hwnd": "0xA1"}, + {"hwnd": "0xA1", "title": "sample.txt - Notepad++", + "visible": True, "pid": 193.0}, + True, + ), + ({"hwnd": "0xA1"}, {"hwnd": "0xB2", "title": "Notepad++", + "visible": True, "pid": 193}, False), + ({"hwnd": "0xA1"}, {"hwnd": "0xA1", "raw": "opaque"}, False), + ({"hwnd": "0xA1"}, {"hwnd": "0xA1", "title": "Other editor", + "visible": True, "pid": 193}, False), + ({"hwnd": "0xA1"}, {"hwnd": "0xA1", "title": "Notepad++", + "visible": False, "pid": 193}, False), + ({"hwnd": "0xA1"}, {"hwnd": "0xA1", "title": "Notepad++", + "visible": True, "pid": 0}, False), + ({"hwnd": "0xA1"}, {"hwnd": "0xA1", "title": "Notepad++", + "visible": True, "pid": True}, False), + ({"hwnd": "0x0"}, {"hwnd": "0x0", "title": "Notepad++", + "visible": True, "pid": 193}, False), + ({"hwnd": "not-a-handle"}, {"hwnd": "not-a-handle", + "title": "Notepad++", "visible": True, + "pid": 193}, False), + ("malformed", {"hwnd": "0xA1", "title": "Notepad++", + "visible": True, "pid": 193}, False), + ({"hwnd": "0xA1"}, ["malformed"], False), + ], +) +def test_live_observer_requires_same_visible_notepad_hwnd(match, info, expected): + """Read-only live acceptance must not pass on fallback, stale or hidden windows.""" + repo = Path(__file__).resolve().parents[1] + probe = runpy.run_path( + str(repo / "scripts/ci/qualify-mvp-wininspect-live.py") + )["qualified_notepad_window"] + assert probe(match, info) is expected