#!/usr/bin/env python3
"""Summarize whether the current VM can run the EXE runtime trace needed for blockers."""
from __future__ import annotations

import argparse
import html
import json
import shutil
import subprocess
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"
RUNTIME_TRACE_FEASIBILITY_EVIDENCE_REFS = [
    {
        "path": "out/runtime_trace_execution_probe.json",
        "fields": [
            "canCaptureTraceNow",
            "blockers",
            "probes",
            "promotionStatus",
            "proofFound",
            "runtimeTraceExecutionProofFound",
            "failedRuntimeTraceExecutionGateIds",
            "missingEvidence",
            "evidenceRefs",
            "evidenceRefCount",
        ],
    },
    {"path": "out/runtime_memory_snapshot.json", "fields": ["loadedBaseHex", "memory", "promotionStatus"]},
    {"path": "out/runtime_input_path_probe.json", "fields": ["heldKeyPressedDetected", "baselineSelectedPointerContext", "finalSelectedPointerContext"]},
    {"path": "out/runtime_key_sequence_probe.json", "fields": ["sequenceCount", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_key_sequence_prelude_probe.json", "fields": ["sequenceCount", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_poll.json", "fields": ["sampleCount", "observedSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_prelude_poll.json", "fields": ["sampleCount", "observedSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_long_poll.json", "fields": ["sampleCount", "observedSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_late_poll.json", "fields": ["sampleCount", "observedSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_route_watch_values_poll.json", "fields": ["sampleCount", "observedWatchValues", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_savedata_load_poll.json", "fields": ["sampleCount", "observedSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_multislot_savedata_load_poll.json", "fields": ["sampleCount", "publicSaveSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_multislot_savedata_load_case_alias_poll.json", "fields": ["sampleCount", "publicSaveSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll.json", "fields": ["sampleCount", "publicSaveSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.json", "fields": ["sampleCount", "publicSaveSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.json", "fields": ["sampleCount", "publicSaveSelectors", "anyReachedRouteSelectorContext"]},
    {"path": "out/runtime_save_file_io_probe.json", "fields": ["backend", "inputTraceUsable", "anySavedat1DatAccess"]},
    {"path": "out/runtime_save_file_io_strace_probe.json", "fields": ["backend", "inputTraceUsable", "anySavedat1DatAccess"]},
    {"path": "out/runtime_save_file_io_strace_attach_probe.json", "fields": ["backend", "inputTraceUsable", "anySavedat1DatAccess"]},
    {"path": "out/runtime_save_file_io_strace_attach_load_candidates_probe.json", "fields": ["backend", "inputTraceUsable", "anySavedat1DatAccess"]},
    {"path": "out/runtime_save_file_io_strace_attach_load_candidates_case_alias_probe.json", "fields": ["backend", "inputTraceUsable", "anySavedat1DatAccess"]},
]


def existing_evidence_refs() -> list[dict]:
    return [
        ref
        for ref in RUNTIME_TRACE_FEASIBILITY_EVIDENCE_REFS
        if (ROOT / ref["path"]).exists()
    ]


def run_text(cmd: list[str]) -> tuple[int, str]:
    try:
        result = subprocess.run(
            cmd,
            cwd=ROOT,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            errors="replace",
            timeout=10,
        )
    except (OSError, subprocess.SubprocessError) as exc:
        return 127, str(exc)
    return result.returncode, result.stdout.strip()


def first_line(text: str) -> str:
    return (text.splitlines() or [""])[0]


def apt_candidate(package: str) -> dict:
    status, output = run_text(["apt-cache", "policy", package])
    candidate = None
    installed = None
    for line in output.splitlines():
        stripped = line.strip()
        if stripped.startswith("Installed:"):
            installed = stripped.split(":", 1)[1].strip()
        if stripped.startswith("Candidate:"):
            candidate = stripped.split(":", 1)[1].strip()
    return {
        "package": package,
        "status": status,
        "installed": installed,
        "candidate": candidate,
        "rawFirstLine": first_line(output),
    }


def command_info(command: str) -> dict:
    path = shutil.which(command)
    return {
        "command": command,
        "available": bool(path),
        "path": path,
    }


def load_execution_probe(out_dir: Path = OUT) -> dict | None:
    path = out_dir / "runtime_trace_execution_probe.json"
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    return data if isinstance(data, dict) else None


def load_memory_snapshot(out_dir: Path = OUT) -> dict | None:
    path = out_dir / "runtime_memory_snapshot.json"
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    return data if isinstance(data, dict) else None


def load_input_probe(out_dir: Path = OUT) -> dict | None:
    path = out_dir / "runtime_input_path_probe.json"
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    return data if isinstance(data, dict) else None


def load_key_sequence_probe(out_dir: Path = OUT, filename: str = "runtime_key_sequence_probe.json") -> dict | None:
    path = out_dir / filename
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    return data if isinstance(data, dict) else None


def load_selected_pointer_poll(
    out_dir: Path = OUT,
    filename: str = "runtime_selected_pointer_poll.json",
) -> dict | None:
    path = out_dir / filename
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    return data if isinstance(data, dict) else None


def load_save_file_io_probe(
    out_dir: Path = OUT,
    filename: str = "runtime_save_file_io_probe.json",
) -> dict | None:
    path = out_dir / filename
    if not path.exists():
        return None
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    return data if isinstance(data, dict) else None


def watch_value_summary(poll: dict | None) -> str:
    parts = []
    for name, rows in sorted(((poll or {}).get("observedWatchValues") or {}).items()):
        values = ",".join(
            f"{row.get('valueHex')}x{row.get('count')}"
            for row in rows or []
            if row.get("valueHex") is not None
        )
        parts.append(f"{name}={values or '-'}")
    return "; ".join(parts) or "-"


def selected_pointer_poll_input_quality(poll: dict | None) -> dict:
    rows = (poll or {}).get("rows") or []
    pressed_offsets = set()
    pressed_event_count = 0
    sequence_with_observed_press = 0
    key_write_ok_count = 0
    sequence_with_key_writes = 0
    for row in rows:
        writes = row.get("writes") or []
        row_write_ok = any((write.get("write") or {}).get("writeOk") is True for write in writes)
        if row_write_ok:
            sequence_with_key_writes += 1
        key_write_ok_count += sum(1 for write in writes if (write.get("write") or {}).get("writeOk") is True)
        row_has_press = False
        for event in row.get("events") or []:
            offsets = event.get("pressedKeyOffsets") or []
            if offsets:
                row_has_press = True
                pressed_event_count += 1
                pressed_offsets.update(offset for offset in offsets if isinstance(offset, int))
        if row_has_press:
            sequence_with_observed_press += 1
    return {
        "sequenceCount": len(rows),
        "sequenceWithPidCount": sum(1 for row in rows if row.get("linuxPid")),
        "sequenceWithLoadedBaseCount": sum(1 for row in rows if row.get("loadedBaseHex")),
        "sequenceWithFocusedWindowCount": sum(1 for row in rows if row.get("focusedWindows")),
        "sequenceWithKeyWritesCount": sequence_with_key_writes,
        "keyWriteOkCount": key_write_ok_count,
        "sequenceWithObservedKeyPressCount": sequence_with_observed_press,
        "pressedEventCount": pressed_event_count,
        "observedPressedKeyOffsets": sorted(pressed_offsets),
        "inputObservedInAllSequences": bool(rows) and sequence_with_observed_press == len(rows),
    }


def selected_pointer_poll_input_quality_brief(quality: dict | None) -> str:
    if not quality:
        return "-"
    offsets = ",".join(str(offset) for offset in quality.get("observedPressedKeyOffsets") or []) or "-"
    return (
        f"pid={quality.get('sequenceWithPidCount')}/{quality.get('sequenceCount')} "
        f"base={quality.get('sequenceWithLoadedBaseCount')}/{quality.get('sequenceCount')} "
        f"keyWrites={quality.get('sequenceWithKeyWritesCount')}/{quality.get('sequenceCount')} "
        f"pressedSeq={quality.get('sequenceWithObservedKeyPressCount')}/{quality.get('sequenceCount')} "
        f"pressedEvents={quality.get('pressedEventCount')} offsets={offsets}"
    )


def binfmt_status(name: str) -> dict:
    path = Path("/proc/sys/fs/binfmt_misc") / name
    if not path.exists():
        return {
            "name": name,
            "registered": False,
            "enabled": False,
            "path": str(path),
            "rawFirstLine": "",
        }
    raw = path.read_text(encoding="utf-8", errors="replace")
    return {
        "name": name,
        "registered": True,
        "enabled": "enabled" in raw,
        "path": str(path),
        "rawFirstLine": first_line(raw),
    }


def build_summary() -> dict:
    commands = {
        name: command_info(name)
        for name in [
            "wine",
            "winedbg",
            "wineboot",
            "gdb",
            "gdb-multiarch",
            "Xvfb",
            "xvfb-run",
            "xdotool",
            "xwininfo",
            "qemu-i386",
            "strace",
        ]
    }
    _, arch = run_text(["dpkg", "--print-architecture"])
    _, foreign_arches = run_text(["dpkg", "--print-foreign-architectures"])
    wine32 = apt_candidate("wine32")
    wine64_tools = apt_candidate("wine64-tools")
    wine_meta = apt_candidate("wine")
    qemu_user_binfmt = apt_candidate("qemu-user-binfmt")
    gdb_multiarch = apt_candidate("gdb-multiarch")
    wine_version_status, wine_version_output = run_text(["wine", "--version"])
    wine_loader_smoke = {
        "command": "wine --version",
        "status": wine_version_status,
        "firstLine": first_line(wine_version_output),
        "ok": wine_version_status == 0,
    }
    qemu_wine_status, qemu_wine_output = run_text(["qemu-i386", "/usr/lib/wine/wine", "--version"])
    qemu_wine_loader_smoke = {
        "command": "qemu-i386 /usr/lib/wine/wine --version",
        "status": qemu_wine_status,
        "firstLine": first_line(qemu_wine_output),
        "ok": qemu_wine_status == 0,
    }
    qemu_child_status, qemu_child_output = run_text([
        "env",
        "WINEDEBUG=-all",
        "qemu-i386",
        "/usr/lib/wine/wine",
        "cmd",
        "/c",
        "ver",
    ])
    qemu_wine_child_exec_smoke = {
        "command": "env WINEDEBUG=-all qemu-i386 /usr/lib/wine/wine cmd /c ver",
        "status": qemu_child_status,
        "firstLine": first_line(qemu_child_output),
        "ok": qemu_child_status == 0,
    }
    qemu_i386_binfmt = binfmt_status("qemu-i386")
    execution_probe = load_execution_probe()
    memory_snapshot = load_memory_snapshot()
    input_probe = load_input_probe()
    key_sequence_probe = load_key_sequence_probe()
    key_sequence_prelude_probe = load_key_sequence_probe(filename="runtime_key_sequence_prelude_probe.json")
    selected_pointer_poll = load_selected_pointer_poll()
    selected_pointer_prelude_poll = load_selected_pointer_poll(filename="runtime_selected_pointer_prelude_poll.json")
    selected_pointer_long_poll = load_selected_pointer_poll(filename="runtime_selected_pointer_long_poll.json")
    selected_pointer_late_poll = load_selected_pointer_poll(filename="runtime_selected_pointer_late_poll.json")
    route_watch_values_poll = load_selected_pointer_poll(filename="runtime_route_watch_values_poll.json")
    selected_pointer_savedata_load_poll = load_selected_pointer_poll(
        filename="runtime_selected_pointer_savedata_load_poll.json"
    )
    selected_pointer_multislot_savedata_load_poll = load_selected_pointer_poll(
        filename="runtime_selected_pointer_multislot_savedata_load_poll.json"
    )
    selected_pointer_multislot_savedata_load_case_alias_poll = load_selected_pointer_poll(
        filename="runtime_selected_pointer_multislot_savedata_load_case_alias_poll.json"
    )
    selected_pointer_multislot_savedata_load_input_path_case_alias_poll = load_selected_pointer_poll(
        filename="runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll.json"
    )
    selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll = load_selected_pointer_poll(
        filename="runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.json"
    )
    selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll = load_selected_pointer_poll(
        filename="runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.json"
    )
    selected_pointer_savedata_load_input_quality = selected_pointer_poll_input_quality(
        selected_pointer_savedata_load_poll
    )
    selected_pointer_multislot_savedata_load_input_quality = selected_pointer_poll_input_quality(
        selected_pointer_multislot_savedata_load_poll
    )
    selected_pointer_multislot_savedata_load_case_alias_input_quality = selected_pointer_poll_input_quality(
        selected_pointer_multislot_savedata_load_case_alias_poll
    )
    selected_pointer_multislot_savedata_load_input_path_case_alias_input_quality = selected_pointer_poll_input_quality(
        selected_pointer_multislot_savedata_load_input_path_case_alias_poll
    )
    selected_pointer_synthetic_selector_2_0_input_path_case_alias_input_quality = selected_pointer_poll_input_quality(
        selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll
    )
    selected_pointer_patched_public_selector_2_0_input_path_case_alias_input_quality = (
        selected_pointer_poll_input_quality(selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll)
    )
    save_file_io_probe = load_save_file_io_probe()
    save_file_io_strace_probe = load_save_file_io_probe(filename="runtime_save_file_io_strace_probe.json")
    save_file_io_strace_attach_probe = load_save_file_io_probe(
        filename="runtime_save_file_io_strace_attach_probe.json"
    )
    save_file_io_strace_attach_load_candidates_probe = load_save_file_io_probe(
        filename="runtime_save_file_io_strace_attach_load_candidates_probe.json"
    )
    save_file_io_strace_attach_load_candidates_case_alias_probe = load_save_file_io_probe(
        filename="runtime_save_file_io_strace_attach_load_candidates_case_alias_probe.json"
    )
    base_environment_ready = (
        commands["wine"]["available"]
        and commands["winedbg"]["available"]
        and commands["wineboot"]["available"]
        and commands["gdb"]["available"]
        and commands["xvfb-run"]["available"]
        and wine_loader_smoke["ok"]
    )
    blockers = []
    if not commands["wine"]["available"]:
        blockers.append("wine is not installed")
    if not commands["winedbg"]["available"]:
        blockers.append("winedbg is not installed")
    if not commands["wineboot"]["available"]:
        blockers.append("wineboot is not installed")
    if not commands["gdb"]["available"]:
        blockers.append("gdb is not installed")
    if not commands["xvfb-run"]["available"]:
        blockers.append("xvfb-run/Xvfb is not installed for headless DirectDraw startup")
    if "i386" not in (foreign_arches.split() if foreign_arches else []):
        blockers.append("i386 architecture is not enabled, so wine32 is unavailable from the current apt view")
    if wine32.get("candidate") in {None, "(none)"}:
        blockers.append("wine32 has no candidate package in the current apt configuration")
    if not wine_loader_smoke["ok"]:
        blockers.append(f"wine --version failed: {wine_loader_smoke['firstLine'] or 'no output'}")
    if qemu_wine_loader_smoke["ok"] and not qemu_wine_child_exec_smoke["ok"]:
        if not qemu_i386_binfmt["enabled"]:
            blockers.append(
                "direct qemu-i386 can start the Wine loader, but Wine child-process loader exec still fails without binfmt"
            )
        else:
            blockers.append(
                "direct qemu-i386 Wine cmd child smoke failed despite qemu-i386 binfmt: "
                f"{qemu_wine_child_exec_smoke['firstLine'] or 'no output'}"
            )
    if commands["qemu-i386"]["available"] and not qemu_i386_binfmt["enabled"] and not wine_loader_smoke["ok"]:
        blockers.append("qemu-i386 is installed but qemu-i386 binfmt is not enabled for transparent i386 Wine exec")
    if execution_probe and not execution_probe.get("canCaptureTraceNow"):
        blockers.extend(f"execution probe: {item}" for item in execution_probe.get("blockers") or [])
    can_run_now = base_environment_ready and not blockers
    trace_points = [
        {
            "name": "mode1 source write watchpoint",
            "kind": "watch-write-byte",
            "addressHex": "0x0059e348",
            "purpose": "break on any runtime producer of opcode 0x24 mode1 source before the handler reads it",
        },
        {
            "name": "opcode24 mode1 read",
            "kind": "execute-breakpoint",
            "addressHex": "0x0040c675",
            "purpose": "confirm the value consumed by opcode 0x24 mode1 on the map1_01a->map2_02d path",
        },
        {
            "name": "current blocker frontier reader",
            "kind": "execute-breakpoint",
            "addressHex": "0x00542b0c",
            "purpose": "confirm the control path reaches the branch reader and capture selectionBuffer[0x20]",
        },
        {
            "name": "gate-time context base proof",
            "kind": "execute-breakpoint",
            "addressHex": "0x005428c4",
            "purpose": "capture context+0xa8 base and gate index before the first inherited gate",
        },
    ]
    commands_to_try = [
        "sudo dpkg --add-architecture i386 && sudo apt-get update",
        "sudo apt-get install wine32 wine64-tools xvfb gdb qemu-user-binfmt",
        "sudo apt-get install gdb-multiarch",
        "if native i386 exec is unavailable, register qemu-i386 binfmt for EM_386 ELF binaries",
        "xvfb-run -a wineboot -u",
        "python3 tools/probe_runtime_trace_execution.py",
        "WINEDEBUG=-all xvfb-run -a winedbg --gdb Hwanse2.exe",
        "gdb -q -ex 'target remote :<winedbg-port>' -ex 'watch *(unsigned char*)0x0059e348' -ex 'hbreak *0x0040c675'",
        "python3 tools/probe_runtime_memory_snapshot.py",
        "python3 tools/probe_runtime_input_path.py",
        "python3 tools/probe_runtime_key_sequences.py",
        "python3 tools/probe_runtime_selected_pointer_poll.py",
        "python3 tools/probe_runtime_selected_pointer_poll.py --prelude input-path --sequence-name accept --sequence-name accept-accept --sequence-name accept-down-accept --output-prefix runtime_selected_pointer_prelude_poll",
        "python3 tools/probe_runtime_selected_pointer_poll.py --startup-wait 45 --output-prefix runtime_selected_pointer_late_poll --sequence 'late-menu-explore=Return,Return,z,Return,Down,Return,Down,Return,Up,Return,Escape,Return,space,Return,x,Return,c,Return,Right,Return,Left,Return,Down,Down,Return'",
        "python3 tools/probe_runtime_selected_pointer_poll.py --startup-wait 45 --hold 0.35 --gap 0.5 --interval 0.02 --output-prefix runtime_route_watch_values_poll --sequence 'late-menu-explore=Return,Return,z,Return,Down,Return,Down,Return,Up,Return,Escape,Return,space,Return,x,Return,c,Return,Right,Return,Left,Return,Down,Down,Return'",
        "place a non-synthetic savedat under SaveData\\savedat1.dat, then run python3 tools/probe_runtime_selected_pointer_poll.py --startup-wait 18 --output-prefix runtime_selected_pointer_savedata_load_poll with load-menu candidate sequences",
        "python3 tools/probe_runtime_selected_pointer_multislot_savedata_poll.py",
        "python3 tools/probe_runtime_selected_pointer_multislot_savedata_poll.py --case-aliases --output-prefix runtime_selected_pointer_multislot_savedata_load_case_alias_poll",
        "python3 tools/probe_runtime_selected_pointer_multislot_savedata_poll.py --prelude input-path --case-aliases --output-prefix runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll",
        "python3 tools/probe_runtime_selected_pointer_multislot_savedata_poll.py --prelude input-path --case-aliases --staged-kind 'patched public-base diagnostic' --slot-source 1=out/runtime_patched_public_savedat_selector_2_0.dat --sequence input-path-slot1-down-enter=Down,Return --sequence input-path-slot1-down-enter-enter=Down,Return,Return --output-prefix runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll",
        "python3 tools/probe_runtime_save_file_io.py --backend strace --sequence load-down-enter=Down,Return --output-prefix runtime_save_file_io_strace_probe",
        "python3 tools/probe_runtime_save_file_io.py --backend strace-attach --sequence load-down-enter=Down,Return --output-prefix runtime_save_file_io_strace_attach_probe",
        "python3 tools/probe_runtime_save_file_io.py --backend strace-attach --output-prefix runtime_save_file_io_strace_attach_load_candidates_probe --sequence load-down-enter=Down,Return --sequence load-down-z=Down,z --sequence load-down-space=Down,space --sequence load-down-x=Down,x --sequence load-return-down-z=Return,Down,z --sequence load-return-down-space=Return,Down,space --sequence load-return-down-x=Return,Down,x --sequence load-down-enter-enter=Down,Return,Return",
        "python3 tools/probe_runtime_save_file_io.py --backend strace-attach --case-aliases --output-prefix runtime_save_file_io_strace_attach_load_candidates_case_alias_probe --sequence load-down-enter=Down,Return --sequence load-down-z=Down,z --sequence load-down-space=Down,space --sequence load-down-x=Down,x --sequence load-return-down-z=Return,Down,z --sequence load-return-down-space=Return,Down,space --sequence load-return-down-x=Return,Down,x --sequence load-down-enter-enter=Down,Return,Return",
        "qemu-i386 /usr/lib/wine/wine --version",
        "env WINEDEBUG=-all qemu-i386 /usr/lib/wine/wine cmd /c ver",
    ]
    execution_probe_binfmt = (execution_probe or {}).get("qemuI386Binfmt") or {}
    execution_probe_binfmt_raw = execution_probe_binfmt.get("raw") or ""
    execution_probe_binfmt_enabled = bool(execution_probe_binfmt.get("registered")) and (
        "enabled" in execution_probe_binfmt_raw
    )
    binfmt_consistency = {
        "summaryRegistered": qemu_i386_binfmt.get("registered"),
        "summaryEnabled": qemu_i386_binfmt.get("enabled"),
        "summaryRawFirstLine": qemu_i386_binfmt.get("rawFirstLine"),
        "executionProbeRegistered": execution_probe_binfmt.get("registered"),
        "executionProbeEnabled": execution_probe_binfmt_enabled,
        "executionProbeRawFirstLine": first_line(execution_probe_binfmt_raw),
        "qemuWineChildExecOk": qemu_wine_child_exec_smoke.get("ok"),
        "debuggerProbeCanCapture": (execution_probe or {}).get("canCaptureTraceNow"),
        "conclusion": (
            "The current summary /proc view and the embedded execution probe disagree about qemu-i386 "
            "binfmt state, but both paths still leave the child/debugger trace unavailable."
            if execution_probe_binfmt.get("registered") is True
            and execution_probe_binfmt_enabled != bool(qemu_i386_binfmt.get("enabled"))
            else "The qemu-i386 binfmt state is consistent with the child/debugger trace availability check."
        ),
    }
    snapshot_note = ""
    if memory_snapshot and (memory_snapshot.get("memory") or {}).get("canReadProcessMemory"):
        memory = memory_snapshot.get("memory") or {}
        snapshot_note = (
            " A /proc process-memory snapshot can read the relocated Hwanse2.exe image "
            f"(loadedBase={memory_snapshot.get('loadedBaseHex')}, "
            f"selectedPointer={memory.get('selectedPointerStaticValueHex') or memory.get('selectedPointerRuntimeValueHex')}, "
            f"currentRootSelected={memory.get('selectedPointerEqualsCurrentRoot')}), "
            "but it is an idle sample, not a watchpoint/control-flow trace."
        )
    input_note = ""
    if input_probe:
        final_context = input_probe.get("finalSelectedPointerContext") or {}
        input_note = (
            " A bounded input probe found Hwanse2.exe windows and readable input memory, "
            f"held X keydown reached the DirectInput cache={input_probe.get('heldKeyPressedDetected')}, "
            f"synthetic X key events changed the selected pointer={input_probe.get('xEventChangedSelectedPointer')}, "
            f"and cached-key-buffer pokes changed it={input_probe.get('keyBufferPokeChangedSelectedPointer')} "
            f"to selector context {final_context.get('selector') or '-'}."
        )
    key_sequence_note = ""
    if key_sequence_probe:
        key_sequence_note = (
            " A bounded key-sequence probe tried "
            f"{key_sequence_probe.get('sequenceCount')} direct key-buffer sequence(s) "
            f"after startup wait {key_sequence_probe.get('startupWaitSeconds')}s; "
            f"route selector 2:0 reached={key_sequence_probe.get('anyReachedRouteSelectorContext')}."
        )
    key_sequence_prelude_note = ""
    if key_sequence_prelude_probe:
        observed = []
        for row in key_sequence_prelude_probe.get("sequences") or []:
            for selector in row.get("uniqueSelectorContexts") or []:
                if selector not in observed:
                    observed.append(selector)
        key_sequence_prelude_note = (
            " A supplemental input-path prelude key-sequence probe tried "
            f"{key_sequence_prelude_probe.get('sequenceCount')} sequence(s); "
            f"observed selectors={','.join(observed) or '-'}, "
            f"route selector 2:0 reached={key_sequence_prelude_probe.get('anyReachedRouteSelectorContext')}."
        )
    selected_pointer_poll_note = ""
    if selected_pointer_poll:
        selected_pointer_poll_note = (
            " A non-debugger selected-pointer poll sampled "
            f"{selected_pointer_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_poll.get('sequenceCount')} key-buffer sequence(s) at "
            f"{selected_pointer_poll.get('pollIntervalSeconds')}s intervals; "
            f"observed selectors={','.join(selected_pointer_poll.get('observedSelectors') or []) or '-'}, "
            f"route selector 2:0 reached={selected_pointer_poll.get('anyReachedRouteSelectorContext')}, "
            f"current root reached={selected_pointer_poll.get('anyReachedCurrentRoot')}."
        )
    selected_pointer_prelude_poll_note = ""
    if selected_pointer_prelude_poll:
        selected_pointer_prelude_poll_note = (
            " A supplemental input-path selected-pointer poll sampled "
            f"{selected_pointer_prelude_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_prelude_poll.get('sequenceCount')} key-buffer sequence(s) at "
            f"{selected_pointer_prelude_poll.get('pollIntervalSeconds')}s intervals; "
            f"observed selectors={','.join(selected_pointer_prelude_poll.get('observedSelectors') or []) or '-'}, "
            f"route selector 2:0 reached={selected_pointer_prelude_poll.get('anyReachedRouteSelectorContext')}, "
            f"current root reached={selected_pointer_prelude_poll.get('anyReachedCurrentRoot')}."
        )
    selected_pointer_long_poll_note = ""
    if selected_pointer_long_poll:
        selected_pointer_long_poll_note = (
            " A supplemental long selected-pointer poll sampled "
            f"{selected_pointer_long_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_long_poll.get('sequenceCount')} custom key-buffer sequence(s) at "
            f"{selected_pointer_long_poll.get('pollIntervalSeconds')}s intervals; "
            f"observed selectors={','.join(selected_pointer_long_poll.get('observedSelectors') or []) or '-'}, "
            f"route selector 2:0 reached={selected_pointer_long_poll.get('anyReachedRouteSelectorContext')}, "
            f"current root reached={selected_pointer_long_poll.get('anyReachedCurrentRoot')}."
        )
    selected_pointer_late_poll_note = ""
    if selected_pointer_late_poll:
        selected_pointer_late_poll_note = (
            " A supplemental late-start selected-pointer poll waited "
            f"{selected_pointer_late_poll.get('startupWaitSeconds')}s before input and sampled "
            f"{selected_pointer_late_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_late_poll.get('sequenceCount')} key-buffer sequence(s) at "
            f"{selected_pointer_late_poll.get('pollIntervalSeconds')}s intervals; "
            f"observed selectors={','.join(selected_pointer_late_poll.get('observedSelectors') or []) or '-'}, "
            f"route selector 2:0 reached={selected_pointer_late_poll.get('anyReachedRouteSelectorContext')}, "
            f"current root reached={selected_pointer_late_poll.get('anyReachedCurrentRoot')}."
        )
    route_watch_values_poll_note = ""
    if route_watch_values_poll:
        route_watch_values_poll_note = (
            " A supplemental route watch-value poll sampled "
            f"{route_watch_values_poll.get('sampleCount')} state(s) across "
            f"{route_watch_values_poll.get('sequenceCount')} key-buffer sequence(s); "
            f"observed selectors={','.join(route_watch_values_poll.get('observedSelectors') or []) or '-'}, "
            f"watchValues={watch_value_summary(route_watch_values_poll)}, "
            f"route selector 2:0 reached={route_watch_values_poll.get('anyReachedRouteSelectorContext')}."
        )
    selected_pointer_savedata_load_poll_note = ""
    if selected_pointer_savedata_load_poll:
        selected_pointer_savedata_load_poll_note = (
            " A supplemental SaveData-load selected-pointer poll placed a public captured save under "
            "SaveData\\savedat1.dat and sampled "
            f"{selected_pointer_savedata_load_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_savedata_load_poll.get('sequenceCount')} load-menu candidate sequence(s); "
            "input quality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_savedata_load_input_quality)}; "
            f"observed selectors={','.join(selected_pointer_savedata_load_poll.get('observedSelectors') or []) or '-'}, "
            f"route selector 2:0 reached={selected_pointer_savedata_load_poll.get('anyReachedRouteSelectorContext')}, "
            f"current root reached={selected_pointer_savedata_load_poll.get('anyReachedCurrentRoot')}."
        )
    selected_pointer_multislot_savedata_load_poll_note = ""
    if selected_pointer_multislot_savedata_load_poll:
        selected_pointer_multislot_savedata_load_poll_note = (
            " A supplemental multislot SaveData-load selected-pointer poll staged public captured saves under "
            "SaveData\\savedat1.dat..savedat3.dat and sampled "
            f"{selected_pointer_multislot_savedata_load_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_multislot_savedata_load_poll.get('sequenceCount')} load-menu candidate sequence(s); "
            "input quality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_multislot_savedata_load_input_quality)}; "
            "public selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_poll.get('publicSaveSelectors') or []) or '-'}, "
            f"observed selectors={','.join(selected_pointer_multislot_savedata_load_poll.get('observedSelectors') or []) or '-'}, "
            "observed public save selector="
            f"{selected_pointer_multislot_savedata_load_poll.get('anyReachedPublicSaveSelector')}, "
            f"route selector 2:0 reached={selected_pointer_multislot_savedata_load_poll.get('anyReachedRouteSelectorContext')}."
        )
    selected_pointer_multislot_savedata_load_case_alias_poll_note = ""
    if selected_pointer_multislot_savedata_load_case_alias_poll:
        selected_pointer_multislot_savedata_load_case_alias_poll_note = (
            " A supplemental case-alias multislot SaveData-load selected-pointer poll staged public captured saves under "
            "SaveData\\savedat1.dat..savedat3.dat while temporarily aliasing original archive case names, and sampled "
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s); "
            "input quality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_multislot_savedata_load_case_alias_input_quality)}; "
            "public selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, "
            "observed selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_case_alias_poll.get('observedSelectors') or []) or '-'}, "
            "observed public save selector="
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('anyReachedPublicSaveSelector')}, "
            f"route selector 2:0 reached={selected_pointer_multislot_savedata_load_case_alias_poll.get('anyReachedRouteSelectorContext')}."
        )
    selected_pointer_multislot_savedata_load_input_path_case_alias_poll_note = ""
    if selected_pointer_multislot_savedata_load_input_path_case_alias_poll:
        selected_pointer_multislot_savedata_load_input_path_case_alias_poll_note = (
            " A supplemental input-path case-alias multislot SaveData-load selected-pointer poll staged public captured "
            "saves under SaveData\\savedat1.dat..savedat3.dat, ran the input-path prelude, and sampled "
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s); "
            "input quality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_multislot_savedata_load_input_path_case_alias_input_quality)}; "
            "public selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, "
            "observed selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('observedSelectors') or []) or '-'}, "
            "observed public save selector="
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('anyReachedPublicSaveSelector')}, "
            f"route selector 2:0 reached={selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('anyReachedRouteSelectorContext')}."
        )
    selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_note = ""
    if selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll:
        selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_note = (
            " A supplemental standalone synthetic selector 2:0 poll staged a save-shaped file under "
            "SaveData\\savedat1.dat, ran the input-path prelude with case aliases, and sampled "
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s); "
            "input quality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_synthetic_selector_2_0_input_path_case_alias_input_quality)}; "
            "staged selectors="
            f"{','.join(selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, "
            "observed selectors="
            f"{','.join(selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('observedSelectors') or []) or '-'}, "
            "observed staged selector="
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('anyReachedPublicSaveSelector')}, "
            f"route selector 2:0 reached={selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('anyReachedRouteSelectorContext')}. "
            "This leaves the standalone synthetic file non-promoting and contrasts with the patched public-base diagnostic."
        )
    selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_note = ""
    if selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll:
        selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_note = (
            " A supplemental patched public-base selector 2:0 diagnostic poll staged a public save with only "
            "selector/position bytes patched under SaveData\\savedat1.dat, ran the input-path prelude with case aliases, and sampled "
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('sampleCount')} state(s) across "
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s); "
            "input quality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_patched_public_selector_2_0_input_path_case_alias_input_quality)}; "
            "staged selectors="
            f"{','.join(selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, "
            "observed selectors="
            f"{','.join(selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('observedSelectors') or []) or '-'}, "
            "observed staged selector="
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('anyReachedPublicSaveSelector')}, "
            f"route selector 2:0 reached={selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('anyReachedRouteSelectorContext')}. "
            "This proves the current load path can select a constructed 2:0 save-shaped diagnostic, but not a captured gameplay save."
        )
    save_file_io_probe_note = ""
    if save_file_io_probe:
        save_file_io_probe_note = (
            " A supplemental SaveData file-I/O trace probe placed the same public save under "
            f"{(save_file_io_probe.get('temporarySave') or {}).get('target')} with backend="
            f"{save_file_io_probe.get('backend')}; inputTraceUsable={save_file_io_probe.get('inputTraceUsable')}, "
            f"pidRuns={save_file_io_probe.get('sequenceWithPidCount')}/{save_file_io_probe.get('sequenceCount')}, "
            f"keyWriteRuns={save_file_io_probe.get('sequenceWithKeyWritesCount')}/{save_file_io_probe.get('sequenceCount')}, "
            f"savedat1Access={save_file_io_probe.get('anySavedat1DatAccess')}. This is backend-feasibility evidence only."
        )
    save_file_io_strace_probe_note = ""
    if save_file_io_strace_probe:
        save_file_io_strace_probe_note = (
            " A supplemental strace SaveData file-I/O probe placed the same public save under "
            f"{(save_file_io_strace_probe.get('temporarySave') or {}).get('target')} with backend="
            f"{save_file_io_strace_probe.get('backend')}; inputTraceUsable="
            f"{save_file_io_strace_probe.get('inputTraceUsable')}, "
            f"pidRuns={save_file_io_strace_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_probe.get('sequenceCount')}, "
            f"savedat1Access={save_file_io_strace_probe.get('anySavedat1DatAccess')}. "
            "This is backend-feasibility evidence only."
        )
    save_file_io_strace_attach_probe_note = ""
    if save_file_io_strace_attach_probe:
        save_file_io_strace_attach_probe_note = (
            " A supplemental attached strace SaveData file-I/O probe placed the same public save under "
            f"{(save_file_io_strace_attach_probe.get('temporarySave') or {}).get('target')} with backend="
            f"{save_file_io_strace_attach_probe.get('backend')}; inputTraceUsable="
            f"{save_file_io_strace_attach_probe.get('inputTraceUsable')}, "
            f"pidRuns={save_file_io_strace_attach_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_attach_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_attach_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_attach_probe.get('sequenceCount')}, "
            f"savedat1Access={save_file_io_strace_attach_probe.get('anySavedat1DatAccess')}. "
            "This makes the bounded file-I/O window usable, but absent savedat lines still only cover that load-menu candidate sequence."
        )
    save_file_io_strace_attach_load_candidates_probe_note = ""
    if save_file_io_strace_attach_load_candidates_probe:
        save_file_io_strace_attach_load_candidates_probe_note = (
            " A broader attached strace SaveData file-I/O probe placed the same public save under "
            f"{(save_file_io_strace_attach_load_candidates_probe.get('temporarySave') or {}).get('target')} with backend="
            f"{save_file_io_strace_attach_load_candidates_probe.get('backend')}; inputTraceUsable="
            f"{save_file_io_strace_attach_load_candidates_probe.get('inputTraceUsable')}, "
            f"pidRuns={save_file_io_strace_attach_load_candidates_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceCount')}, "
            f"savedat1Access={save_file_io_strace_attach_load_candidates_probe.get('anySavedat1DatAccess')}. "
            "This makes all covered load-menu candidate file-I/O windows usable, but it still only rules out savedat access for those bounded inputs."
        )
    save_file_io_strace_attach_load_candidates_case_alias_probe_note = ""
    if save_file_io_strace_attach_load_candidates_case_alias_probe:
        save_file_io_strace_attach_load_candidates_case_alias_probe_note = (
            " A case-alias attached strace SaveData file-I/O probe placed the same public save under "
            f"{(save_file_io_strace_attach_load_candidates_case_alias_probe.get('temporarySave') or {}).get('target')} with backend="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('backend')}; caseAliases="
            f"{(save_file_io_strace_attach_load_candidates_case_alias_probe.get('caseAliases') or {}).get('enabled')}, "
            f"inputTraceUsable={save_file_io_strace_attach_load_candidates_case_alias_probe.get('inputTraceUsable')}, "
            f"pidRuns={save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceCount')}, "
            f"savedat1Access={save_file_io_strace_attach_load_candidates_case_alias_probe.get('anySavedat1DatAccess')}. "
            "The aliases reduce resource lookup trace noise, but no savedat access was observed in the same bounded windows."
        )
    if not base_environment_ready:
        conclusion = (
            "The current exe.dev VM cannot run the required Hwanse2.exe runtime producer trace yet because "
            "one or more Wine/debugger/headless prerequisites still fail. The exact watchpoints and "
            "breakpoints are recorded so the trace can be retried after the environment is fixed."
        )
    elif execution_probe and not execution_probe.get("canCaptureTraceNow"):
        control_probe_failed = any("notepad" in item for item in execution_probe.get("blockers") or [])
        conclusion = (
            "Wine, winedbg, Xvfb, gdb, and i386 package prerequisites are installed, but the bounded "
            "execution probe still fails before a stable route trace can be captured. "
            + (
                "The notepad control probes fail too, so this is a qemu-i386/WineDbg debugger-path issue rather than Hwanse-specific route proof."
                if control_probe_failed
                else "Treat the blocker as a runtime execution/debugger failure, not as route proof."
            )
            + snapshot_note
            + input_note
            + key_sequence_note
            + key_sequence_prelude_note
            + selected_pointer_poll_note
            + selected_pointer_prelude_poll_note
            + selected_pointer_long_poll_note
            + selected_pointer_late_poll_note
            + route_watch_values_poll_note
            + selected_pointer_savedata_load_poll_note
            + selected_pointer_multislot_savedata_load_poll_note
            + selected_pointer_multislot_savedata_load_case_alias_poll_note
            + selected_pointer_multislot_savedata_load_input_path_case_alias_poll_note
            + selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_note
            + selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_note
            + save_file_io_probe_note
            + save_file_io_strace_probe_note
            + save_file_io_strace_attach_probe_note
            + save_file_io_strace_attach_load_candidates_probe_note
            + save_file_io_strace_attach_load_candidates_case_alias_probe_note
        )
    else:
        conclusion = (
            "The required Wine/winedbg/Xvfb commands appear available; run the recorded watchpoint plan "
            "before promoting map1_01a->map2_02d."
            + snapshot_note
            + input_note
            + key_sequence_note
            + key_sequence_prelude_note
            + selected_pointer_poll_note
            + selected_pointer_prelude_poll_note
            + selected_pointer_long_poll_note
            + selected_pointer_late_poll_note
            + route_watch_values_poll_note
            + selected_pointer_savedata_load_poll_note
            + selected_pointer_multislot_savedata_load_poll_note
            + selected_pointer_multislot_savedata_load_case_alias_poll_note
            + selected_pointer_multislot_savedata_load_input_path_case_alias_poll_note
            + selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_note
            + selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_note
            + save_file_io_probe_note
            + save_file_io_strace_probe_note
            + save_file_io_strace_attach_probe_note
            + save_file_io_strace_attach_load_candidates_probe_note
            + save_file_io_strace_attach_load_candidates_case_alias_probe_note
        )
    audit_gap = (
        (
            (
                "The current VM has Wine tooling installed, but qemu-i386/WineDbg control probes fail even for notepad, so the Hwanse2.exe runtime trace cannot be captured here yet. "
                "A non-debugger /proc memory snapshot can read Hwanse2.exe globals, but the latest idle sample is not route-path proof."
                if memory_snapshot and (memory_snapshot.get("memory") or {}).get("canReadProcessMemory")
                else "The current VM has Wine tooling installed, but qemu-i386/WineDbg control probes fail even for notepad, so the Hwanse2.exe runtime trace cannot be captured here yet."
            )
            if any("notepad" in item for item in execution_probe.get("blockers") or [])
            else "The current VM has Wine tooling installed, but the Hwanse2.exe/winedbg execution probe still fails before the runtime trace can be captured."
        )
        if execution_probe and not execution_probe.get("canCaptureTraceNow")
        else "The current VM cannot run the required Hwanse2.exe runtime trace yet."
        if not can_run_now
        else "The runtime trace environment is available, but the trace has not been captured yet."
    )
    if qemu_wine_loader_smoke["ok"] and not qemu_wine_child_exec_smoke["ok"]:
        audit_gap += (
            f" Direct qemu-i386 can run the Wine loader smoke ({qemu_wine_loader_smoke['firstLine']}), "
            f"but CLI child exec smoke ok={qemu_wine_child_exec_smoke['ok']}; "
            f"{'transparent binfmt is still required' if not qemu_i386_binfmt['enabled'] else 'the child smoke still needs investigation'}."
        )
    if binfmt_consistency.get("executionProbeRegistered") is True:
        audit_gap += (
            " Embedded execution-probe binfmt view: "
            f"registered={binfmt_consistency.get('executionProbeRegistered')}, "
            f"enabled={binfmt_consistency.get('executionProbeEnabled')}; "
            f"summary view enabled={binfmt_consistency.get('summaryEnabled')}. "
            f"{binfmt_consistency.get('conclusion')}"
        )
    if qemu_wine_loader_smoke["ok"] and qemu_wine_child_exec_smoke["ok"]:
        audit_gap += (
            f" Direct qemu-i386 can run both the Wine loader smoke ({qemu_wine_loader_smoke['firstLine']}) "
            f"and CLI child exec smoke ({qemu_wine_child_exec_smoke['firstLine']}); the remaining blocker is the WineDbg/runtime trace path."
        )
    if input_probe and input_probe.get("heldKeyPressedDetected") is True:
        audit_gap += (
            " A bounded X/input-buffer probe confirms Wine DirectInput can see held synthetic keydowns, "
            "but ordinary X key events did not move the idle selected pointer. "
        )
        final_context = input_probe.get("finalSelectedPointerContext") or {}
        if input_probe.get("keyBufferPokeChangedSelectedPointer") is True:
            audit_gap += (
                f"Direct cached-key-buffer pokes moved the selected pointer only to non-route selector "
                f"{final_context.get('selector') or '-'}, not current selector 2:0. "
            )
        audit_gap += "This remains input-path diagnostic evidence, not route proof."
    if key_sequence_probe:
        audit_gap += (
            f" A bounded direct key-buffer sequence probe covered {key_sequence_probe.get('sequenceCount')} sequence(s) "
            f"after {key_sequence_probe.get('startupWaitSeconds')}s startup wait and reached route selector 2:0="
            f"{key_sequence_probe.get('anyReachedRouteSelectorContext')}; it remains non-promoting diagnostic evidence."
        )
    if key_sequence_prelude_probe:
        observed = []
        for row in key_sequence_prelude_probe.get("sequences") or []:
            for selector in row.get("uniqueSelectorContexts") or []:
                if selector not in observed:
                    observed.append(selector)
        audit_gap += (
            f" A supplemental input-path prelude key-buffer probe covered {key_sequence_prelude_probe.get('sequenceCount')} sequence(s), "
            f"observed selectors={','.join(observed) or '-'}, and reached route selector 2:0="
            f"{key_sequence_prelude_probe.get('anyReachedRouteSelectorContext')}; it is diagnostic-only."
        )
    if selected_pointer_poll:
        audit_gap += (
            f" A non-debugger selected-pointer poll covered {selected_pointer_poll.get('sampleCount')} sample(s) "
            f"across {selected_pointer_poll.get('sequenceCount')} direct key-buffer sequence(s), observed selectors="
            f"{','.join(selected_pointer_poll.get('observedSelectors') or []) or '-'}, and reached route selector 2:0="
            f"{selected_pointer_poll.get('anyReachedRouteSelectorContext')}; it still does not replace a watchpoint trace."
        )
    if selected_pointer_prelude_poll:
        audit_gap += (
            f" A supplemental input-path selected-pointer poll covered {selected_pointer_prelude_poll.get('sampleCount')} sample(s) "
            f"across {selected_pointer_prelude_poll.get('sequenceCount')} direct key-buffer sequence(s), observed selectors="
            f"{','.join(selected_pointer_prelude_poll.get('observedSelectors') or []) or '-'}, and reached route selector 2:0="
            f"{selected_pointer_prelude_poll.get('anyReachedRouteSelectorContext')}; it is also diagnostic-only."
        )
    if selected_pointer_long_poll:
        audit_gap += (
            f" A supplemental long selected-pointer poll covered {selected_pointer_long_poll.get('sampleCount')} sample(s) "
            f"across {selected_pointer_long_poll.get('sequenceCount')} custom key-buffer sequence(s), observed selectors="
            f"{','.join(selected_pointer_long_poll.get('observedSelectors') or []) or '-'}, and reached route selector 2:0="
            f"{selected_pointer_long_poll.get('anyReachedRouteSelectorContext')}; it is also diagnostic-only."
        )
    if selected_pointer_late_poll:
        audit_gap += (
            f" A supplemental late-start selected-pointer poll waited {selected_pointer_late_poll.get('startupWaitSeconds')}s, "
            f"covered {selected_pointer_late_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_late_poll.get('sequenceCount')} key-buffer sequence(s), observed selectors="
            f"{','.join(selected_pointer_late_poll.get('observedSelectors') or []) or '-'}, and reached route selector 2:0="
            f"{selected_pointer_late_poll.get('anyReachedRouteSelectorContext')}; it is also diagnostic-only."
        )
    if route_watch_values_poll:
        audit_gap += (
            f" A supplemental route watch-value poll covered {route_watch_values_poll.get('sampleCount')} sample(s) "
            f"across {route_watch_values_poll.get('sequenceCount')} key-buffer sequence(s), observed selectors="
            f"{','.join(route_watch_values_poll.get('observedSelectors') or []) or '-'}, watchValues="
            f"{watch_value_summary(route_watch_values_poll)}, and reached route selector 2:0="
            f"{route_watch_values_poll.get('anyReachedRouteSelectorContext')}; it is also diagnostic-only."
        )
    if selected_pointer_savedata_load_poll:
        audit_gap += (
            f" A supplemental SaveData-load poll placed a public captured save under SaveData\\savedat1.dat and covered "
            f"{selected_pointer_savedata_load_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_savedata_load_poll.get('sequenceCount')} load-menu candidate sequence(s), inputQuality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_savedata_load_input_quality)}, observed selectors="
            f"{','.join(selected_pointer_savedata_load_poll.get('observedSelectors') or []) or '-'}, and reached route selector 2:0="
            f"{selected_pointer_savedata_load_poll.get('anyReachedRouteSelectorContext')}; it did not prove the original load-menu path."
        )
    if selected_pointer_multislot_savedata_load_poll:
        audit_gap += (
            f" A supplemental multislot SaveData-load poll staged public captured saves under SaveData\\savedat1.dat..savedat3.dat and covered "
            f"{selected_pointer_multislot_savedata_load_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_multislot_savedata_load_poll.get('sequenceCount')} load-menu candidate sequence(s), inputQuality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_multislot_savedata_load_input_quality)}, publicSelectors="
            f"{','.join(selected_pointer_multislot_savedata_load_poll.get('publicSaveSelectors') or []) or '-'}, observed selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_poll.get('observedSelectors') or []) or '-'}, observedPublic="
            f"{selected_pointer_multislot_savedata_load_poll.get('anyReachedPublicSaveSelector')}, and reached route selector 2:0="
            f"{selected_pointer_multislot_savedata_load_poll.get('anyReachedRouteSelectorContext')}; it did not prove the original load-menu path."
        )
    if selected_pointer_multislot_savedata_load_case_alias_poll:
        audit_gap += (
            " A supplemental case-alias multislot SaveData-load poll staged public captured saves under "
            "SaveData\\savedat1.dat..savedat3.dat and temporarily aliased original resource archive case names; it covered "
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s), inputQuality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_multislot_savedata_load_case_alias_input_quality)}, publicSelectors="
            f"{','.join(selected_pointer_multislot_savedata_load_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, observed selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_case_alias_poll.get('observedSelectors') or []) or '-'}, observedPublic="
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('anyReachedPublicSaveSelector')}, and reached route selector 2:0="
            f"{selected_pointer_multislot_savedata_load_case_alias_poll.get('anyReachedRouteSelectorContext')}; aliases did not make the public saves or route selector reachable."
        )
    if selected_pointer_multislot_savedata_load_input_path_case_alias_poll:
        audit_gap += (
            " A supplemental input-path case-alias multislot SaveData-load poll staged public captured saves under "
            "SaveData\\savedat1.dat..savedat3.dat, ran the input-path prelude, and covered "
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s), inputQuality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_multislot_savedata_load_input_path_case_alias_input_quality)}, publicSelectors="
            f"{','.join(selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, observed selectors="
            f"{','.join(selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('observedSelectors') or []) or '-'}, observedPublic="
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('anyReachedPublicSaveSelector')}, and reached route selector 2:0="
            f"{selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get('anyReachedRouteSelectorContext')}; this remains non-route load-path evidence, not current route selector proof."
        )
    if selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll:
        audit_gap += (
            " A supplemental standalone synthetic selector 2:0 poll staged a save-shaped file under SaveData\\savedat1.dat, "
            "ran the input-path prelude with case aliases, and covered "
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s), inputQuality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_synthetic_selector_2_0_input_path_case_alias_input_quality)}, stagedSelectors="
            f"{','.join(selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, observed selectors="
            f"{','.join(selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('observedSelectors') or []) or '-'}, observedStaged="
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('anyReachedPublicSaveSelector')}, and reached route selector 2:0="
            f"{selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get('anyReachedRouteSelectorContext')}; this keeps standalone synthetic selector 2:0 non-promoting."
        )
    if selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll:
        audit_gap += (
            " A supplemental patched public-base selector 2:0 diagnostic poll staged a public save with only selector/position bytes patched "
            "under SaveData\\savedat1.dat, ran the input-path prelude with case aliases, and covered "
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('sampleCount')} sample(s) across "
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('sequenceCount')} load-menu candidate sequence(s), inputQuality="
            f"{selected_pointer_poll_input_quality_brief(selected_pointer_patched_public_selector_2_0_input_path_case_alias_input_quality)}, stagedSelectors="
            f"{','.join(selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('publicSaveSelectors') or []) or '-'}, observed selectors="
            f"{','.join(selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('observedSelectors') or []) or '-'}, observedStaged="
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('anyReachedPublicSaveSelector')}, and reached route selector 2:0="
            f"{selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get('anyReachedRouteSelectorContext')}; this proves the load path can select a constructed 2:0 save-shaped diagnostic, but it is not a captured gameplay save."
        )
    if save_file_io_probe:
        audit_gap += (
            f" A supplemental SaveData file-I/O trace probe ({save_file_io_probe.get('backend')}) placed a public "
            f"save under {(save_file_io_probe.get('temporarySave') or {}).get('target')} but inputTraceUsable="
            f"{save_file_io_probe.get('inputTraceUsable')} (pidRuns={save_file_io_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_probe.get('sequenceCount')}, keyWriteRuns={save_file_io_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_probe.get('sequenceCount')}); absent savedat lines remain backend-feasibility evidence, not load-menu proof."
        )
    if save_file_io_strace_probe:
        audit_gap += (
            f" A supplemental SaveData file-I/O trace probe ({save_file_io_strace_probe.get('backend')}) placed a public "
            f"save under {(save_file_io_strace_probe.get('temporarySave') or {}).get('target')} but inputTraceUsable="
            f"{save_file_io_strace_probe.get('inputTraceUsable')} (pidRuns="
            f"{save_file_io_strace_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_probe.get('sequenceCount')}); absent savedat lines remain backend-feasibility evidence, not load-menu proof."
        )
    if save_file_io_strace_attach_probe:
        audit_gap += (
            f" A supplemental attached SaveData file-I/O trace probe ({save_file_io_strace_attach_probe.get('backend')}) placed a public "
            f"save under {(save_file_io_strace_attach_probe.get('temporarySave') or {}).get('target')} and had inputTraceUsable="
            f"{save_file_io_strace_attach_probe.get('inputTraceUsable')} (pidRuns="
            f"{save_file_io_strace_attach_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_attach_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_attach_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_attach_probe.get('sequenceCount')}, matchedFileIoLines="
            f"{save_file_io_strace_attach_probe.get('matchedLineCount')}, savedat1Access="
            f"{save_file_io_strace_attach_probe.get('anySavedat1DatAccess')}); this rules out savedat file access only for the bounded attached load-menu candidate window, not the full load-menu path."
        )
    if save_file_io_strace_attach_load_candidates_probe:
        audit_gap += (
            f" A broader attached SaveData file-I/O trace probe ({save_file_io_strace_attach_load_candidates_probe.get('backend')}) placed a public "
            f"save under {(save_file_io_strace_attach_load_candidates_probe.get('temporarySave') or {}).get('target')} and had inputTraceUsable="
            f"{save_file_io_strace_attach_load_candidates_probe.get('inputTraceUsable')} (pidRuns="
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_attach_load_candidates_probe.get('sequenceCount')}, matchedFileIoLines="
            f"{save_file_io_strace_attach_load_candidates_probe.get('matchedLineCount')}, savedat1Access="
            f"{save_file_io_strace_attach_load_candidates_probe.get('anySavedat1DatAccess')}); this rules out savedat file access across the covered bounded load-menu candidate windows, not the full load-menu path."
        )
    if save_file_io_strace_attach_load_candidates_case_alias_probe:
        audit_gap += (
            f" A case-alias attached SaveData file-I/O trace probe ({save_file_io_strace_attach_load_candidates_case_alias_probe.get('backend')}) placed a public "
            f"save under {(save_file_io_strace_attach_load_candidates_case_alias_probe.get('temporarySave') or {}).get('target')} with temporary resource archive aliases and had inputTraceUsable="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('inputTraceUsable')} (pidRuns="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceWithPidCount')}/"
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceCount')}, keyWriteRuns="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceWithKeyWritesCount')}/"
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('sequenceCount')}, matchedFileIoLines="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('matchedLineCount')}, savedat1Access="
            f"{save_file_io_strace_attach_load_candidates_case_alias_probe.get('anySavedat1DatAccess')}); aliases reduce archive lookup noise but still do not prove full load-menu reachability."
        )
    failed_runtime_trace_gate_ids = []
    if can_run_now is not True:
        failed_runtime_trace_gate_ids.append("runtime-trace-capture-unavailable")
    if (execution_probe or {}).get("canCaptureTraceNow") is not True:
        failed_runtime_trace_gate_ids.append("stable-watchpoint-session-unavailable")
    failed_runtime_trace_gate_ids.append("equivalent-selected-root-proof-missing")
    missing_evidence = [
        "stable runtime trace capture session for Hwanse2.exe",
        "watchpoint or breakpoint path that observes selected pointer 0x0059de30 on the route path",
        "equivalent selected-root proof if runtime tracing remains unavailable",
    ]
    evidence_refs = existing_evidence_refs()
    return {
        "objective": "runtime trace feasibility for Hwanse2.exe route blocker proof",
        "proofFound": False,
        "failedRuntimeTraceGateIds": failed_runtime_trace_gate_ids,
        "missingEvidence": missing_evidence,
        "evidenceRefs": evidence_refs,
        "evidenceRefCount": len(evidence_refs),
        "canRunRuntimeTraceNow": can_run_now,
        "blockers": blockers,
        "commands": commands,
        "wineLoaderSmoke": wine_loader_smoke,
        "qemuWineLoaderSmoke": qemu_wine_loader_smoke,
        "qemuWineChildExecSmoke": qemu_wine_child_exec_smoke,
        "qemuI386Binfmt": qemu_i386_binfmt,
        "binfmtConsistency": binfmt_consistency,
        "dpkgArchitecture": arch,
        "dpkgForeignArchitectures": foreign_arches.split() if foreign_arches else [],
        "aptPackages": {
            "wine": wine_meta,
            "wine32": wine32,
            "wine64-tools": wine64_tools,
            "qemu-user-binfmt": qemu_user_binfmt,
            "gdb-multiarch": gdb_multiarch,
        },
        "executionProbe": execution_probe,
        "memorySnapshot": memory_snapshot,
        "inputProbe": input_probe,
        "keySequenceProbe": key_sequence_probe,
        "keySequencePreludeProbe": key_sequence_prelude_probe,
        "selectedPointerPoll": selected_pointer_poll,
        "selectedPointerPreludePoll": selected_pointer_prelude_poll,
        "selectedPointerLongPoll": selected_pointer_long_poll,
        "selectedPointerLatePoll": selected_pointer_late_poll,
        "routeWatchValuesPoll": route_watch_values_poll,
        "selectedPointerSavedataLoadPoll": selected_pointer_savedata_load_poll,
        "selectedPointerSavedataLoadInputQuality": selected_pointer_savedata_load_input_quality,
        "selectedPointerMultislotSavedataLoadPoll": selected_pointer_multislot_savedata_load_poll,
        "selectedPointerMultislotSavedataLoadInputQuality": selected_pointer_multislot_savedata_load_input_quality,
        "selectedPointerMultislotSavedataLoadCaseAliasPoll": selected_pointer_multislot_savedata_load_case_alias_poll,
        "selectedPointerMultislotSavedataLoadCaseAliasInputQuality": selected_pointer_multislot_savedata_load_case_alias_input_quality,
        "selectedPointerMultislotSavedataLoadInputPathCaseAliasPoll": selected_pointer_multislot_savedata_load_input_path_case_alias_poll,
        "selectedPointerMultislotSavedataLoadInputPathCaseAliasInputQuality": selected_pointer_multislot_savedata_load_input_path_case_alias_input_quality,
        "selectedPointerSyntheticSelector20InputPathCaseAliasPoll": selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll,
        "selectedPointerSyntheticSelector20InputPathCaseAliasInputQuality": selected_pointer_synthetic_selector_2_0_input_path_case_alias_input_quality,
        "selectedPointerPatchedPublicSelector20InputPathCaseAliasPoll": selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll,
        "selectedPointerPatchedPublicSelector20InputPathCaseAliasInputQuality": selected_pointer_patched_public_selector_2_0_input_path_case_alias_input_quality,
        "saveFileIoProbe": save_file_io_probe,
        "saveFileIoStraceProbe": save_file_io_strace_probe,
        "saveFileIoStraceAttachProbe": save_file_io_strace_attach_probe,
        "saveFileIoStraceAttachLoadCandidatesProbe": save_file_io_strace_attach_load_candidates_probe,
        "saveFileIoStraceAttachLoadCandidatesCaseAliasProbe": save_file_io_strace_attach_load_candidates_case_alias_probe,
        "tracePoints": trace_points,
        "commandsToTry": commands_to_try,
        "promotionStatus": "blocked" if not can_run_now else "trace-required",
        "auditGap": audit_gap,
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Runtime Trace Feasibility",
        "",
        f"- objective: {summary['objective']}",
        f"- proof found: {summary['proofFound']}",
        f"- failed runtime trace gates: `{', '.join(summary.get('failedRuntimeTraceGateIds') or []) or '-'}`",
        f"- missing evidence count: {len(summary.get('missingEvidence') or [])}",
        f"- evidence refs: {summary.get('evidenceRefCount')}",
        f"- can run runtime trace now: {summary['canRunRuntimeTraceNow']}",
        f"- dpkg architecture: `{summary['dpkgArchitecture']}`",
        f"- foreign architectures: `{', '.join(summary['dpkgForeignArchitectures']) or '-'}`",
        f"- wine loader smoke: `{summary['wineLoaderSmoke']['firstLine'] or 'failed'}`",
        f"- qemu wine loader smoke: `{summary['qemuWineLoaderSmoke']['firstLine'] or 'failed'}`",
        f"- qemu wine child exec smoke: `{summary['qemuWineChildExecSmoke']['firstLine'] or 'failed'}`",
        f"- qemu-i386 binfmt: `{summary['qemuI386Binfmt']['rawFirstLine'] or '-'}`",
        "- binfmt consistency: "
        f"summary enabled `{summary.get('binfmtConsistency', {}).get('summaryEnabled')}`, "
        f"execution probe enabled `{summary.get('binfmtConsistency', {}).get('executionProbeEnabled')}`",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        summary["conclusion"],
        "",
        "## Missing Evidence",
        "",
        *[f"- {item}" for item in summary.get("missingEvidence") or []],
        "",
        "## Evidence Refs",
        "",
    ]
    lines.extend(
        f"- `{row['path']}`: `{', '.join(row.get('fields') or [])}`"
        for row in summary.get("evidenceRefs") or []
    )
    lines.extend([
        "",
        "## Tool Availability",
        "",
        "| command | available | path |",
        "| --- | --- | --- |",
    ])
    for row in summary["commands"].values():
        lines.append(f"| `{row['command']}` | {row['available']} | `{row.get('path') or '-'}` |")
    lines.extend([
        "",
        "## Apt Packages",
        "",
        "| package | installed | candidate |",
        "| --- | --- | --- |",
    ])
    for row in summary["aptPackages"].values():
        lines.append(f"| `{row['package']}` | `{row.get('installed') or '-'}` | `{row.get('candidate') or '-'}` |")
    lines.extend([
        "",
        "## QEMU Wine Smoke",
        "",
        "| check | status | first line |",
        "| --- | ---: | --- |",
        (
            f"| `{summary['qemuWineLoaderSmoke']['command']}` | "
            f"{summary['qemuWineLoaderSmoke']['status']} | "
            f"`{summary['qemuWineLoaderSmoke']['firstLine'] or '-'}` |"
        ),
        (
            f"| `{summary['qemuWineChildExecSmoke']['command']}` | "
            f"{summary['qemuWineChildExecSmoke']['status']} | "
            f"`{summary['qemuWineChildExecSmoke']['firstLine'] or '-'}` |"
        ),
    ])
    if summary.get("executionProbe"):
        probe = summary["executionProbe"]
        lines.extend([
            "",
            "## Execution Probe",
            "",
            f"- can capture trace now: {probe.get('canCaptureTraceNow')}",
            f"- report: `out/runtime_trace_execution_probe.json`",
            "",
        ])
        lines.extend(f"- {item}" for item in probe.get("blockers") or ["none"])
    if summary.get("memorySnapshot"):
        snapshot = summary["memorySnapshot"]
        memory = snapshot.get("memory") or {}
        lines.extend([
            "",
            "## Process Memory Snapshot",
            "",
            f"- can read process memory: {memory.get('canReadProcessMemory')}",
            f"- loaded base: `{snapshot.get('loadedBaseHex') or '-'}`",
            f"- selected pointer static value: `{memory.get('selectedPointerStaticValueHex') or '-'}`",
            f"- selected pointer equals current root: {memory.get('selectedPointerEqualsCurrentRoot')}",
            f"- current root relocation looks valid: {memory.get('currentRootRelocationLooksValid')}",
            f"- report: `out/runtime_memory_snapshot.json`",
            "",
        ])
    if summary.get("inputProbe"):
        probe = summary["inputProbe"]
        initial = probe.get("initialSample") or {}
        final = probe.get("finalSample") or {}
        lines.extend([
            "",
            "## Input Path Probe",
            "",
            f"- xdotool path: `{probe.get('xdotoolPath') or '-'}`",
            f"- loaded base: `{probe.get('loadedBaseHex') or '-'}`",
            f"- baseline selected pointer: `{probe.get('baselineSelectedPointerStaticHex') or '-'}`",
            f"- baseline selector context: `{(probe.get('baselineSelectedPointerContext') or {}).get('selector') or '-'}`",
            f"- initial selected pointer: `{initial.get('selectedPointerStaticHex') or '-'}`",
            f"- final selected pointer: `{final.get('selectedPointerStaticHex') or '-'}`",
            f"- final selector context: `{(probe.get('finalSelectedPointerContext') or {}).get('selector') or '-'}`",
            f"- held-key pressed detected: {probe.get('heldKeyPressedDetected')}",
            f"- held-key changed selected pointer: {probe.get('heldKeyChangedSelectedPointer')}",
            f"- X event changed selected pointer: {probe.get('xEventChangedSelectedPointer')}",
            f"- key-buffer poke changed selected pointer: {probe.get('keyBufferPokeChangedSelectedPointer')}",
            f"- report: `out/runtime_input_path_probe.json`",
            "",
        ])
    if summary.get("keySequenceProbe"):
        probe = summary["keySequenceProbe"]
        lines.extend([
            "",
            "## Key Sequence Probe",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_key_sequence_probe.json`",
            "",
        ])
    if summary.get("keySequencePreludeProbe"):
        probe = summary["keySequencePreludeProbe"]
        observed = []
        for row in probe.get("sequences") or []:
            for selector in row.get("uniqueSelectorContexts") or []:
                if selector not in observed:
                    observed.append(selector)
        lines.extend([
            "",
            "## Key Sequence Prelude Probe",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- observed selectors: `{', '.join(observed) or '-'}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_key_sequence_prelude_probe.json`",
            "",
        ])
    if summary.get("selectedPointerPoll"):
        probe = summary["selectedPointerPoll"]
        lines.extend([
            "",
            "## Selected-Pointer Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_poll.json`",
            "",
        ])
    if summary.get("selectedPointerPreludePoll"):
        probe = summary["selectedPointerPreludePoll"]
        lines.extend([
            "",
            "## Selected-Pointer Prelude Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_prelude_poll.json`",
            "",
        ])
    if summary.get("selectedPointerLongPoll"):
        probe = summary["selectedPointerLongPoll"]
        lines.extend([
            "",
            "## Selected-Pointer Long Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_long_poll.json`",
            "",
        ])
    if summary.get("selectedPointerLatePoll"):
        probe = summary["selectedPointerLatePoll"]
        lines.extend([
            "",
            "## Selected-Pointer Late Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_late_poll.json`",
            "",
        ])
    if summary.get("selectedPointerSavedataLoadPoll"):
        probe = summary["selectedPointerSavedataLoadPoll"]
        quality = summary.get("selectedPointerSavedataLoadInputQuality") or {}
        lines.extend([
            "",
            "## Selected-Pointer SaveData Load Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- input quality: `{selected_pointer_poll_input_quality_brief(quality)}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_savedata_load_poll.json`",
            "",
        ])
    if summary.get("selectedPointerMultislotSavedataLoadPoll"):
        probe = summary["selectedPointerMultislotSavedataLoadPoll"]
        quality = summary.get("selectedPointerMultislotSavedataLoadInputQuality") or {}
        lines.extend([
            "",
            "## Selected-Pointer Multislot SaveData Load Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- input quality: `{selected_pointer_poll_input_quality_brief(quality)}`",
            f"- public save selectors: `{', '.join(probe.get('publicSaveSelectors') or []) or '-'}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- observed public save selectors: `{', '.join(probe.get('observedPublicSaveSelectors') or []) or '-'}`",
            f"- any reached public save selector: {probe.get('anyReachedPublicSaveSelector')}",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_multislot_savedata_load_poll.json`",
            "",
        ])
    if summary.get("selectedPointerMultislotSavedataLoadCaseAliasPoll"):
        probe = summary["selectedPointerMultislotSavedataLoadCaseAliasPoll"]
        quality = summary.get("selectedPointerMultislotSavedataLoadCaseAliasInputQuality") or {}
        lines.extend([
            "",
            "## Selected-Pointer Multislot SaveData Load Case-Alias Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- case aliases: enabled={(probe.get('caseAliases') or {}).get('enabled')}; removed={','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-'}",
            f"- input quality: `{selected_pointer_poll_input_quality_brief(quality)}`",
            f"- public save selectors: `{', '.join(probe.get('publicSaveSelectors') or []) or '-'}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- observed public save selectors: `{', '.join(probe.get('observedPublicSaveSelectors') or []) or '-'}`",
            f"- any reached public save selector: {probe.get('anyReachedPublicSaveSelector')}",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_multislot_savedata_load_case_alias_poll.json`",
            "",
        ])
    if summary.get("selectedPointerMultislotSavedataLoadInputPathCaseAliasPoll"):
        probe = summary["selectedPointerMultislotSavedataLoadInputPathCaseAliasPoll"]
        quality = summary.get("selectedPointerMultislotSavedataLoadInputPathCaseAliasInputQuality") or {}
        lines.extend([
            "",
            "## Selected-Pointer Multislot SaveData Load Input-Path Case-Alias Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- case aliases: enabled={(probe.get('caseAliases') or {}).get('enabled')}; removed={','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-'}",
            f"- input quality: `{selected_pointer_poll_input_quality_brief(quality)}`",
            f"- public save selectors: `{', '.join(probe.get('publicSaveSelectors') or []) or '-'}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- observed public save selectors: `{', '.join(probe.get('observedPublicSaveSelectors') or []) or '-'}`",
            f"- any reached public save selector: {probe.get('anyReachedPublicSaveSelector')}",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            f"- report: `out/runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll.json`",
            "",
        ])
    if summary.get("selectedPointerSyntheticSelector20InputPathCaseAliasPoll"):
        probe = summary["selectedPointerSyntheticSelector20InputPathCaseAliasPoll"]
        quality = summary.get("selectedPointerSyntheticSelector20InputPathCaseAliasInputQuality") or {}
        lines.extend([
            "",
            "## Selected-Pointer Synthetic Selector 2:0 Input-Path Case-Alias Poll",
            "",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- case aliases: enabled={(probe.get('caseAliases') or {}).get('enabled')}; removed={','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-'}",
            f"- input quality: `{selected_pointer_poll_input_quality_brief(quality)}`",
            f"- staged selectors: `{', '.join(probe.get('publicSaveSelectors') or []) or '-'}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- observed staged selectors: `{', '.join(probe.get('observedPublicSaveSelectors') or []) or '-'}`",
            f"- any reached staged selector: {probe.get('anyReachedPublicSaveSelector')}",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            "- promotion note: standalone synthetic save-shaped file; non-promoting",
            f"- report: `out/runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.json`",
            "",
        ])
    if summary.get("selectedPointerPatchedPublicSelector20InputPathCaseAliasPoll"):
        probe = summary["selectedPointerPatchedPublicSelector20InputPathCaseAliasPoll"]
        quality = summary.get("selectedPointerPatchedPublicSelector20InputPathCaseAliasInputQuality") or {}
        lines.extend([
            "",
            "## Selected-Pointer Patched Public-Base Selector 2:0 Input-Path Case-Alias Poll",
            "",
            f"- staged save kind: `{probe.get('stagedSaveKind') or '-'}`",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sample count: {probe.get('sampleCount')}",
            f"- startup wait seconds: `{probe.get('startupWaitSeconds')}`",
            f"- prelude: `{probe.get('prelude') or '-'}`",
            f"- poll interval seconds: `{probe.get('pollIntervalSeconds')}`",
            f"- case aliases: enabled={(probe.get('caseAliases') or {}).get('enabled')}; removed={','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-'}",
            f"- input quality: `{selected_pointer_poll_input_quality_brief(quality)}`",
            f"- staged selectors: `{', '.join(probe.get('publicSaveSelectors') or []) or '-'}`",
            f"- observed selectors: `{', '.join(probe.get('observedSelectors') or []) or '-'}`",
            f"- observed staged selectors: `{', '.join(probe.get('observedPublicSaveSelectors') or []) or '-'}`",
            f"- any reached staged selector: {probe.get('anyReachedPublicSaveSelector')}",
            f"- any reached current root: {probe.get('anyReachedCurrentRoot')}",
            f"- any reached route selector 2:0: {probe.get('anyReachedRouteSelectorContext')}",
            "- promotion note: constructed from a public save by patching selector/position bytes; diagnostic-only",
            f"- report: `out/runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.json`",
            "",
        ])
    if summary.get("saveFileIoProbe"):
        probe = summary["saveFileIoProbe"]
        temporary_save = probe.get("temporarySave") or {}
        lines.extend([
            "",
            "## Runtime Save File I/O Probe",
            "",
            f"- backend: `{probe.get('backend')}`",
            f"- temporary save: `{temporary_save.get('target')}`",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sequence with Hwanse2.exe PID: {probe.get('sequenceWithPidCount')}",
            f"- sequence with key-buffer writes: {probe.get('sequenceWithKeyWritesCount')}",
            f"- input trace usable: {probe.get('inputTraceUsable')}",
            f"- matched file-I/O lines: {probe.get('matchedLineCount')}",
            f"- any savedat1.dat access: {probe.get('anySavedat1DatAccess')}",
            f"- report: `out/runtime_save_file_io_probe.json`",
            "",
        ])
    if summary.get("saveFileIoStraceProbe"):
        probe = summary["saveFileIoStraceProbe"]
        temporary_save = probe.get("temporarySave") or {}
        lines.extend([
            "",
            "## Runtime Save File I/O Strace Probe",
            "",
            f"- backend: `{probe.get('backend')}`",
            f"- temporary save: `{temporary_save.get('target')}`",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sequence with Hwanse2.exe PID: {probe.get('sequenceWithPidCount')}",
            f"- sequence with key-buffer writes: {probe.get('sequenceWithKeyWritesCount')}",
            f"- input trace usable: {probe.get('inputTraceUsable')}",
            f"- matched file-I/O lines: {probe.get('matchedLineCount')}",
            f"- any savedat1.dat access: {probe.get('anySavedat1DatAccess')}",
            f"- report: `out/runtime_save_file_io_strace_probe.json`",
            "",
        ])
    if summary.get("saveFileIoStraceAttachProbe"):
        probe = summary["saveFileIoStraceAttachProbe"]
        temporary_save = probe.get("temporarySave") or {}
        lines.extend([
            "",
            "## Runtime Save File I/O Strace Attach Probe",
            "",
            f"- backend: `{probe.get('backend')}`",
            f"- temporary save: `{temporary_save.get('target')}`",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sequence with Hwanse2.exe PID: {probe.get('sequenceWithPidCount')}",
            f"- sequence with key-buffer writes: {probe.get('sequenceWithKeyWritesCount')}",
            f"- input trace usable: {probe.get('inputTraceUsable')}",
            f"- matched file-I/O lines: {probe.get('matchedLineCount')}",
            f"- any savedat1.dat access: {probe.get('anySavedat1DatAccess')}",
            f"- report: `out/runtime_save_file_io_strace_attach_probe.json`",
            "",
        ])
    if summary.get("saveFileIoStraceAttachLoadCandidatesProbe"):
        probe = summary["saveFileIoStraceAttachLoadCandidatesProbe"]
        temporary_save = probe.get("temporarySave") or {}
        lines.extend([
            "",
            "## Runtime Save File I/O Strace Attach Load Candidates Probe",
            "",
            f"- backend: `{probe.get('backend')}`",
            f"- temporary save: `{temporary_save.get('target')}`",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sequence with Hwanse2.exe PID: {probe.get('sequenceWithPidCount')}",
            f"- sequence with key-buffer writes: {probe.get('sequenceWithKeyWritesCount')}",
            f"- input trace usable: {probe.get('inputTraceUsable')}",
            f"- matched file-I/O lines: {probe.get('matchedLineCount')}",
            f"- any savedat1.dat access: {probe.get('anySavedat1DatAccess')}",
            f"- report: `out/runtime_save_file_io_strace_attach_load_candidates_probe.json`",
            "",
        ])
    if summary.get("saveFileIoStraceAttachLoadCandidatesCaseAliasProbe"):
        probe = summary["saveFileIoStraceAttachLoadCandidatesCaseAliasProbe"]
        temporary_save = probe.get("temporarySave") or {}
        lines.extend([
            "",
            "## Runtime Save File I/O Strace Attach Load Candidates Case-Alias Probe",
            "",
            f"- backend: `{probe.get('backend')}`",
            f"- temporary save: `{temporary_save.get('target')}`",
            f"- case aliases: enabled={(probe.get('caseAliases') or {}).get('enabled')}; removed={','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-'}",
            f"- sequence count: {probe.get('sequenceCount')}",
            f"- sequence with Hwanse2.exe PID: {probe.get('sequenceWithPidCount')}",
            f"- sequence with key-buffer writes: {probe.get('sequenceWithKeyWritesCount')}",
            f"- input trace usable: {probe.get('inputTraceUsable')}",
            f"- matched file-I/O lines: {probe.get('matchedLineCount')}",
            f"- any savedat1.dat access: {probe.get('anySavedat1DatAccess')}",
            f"- report: `out/runtime_save_file_io_strace_attach_load_candidates_case_alias_probe.json`",
            "",
        ])
    lines.extend([
        "",
        "## Blockers",
        "",
    ])
    lines.extend(f"- {item}" for item in summary["blockers"])
    if not summary["blockers"]:
        lines.append("- none")
    lines.extend([
        "",
        "## Trace Points",
        "",
        "| name | kind | address | purpose |",
        "| --- | --- | --- | --- |",
    ])
    for row in summary["tracePoints"]:
        lines.append(f"| {row['name']} | `{row['kind']}` | `{row['addressHex']}` | {row['purpose']} |")
    lines.extend([
        "",
        "## Commands To Try",
        "",
    ])
    lines.extend(f"{index}. `{command}`" for index, command in enumerate(summary["commandsToTry"], 1))
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    command_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(row['command'])}</code></td>"
        f"<td>{row['available']}</td>"
        f"<td><code>{html.escape(str(row.get('path') or '-'))}</code></td>"
        "</tr>"
        for row in summary["commands"].values()
    )
    package_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(row['package'])}</code></td>"
        f"<td><code>{html.escape(str(row.get('installed') or '-'))}</code></td>"
        f"<td><code>{html.escape(str(row.get('candidate') or '-'))}</code></td>"
        "</tr>"
        for row in summary["aptPackages"].values()
    )
    blockers = "\n".join(f"<li>{html.escape(item)}</li>" for item in summary["blockers"]) or "<li>none</li>"
    evidence_refs = "".join(
        f"<li><code>{html.escape(row['path'])}</code>: "
        f"<code>{html.escape(', '.join(row.get('fields') or []))}</code></li>"
        for row in summary.get("evidenceRefs") or []
    )
    trace_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['name'])}</td>"
        f"<td><code>{html.escape(row['kind'])}</code></td>"
        f"<td><code>{html.escape(row['addressHex'])}</code></td>"
        f"<td>{html.escape(row['purpose'])}</td>"
        "</tr>"
        for row in summary["tracePoints"]
    )
    commands = "\n".join(f"<li><code>{html.escape(command)}</code></li>" for command in summary["commandsToTry"])
    memory_snapshot_html = ""
    if summary.get("memorySnapshot"):
        snapshot = summary["memorySnapshot"]
        memory = snapshot.get("memory") or {}
        memory_snapshot_html = (
            "<h2>Process Memory Snapshot</h2>"
            f"<p>can read process memory: {html.escape(str(memory.get('canReadProcessMemory')))}; "
            f"loaded base: <code>{html.escape(str(snapshot.get('loadedBaseHex') or '-'))}</code>; "
            f"selected pointer static value: <code>{html.escape(str(memory.get('selectedPointerStaticValueHex') or '-'))}</code>; "
            f"selected pointer equals current root: {html.escape(str(memory.get('selectedPointerEqualsCurrentRoot')))}; "
            f"current root relocation looks valid: {html.escape(str(memory.get('currentRootRelocationLooksValid')))}.</p>"
            "<p>report: <code>out/runtime_memory_snapshot.json</code></p>"
        )
    input_probe_html = ""
    if summary.get("inputProbe"):
        probe = summary["inputProbe"]
        initial = probe.get("initialSample") or {}
        final = probe.get("finalSample") or {}
        input_probe_html = (
            "<h2>Input Path Probe</h2>"
            f"<p>xdotool path: <code>{html.escape(str(probe.get('xdotoolPath') or '-'))}</code>; "
            f"loaded base: <code>{html.escape(str(probe.get('loadedBaseHex') or '-'))}</code>; "
            f"baseline selected pointer: <code>{html.escape(str(probe.get('baselineSelectedPointerStaticHex') or '-'))}</code>; "
            f"baseline selector context: <code>{html.escape(str((probe.get('baselineSelectedPointerContext') or {}).get('selector') or '-'))}</code>; "
            f"initial selected pointer: <code>{html.escape(str(initial.get('selectedPointerStaticHex') or '-'))}</code>; "
            f"final selected pointer: <code>{html.escape(str(final.get('selectedPointerStaticHex') or '-'))}</code>; "
            f"final selector context: <code>{html.escape(str((probe.get('finalSelectedPointerContext') or {}).get('selector') or '-'))}</code>; "
            f"held-key pressed detected: {html.escape(str(probe.get('heldKeyPressedDetected')))}; "
            f"held-key changed selected pointer: {html.escape(str(probe.get('heldKeyChangedSelectedPointer')))}; "
            f"X event changed selected pointer: {html.escape(str(probe.get('xEventChangedSelectedPointer')))}; "
            f"key-buffer poke changed selected pointer: {html.escape(str(probe.get('keyBufferPokeChangedSelectedPointer')))}.</p>"
            "<p>report: <code>out/runtime_input_path_probe.json</code></p>"
        )
    key_sequence_html = ""
    if summary.get("keySequenceProbe"):
        probe = summary["keySequenceProbe"]
        key_sequence_html = (
            "<h2>Key Sequence Probe</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_key_sequence_probe.json</code></p>"
        )
    key_sequence_prelude_html = ""
    if summary.get("keySequencePreludeProbe"):
        probe = summary["keySequencePreludeProbe"]
        observed = []
        for row in probe.get("sequences") or []:
            for selector in row.get("uniqueSelectorContexts") or []:
                if selector not in observed:
                    observed.append(selector)
        key_sequence_prelude_html = (
            "<h2>Key Sequence Prelude Probe</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(observed) or '-')}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_key_sequence_prelude_probe.json</code></p>"
        )
    selected_pointer_poll_html = ""
    if summary.get("selectedPointerPoll"):
        probe = summary["selectedPointerPoll"]
        selected_pointer_poll_html = (
            "<h2>Selected-Pointer Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_poll.json</code></p>"
        )
    selected_pointer_prelude_poll_html = ""
    if summary.get("selectedPointerPreludePoll"):
        probe = summary["selectedPointerPreludePoll"]
        selected_pointer_prelude_poll_html = (
            "<h2>Selected-Pointer Prelude Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_prelude_poll.json</code></p>"
        )
    selected_pointer_long_poll_html = ""
    if summary.get("selectedPointerLongPoll"):
        probe = summary["selectedPointerLongPoll"]
        selected_pointer_long_poll_html = (
            "<h2>Selected-Pointer Long Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_long_poll.json</code></p>"
        )
    selected_pointer_late_poll_html = ""
    if summary.get("selectedPointerLatePoll"):
        probe = summary["selectedPointerLatePoll"]
        selected_pointer_late_poll_html = (
            "<h2>Selected-Pointer Late Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_late_poll.json</code></p>"
        )
    selected_pointer_savedata_load_poll_html = ""
    if summary.get("selectedPointerSavedataLoadPoll"):
        probe = summary["selectedPointerSavedataLoadPoll"]
        quality = summary.get("selectedPointerSavedataLoadInputQuality") or {}
        selected_pointer_savedata_load_poll_html = (
            "<h2>Selected-Pointer SaveData Load Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"input quality: <code>{html.escape(selected_pointer_poll_input_quality_brief(quality))}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_savedata_load_poll.json</code></p>"
        )
    selected_pointer_multislot_savedata_load_poll_html = ""
    if summary.get("selectedPointerMultislotSavedataLoadPoll"):
        probe = summary["selectedPointerMultislotSavedataLoadPoll"]
        quality = summary.get("selectedPointerMultislotSavedataLoadInputQuality") or {}
        selected_pointer_multislot_savedata_load_poll_html = (
            "<h2>Selected-Pointer Multislot SaveData Load Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"input quality: <code>{html.escape(selected_pointer_poll_input_quality_brief(quality))}</code>; "
            "public save selectors: "
            f"<code>{html.escape(', '.join(probe.get('publicSaveSelectors') or []) or '-')}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            "observed public save selectors: "
            f"<code>{html.escape(', '.join(probe.get('observedPublicSaveSelectors') or []) or '-')}</code>; "
            f"any reached public save selector: {html.escape(str(probe.get('anyReachedPublicSaveSelector')))}; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_multislot_savedata_load_poll.json</code></p>"
        )
    selected_pointer_multislot_savedata_load_case_alias_poll_html = ""
    if summary.get("selectedPointerMultislotSavedataLoadCaseAliasPoll"):
        probe = summary["selectedPointerMultislotSavedataLoadCaseAliasPoll"]
        quality = summary.get("selectedPointerMultislotSavedataLoadCaseAliasInputQuality") or {}
        selected_pointer_multislot_savedata_load_case_alias_poll_html = (
            "<h2>Selected-Pointer Multislot SaveData Load Case-Alias Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"case aliases: enabled={html.escape(str((probe.get('caseAliases') or {}).get('enabled')))}; "
            f"removed=<code>{html.escape(','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-')}</code>; "
            f"input quality: <code>{html.escape(selected_pointer_poll_input_quality_brief(quality))}</code>; "
            "public save selectors: "
            f"<code>{html.escape(', '.join(probe.get('publicSaveSelectors') or []) or '-')}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            "observed public save selectors: "
            f"<code>{html.escape(', '.join(probe.get('observedPublicSaveSelectors') or []) or '-')}</code>; "
            f"any reached public save selector: {html.escape(str(probe.get('anyReachedPublicSaveSelector')))}; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_multislot_savedata_load_case_alias_poll.json</code></p>"
        )
    selected_pointer_multislot_savedata_load_input_path_case_alias_poll_html = ""
    if summary.get("selectedPointerMultislotSavedataLoadInputPathCaseAliasPoll"):
        probe = summary["selectedPointerMultislotSavedataLoadInputPathCaseAliasPoll"]
        quality = summary.get("selectedPointerMultislotSavedataLoadInputPathCaseAliasInputQuality") or {}
        selected_pointer_multislot_savedata_load_input_path_case_alias_poll_html = (
            "<h2>Selected-Pointer Multislot SaveData Load Input-Path Case-Alias Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"case aliases: enabled={html.escape(str((probe.get('caseAliases') or {}).get('enabled')))}; "
            f"removed=<code>{html.escape(','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-')}</code>; "
            f"input quality: <code>{html.escape(selected_pointer_poll_input_quality_brief(quality))}</code>; "
            "public save selectors: "
            f"<code>{html.escape(', '.join(probe.get('publicSaveSelectors') or []) or '-')}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            "observed public save selectors: "
            f"<code>{html.escape(', '.join(probe.get('observedPublicSaveSelectors') or []) or '-')}</code>; "
            f"any reached public save selector: {html.escape(str(probe.get('anyReachedPublicSaveSelector')))}; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>report: <code>out/runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll.json</code></p>"
        )
    selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_html = ""
    if summary.get("selectedPointerSyntheticSelector20InputPathCaseAliasPoll"):
        probe = summary["selectedPointerSyntheticSelector20InputPathCaseAliasPoll"]
        quality = summary.get("selectedPointerSyntheticSelector20InputPathCaseAliasInputQuality") or {}
        selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_html = (
            "<h2>Selected-Pointer Synthetic Selector 2:0 Input-Path Case-Alias Poll</h2>"
            f"<p>sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"case aliases: enabled={html.escape(str((probe.get('caseAliases') or {}).get('enabled')))}; "
            f"removed=<code>{html.escape(','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-')}</code>; "
            f"input quality: <code>{html.escape(selected_pointer_poll_input_quality_brief(quality))}</code>; "
            "staged selectors: "
            f"<code>{html.escape(', '.join(probe.get('publicSaveSelectors') or []) or '-')}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            "observed staged selectors: "
            f"<code>{html.escape(', '.join(probe.get('observedPublicSaveSelectors') or []) or '-')}</code>; "
            f"any reached staged selector: {html.escape(str(probe.get('anyReachedPublicSaveSelector')))}; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>promotion note: standalone synthetic save-shaped file; non-promoting.</p>"
            "<p>report: <code>out/runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.json</code></p>"
        )
    selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_html = ""
    if summary.get("selectedPointerPatchedPublicSelector20InputPathCaseAliasPoll"):
        probe = summary["selectedPointerPatchedPublicSelector20InputPathCaseAliasPoll"]
        quality = summary.get("selectedPointerPatchedPublicSelector20InputPathCaseAliasInputQuality") or {}
        selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_html = (
            "<h2>Selected-Pointer Patched Public-Base Selector 2:0 Input-Path Case-Alias Poll</h2>"
            f"<p>staged save kind: <code>{html.escape(str(probe.get('stagedSaveKind') or '-'))}</code>; "
            f"sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"sample count: {html.escape(str(probe.get('sampleCount')))}; "
            f"startup wait seconds: <code>{html.escape(str(probe.get('startupWaitSeconds')))}</code>; "
            f"prelude: <code>{html.escape(str(probe.get('prelude') or '-'))}</code>; "
            f"poll interval seconds: <code>{html.escape(str(probe.get('pollIntervalSeconds')))}</code>; "
            f"case aliases: enabled={html.escape(str((probe.get('caseAliases') or {}).get('enabled')))}; "
            f"removed=<code>{html.escape(','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-')}</code>; "
            f"input quality: <code>{html.escape(selected_pointer_poll_input_quality_brief(quality))}</code>; "
            "staged selectors: "
            f"<code>{html.escape(', '.join(probe.get('publicSaveSelectors') or []) or '-')}</code>; "
            f"observed selectors: <code>{html.escape(', '.join(probe.get('observedSelectors') or []) or '-')}</code>; "
            "observed staged selectors: "
            f"<code>{html.escape(', '.join(probe.get('observedPublicSaveSelectors') or []) or '-')}</code>; "
            f"any reached staged selector: {html.escape(str(probe.get('anyReachedPublicSaveSelector')))}; "
            f"any reached current root: {html.escape(str(probe.get('anyReachedCurrentRoot')))}; "
            f"any reached route selector 2:0: {html.escape(str(probe.get('anyReachedRouteSelectorContext')))}.</p>"
            "<p>promotion note: constructed from a public save by patching selector/position bytes; diagnostic-only.</p>"
            "<p>report: <code>out/runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.json</code></p>"
        )
    save_file_io_probe_html = ""
    if summary.get("saveFileIoProbe"):
        probe = summary["saveFileIoProbe"]
        temporary_save = probe.get("temporarySave") or {}
        save_file_io_probe_html = (
            "<h2>Runtime Save File I/O Probe</h2>"
            f"<p>backend: <code>{html.escape(str(probe.get('backend')))}</code>; "
            f"temporary save: <code>{html.escape(str(temporary_save.get('target')))}</code>; "
            f"sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"pid runs: {html.escape(str(probe.get('sequenceWithPidCount')))}; "
            f"key-write runs: {html.escape(str(probe.get('sequenceWithKeyWritesCount')))}; "
            f"input trace usable: {html.escape(str(probe.get('inputTraceUsable')))}; "
            f"matched file-I/O lines: {html.escape(str(probe.get('matchedLineCount')))}; "
            f"any savedat1.dat access: {html.escape(str(probe.get('anySavedat1DatAccess')))}.</p>"
            "<p>report: <code>out/runtime_save_file_io_probe.json</code></p>"
        )
    save_file_io_strace_probe_html = ""
    if summary.get("saveFileIoStraceProbe"):
        probe = summary["saveFileIoStraceProbe"]
        temporary_save = probe.get("temporarySave") or {}
        save_file_io_strace_probe_html = (
            "<h2>Runtime Save File I/O Strace Probe</h2>"
            f"<p>backend: <code>{html.escape(str(probe.get('backend')))}</code>; "
            f"temporary save: <code>{html.escape(str(temporary_save.get('target')))}</code>; "
            f"sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"pid runs: {html.escape(str(probe.get('sequenceWithPidCount')))}; "
            f"key-write runs: {html.escape(str(probe.get('sequenceWithKeyWritesCount')))}; "
            f"input trace usable: {html.escape(str(probe.get('inputTraceUsable')))}; "
            f"matched file-I/O lines: {html.escape(str(probe.get('matchedLineCount')))}; "
            f"any savedat1.dat access: {html.escape(str(probe.get('anySavedat1DatAccess')))}.</p>"
            "<p>report: <code>out/runtime_save_file_io_strace_probe.json</code></p>"
        )
    save_file_io_strace_attach_probe_html = ""
    if summary.get("saveFileIoStraceAttachProbe"):
        probe = summary["saveFileIoStraceAttachProbe"]
        temporary_save = probe.get("temporarySave") or {}
        save_file_io_strace_attach_probe_html = (
            "<h2>Runtime Save File I/O Strace Attach Probe</h2>"
            f"<p>backend: <code>{html.escape(str(probe.get('backend')))}</code>; "
            f"temporary save: <code>{html.escape(str(temporary_save.get('target')))}</code>; "
            f"sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"pid runs: {html.escape(str(probe.get('sequenceWithPidCount')))}; "
            f"key-write runs: {html.escape(str(probe.get('sequenceWithKeyWritesCount')))}; "
            f"input trace usable: {html.escape(str(probe.get('inputTraceUsable')))}; "
            f"matched file-I/O lines: {html.escape(str(probe.get('matchedLineCount')))}; "
            f"any savedat1.dat access: {html.escape(str(probe.get('anySavedat1DatAccess')))}.</p>"
            "<p>report: <code>out/runtime_save_file_io_strace_attach_probe.json</code></p>"
        )
    save_file_io_strace_attach_load_candidates_probe_html = ""
    if summary.get("saveFileIoStraceAttachLoadCandidatesProbe"):
        probe = summary["saveFileIoStraceAttachLoadCandidatesProbe"]
        temporary_save = probe.get("temporarySave") or {}
        save_file_io_strace_attach_load_candidates_probe_html = (
            "<h2>Runtime Save File I/O Strace Attach Load Candidates Probe</h2>"
            f"<p>backend: <code>{html.escape(str(probe.get('backend')))}</code>; "
            f"temporary save: <code>{html.escape(str(temporary_save.get('target')))}</code>; "
            f"sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"pid runs: {html.escape(str(probe.get('sequenceWithPidCount')))}; "
            f"key-write runs: {html.escape(str(probe.get('sequenceWithKeyWritesCount')))}; "
            f"input trace usable: {html.escape(str(probe.get('inputTraceUsable')))}; "
            f"matched file-I/O lines: {html.escape(str(probe.get('matchedLineCount')))}; "
            f"any savedat1.dat access: {html.escape(str(probe.get('anySavedat1DatAccess')))}.</p>"
            "<p>report: <code>out/runtime_save_file_io_strace_attach_load_candidates_probe.json</code></p>"
        )
    save_file_io_strace_attach_load_candidates_case_alias_probe_html = ""
    if summary.get("saveFileIoStraceAttachLoadCandidatesCaseAliasProbe"):
        probe = summary["saveFileIoStraceAttachLoadCandidatesCaseAliasProbe"]
        temporary_save = probe.get("temporarySave") or {}
        save_file_io_strace_attach_load_candidates_case_alias_probe_html = (
            "<h2>Runtime Save File I/O Strace Attach Load Candidates Case-Alias Probe</h2>"
            f"<p>backend: <code>{html.escape(str(probe.get('backend')))}</code>; "
            f"temporary save: <code>{html.escape(str(temporary_save.get('target')))}</code>; "
            f"case aliases: enabled={html.escape(str((probe.get('caseAliases') or {}).get('enabled')))}; "
            f"removed=<code>{html.escape(','.join((probe.get('caseAliasCleanup') or {}).get('removedAliases') or []) or '-')}</code>; "
            f"sequence count: {html.escape(str(probe.get('sequenceCount')))}; "
            f"pid runs: {html.escape(str(probe.get('sequenceWithPidCount')))}; "
            f"key-write runs: {html.escape(str(probe.get('sequenceWithKeyWritesCount')))}; "
            f"input trace usable: {html.escape(str(probe.get('inputTraceUsable')))}; "
            f"matched file-I/O lines: {html.escape(str(probe.get('matchedLineCount')))}; "
            f"any savedat1.dat access: {html.escape(str(probe.get('anySavedat1DatAccess')))}.</p>"
            "<p>report: <code>out/runtime_save_file_io_strace_attach_load_candidates_case_alias_probe.json</code></p>"
        )
    return "\n".join([
        "<!doctype html><meta charset=\"utf-8\"><title>Runtime Trace Feasibility</title>",
        "<style>body{font-family:system-ui,sans-serif;background:#111;color:#eee;max-width:1100px;margin:24px auto}table{border-collapse:collapse}td,th{border:1px solid #444;padding:6px 8px;vertical-align:top}code{color:#9bd4ff}</style>",
        "<h1>Runtime Trace Feasibility</h1>",
        "<ul>",
        f"<li>objective: {html.escape(summary['objective'])}</li>",
        f"<li>proof found: {html.escape(str(summary['proofFound']))}</li>",
        "<li>failed runtime trace gates: "
        f"<code>{html.escape(','.join(summary.get('failedRuntimeTraceGateIds') or []) or '-')}</code></li>",
        f"<li>missing evidence count: {html.escape(str(len(summary.get('missingEvidence') or [])))}</li>",
        f"<li>evidence refs: {html.escape(str(summary.get('evidenceRefCount')))}</li>",
        f"<li>can run runtime trace now: {summary['canRunRuntimeTraceNow']}</li>",
        f"<li>dpkg architecture: <code>{html.escape(summary['dpkgArchitecture'])}</code></li>",
        f"<li>foreign architectures: <code>{html.escape(', '.join(summary['dpkgForeignArchitectures']) or '-')}</code></li>",
        f"<li>wine loader smoke: <code>{html.escape(summary['wineLoaderSmoke']['firstLine'] or 'failed')}</code></li>",
        f"<li>qemu wine loader smoke: <code>{html.escape(summary['qemuWineLoaderSmoke']['firstLine'] or 'failed')}</code></li>",
        f"<li>qemu wine child exec smoke: <code>{html.escape(summary['qemuWineChildExecSmoke']['firstLine'] or 'failed')}</code></li>",
        f"<li>qemu-i386 binfmt: <code>{html.escape(summary['qemuI386Binfmt']['rawFirstLine'] or '-')}</code></li>",
        "<li>binfmt consistency: summary enabled "
        f"<code>{html.escape(str(summary.get('binfmtConsistency', {}).get('summaryEnabled')))}</code>, "
        "execution probe enabled "
        f"<code>{html.escape(str(summary.get('binfmtConsistency', {}).get('executionProbeEnabled')))}</code></li>",
        f"<li>promotion status: <code>{html.escape(summary['promotionStatus'])}</code></li>",
        "</ul>",
        f"<p>{html.escape(summary['conclusion'])}</p>",
        "<h2>Missing Evidence</h2>",
        "<ul>",
        *(f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or []),
        "</ul>",
        "<h2>Evidence Refs</h2>",
        "<ul>",
        evidence_refs,
        "</ul>",
        "<h2>Tool Availability</h2>",
        "<table><thead><tr><th>command</th><th>available</th><th>path</th></tr></thead><tbody>",
        command_rows,
        "</tbody></table>",
        "<h2>Apt Packages</h2>",
        "<table><thead><tr><th>package</th><th>installed</th><th>candidate</th></tr></thead><tbody>",
        package_rows,
        "</tbody></table>",
        "<h2>QEMU Wine Smoke</h2>",
        "<table><thead><tr><th>check</th><th>status</th><th>first line</th></tr></thead><tbody>",
        "<tr>"
        f"<td><code>{html.escape(summary['qemuWineLoaderSmoke']['command'])}</code></td>"
        f"<td>{html.escape(str(summary['qemuWineLoaderSmoke']['status']))}</td>"
        f"<td><code>{html.escape(summary['qemuWineLoaderSmoke']['firstLine'] or '-')}</code></td>"
        "</tr>"
        "<tr>"
        f"<td><code>{html.escape(summary['qemuWineChildExecSmoke']['command'])}</code></td>"
        f"<td>{html.escape(str(summary['qemuWineChildExecSmoke']['status']))}</td>"
        f"<td><code>{html.escape(summary['qemuWineChildExecSmoke']['firstLine'] or '-')}</code></td>"
        "</tr>",
        "</tbody></table>",
        (
            "<h2>Execution Probe</h2>"
            f"<p>can capture trace now: {summary['executionProbe'].get('canCaptureTraceNow')}</p>"
            "<p>report: <code>out/runtime_trace_execution_probe.json</code></p>"
            if summary.get("executionProbe")
            else ""
        ),
        memory_snapshot_html,
        input_probe_html,
        key_sequence_html,
        key_sequence_prelude_html,
        selected_pointer_poll_html,
        selected_pointer_prelude_poll_html,
        selected_pointer_long_poll_html,
        selected_pointer_late_poll_html,
        selected_pointer_savedata_load_poll_html,
        selected_pointer_multislot_savedata_load_poll_html,
        selected_pointer_multislot_savedata_load_case_alias_poll_html,
        selected_pointer_multislot_savedata_load_input_path_case_alias_poll_html,
        selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll_html,
        selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll_html,
        save_file_io_probe_html,
        save_file_io_strace_probe_html,
        save_file_io_strace_attach_probe_html,
        save_file_io_strace_attach_load_candidates_probe_html,
        save_file_io_strace_attach_load_candidates_case_alias_probe_html,
        "<h2>Blockers</h2><ul>",
        blockers,
        "</ul>",
        "<h2>Trace Points</h2>",
        "<table><thead><tr><th>name</th><th>kind</th><th>address</th><th>purpose</th></tr></thead><tbody>",
        trace_rows,
        "</tbody></table>",
        "<h2>Commands To Try</h2><ol>",
        commands,
        "</ol>",
    ])


def write_outputs(summary: dict, out_dir: Path = OUT) -> None:
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "runtime_trace_feasibility.json").write_text(
        json.dumps(summary, ensure_ascii=False, separators=(",", ":")) + "\n",
        encoding="utf-8",
    )
    (out_dir / "runtime_trace_feasibility.html").write_text(html_page(summary), encoding="utf-8")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary()
    write_outputs(summary, args.out_dir)
    print(f"wrote runtime trace feasibility -> {args.out_dir / 'runtime_trace_feasibility.html'}")


if __name__ == "__main__":
    main()
