#!/usr/bin/env python3
"""Summarize the selector 10:0 follow-up seen in the patched selector 2:0 runtime poll."""
from __future__ import annotations

import argparse
import html
import json
import struct
from pathlib import Path
from typing import Any

from probe_exe_scene_tables import find_cns_strings, read_sections, va_to_offset
from summarize_save_selector_stream_traces import trace_stream


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"
EXE = ROOT / "Hwanse2.exe"
SOURCE = "map1_01a"
TARGET = "map2_02d"
CURRENT_SELECTOR = "2:0"
FOLLOWUP_SELECTOR = "10:0"
CURRENT_ROOT_HEX = "0x00540714"
FOLLOWUP_ROOT_HEX = "0x0053c4a4"
CURRENT_ROOT_VA = int(CURRENT_ROOT_HEX, 16)
FOLLOWUP_ROOT_VA = int(FOLLOWUP_ROOT_HEX, 16)
SELECTED_POINTER_GLOBAL_HEX = "0x0059de30"
FOLLOWUP_POINTER_WINDOW_BEFORE = 0x40
FOLLOWUP_POINTER_WINDOW_AFTER = 0x80
FOLLOWUP_POINTER_BRIDGE_RADIUS = 0x40
FOLLOWUP_POINTER_TRACE_STEPS = 16
ACTIVE_ORDER_WATCH_NAMES = [
    "activeOrderCount",
    "activeOrder0",
    "activeOrder1",
    "activeOrder2",
    "activeSlot0Descriptor",
    "activeSlot1Descriptor",
    "activeSlot2Descriptor",
    "runtimeSlotBaseTable0",
    "runtimeSlotBaseTable1",
    "runtimeSlotBaseTable2",
    "runtimeObjectTable0",
    "runtimeObjectTable1",
    "runtimeObjectTable2",
    "opcode24Mode1Source",
    "opcode24RuntimeFlag",
    "opcode24CurrentObjectIndex",
]
SECONDARY_BRANCH_STATE_WATCH_NAMES = [
    f"secondaryBranchState{index}"
    for index in range(12)
]
BRANCH_STATE_WATCH_NAMES = [
    "activeSelectionFlag",
    "opcode24Mode1Source",
    "opcode24RuntimeFlag",
    "opcode24CurrentObjectIndex",
    *SECONDARY_BRANCH_STATE_WATCH_NAMES,
]
IMAGE_BASE = 0x00400000
IMAGE_SIZE = 0x001BE000


def load_json(path: Path, fallback: Any) -> Any:
    if not path.exists():
        return fallback
    return json.loads(path.read_text(encoding="utf-8"))


def find_selector(rows: list[dict], selector: str) -> dict:
    for row in rows:
        labels = row.get("selectorLabels") or []
        if row.get("selector") == selector or row.get("primarySelector") == selector or selector in labels:
            return row
    return {}


def find_selector_write_rows(runtime_selector_byte_writes: dict, selector: str) -> list[dict]:
    group, slot = (int(part) for part in selector.split(":", 1))
    rows = []
    for row in (runtime_selector_byte_writes.get("opcode4fDataScan") or {}).get("rows") or []:
        if row.get("group") == group and row.get("slot") == slot:
            rows.append({
                "vaHex": row.get("vaHex"),
                "group": row.get("group"),
                "slot": row.get("slot"),
                "mode": row.get("mode"),
                "selector": selector,
            })
    return rows


def aggregate_watch_values_from_rows(rows: list[dict]) -> dict[str, list[dict[str, Any]]]:
    aggregate: dict[str, dict[str, int]] = {}
    for row in rows:
        for name, values in (row.get("uniqueWatchValues") or {}).items():
            target = aggregate.setdefault(name, {})
            for value_row in values or []:
                value_hex = value_row.get("valueHex")
                if value_hex is None:
                    continue
                target[value_hex] = target.get(value_hex, 0) + int(value_row.get("count") or 0)
    return {
        name: [
            {"valueHex": value_hex, "count": count}
            for value_hex, count in sorted(value_rows.items(), key=lambda item: (-item[1], item[0]))
        ]
        for name, value_rows in sorted(aggregate.items())
    }


def single_watch_value(watch_values: dict, sample_count: int, name: str) -> dict | None:
    rows = watch_values.get(name) or []
    if len(rows) != 1:
        return None
    if rows[0].get("count") != sample_count:
        return None
    return rows[0]


def watch_value_hex(watch_values: dict, sample_count: int, name: str) -> str | None:
    row = single_watch_value(watch_values, sample_count, name)
    return row.get("valueHex") if row else None


def watch_value_stable(watch_values: dict, sample_count: int, name: str) -> bool:
    return single_watch_value(watch_values, sample_count, name) is not None


def stable_watch_hexes(watch_values: dict, sample_count: int, names: list[str]) -> list[str | None]:
    return [watch_value_hex(watch_values, sample_count, name) for name in names]


def runtime_to_static_hex(value_hex: str | None, loaded_base_hex: str | None) -> str | None:
    if not value_hex or not loaded_base_hex:
        return None
    value = int(value_hex, 16)
    loaded_base = int(loaded_base_hex, 16)
    if loaded_base <= value < loaded_base + IMAGE_SIZE:
        return f"0x{IMAGE_BASE + value - loaded_base:08x}"
    return None


def build_active_order_runtime_evidence(active_order_poll: dict | None) -> dict:
    active_order_poll = active_order_poll or {}
    if not active_order_poll:
        return {
            "available": False,
            "sourcePoll": "runtime_selected_pointer_patched_public_selector_2_0_active_order_poll.json",
        }
    all_rows = active_order_poll.get("rows") or []
    route_rows = [row for row in all_rows if row.get("reachedRouteSelectorContext")]
    rows = route_rows or all_rows
    route_sample_count = sum(int(row.get("sampleCount") or 0) for row in rows)
    watch_values = aggregate_watch_values_from_rows(rows)
    loaded_bases = sorted({row.get("loadedBaseHex") for row in rows if row.get("loadedBaseHex")})
    loaded_base_hex = loaded_bases[0] if len(loaded_bases) == 1 else None
    order_byte_names = ["activeOrder0", "activeOrder1", "activeOrder2"]
    active_slot_names = ["activeSlot0Descriptor", "activeSlot1Descriptor", "activeSlot2Descriptor"]
    slot_base_table_names = ["runtimeSlotBaseTable0", "runtimeSlotBaseTable1", "runtimeSlotBaseTable2"]
    object_table_names = ["runtimeObjectTable0", "runtimeObjectTable1", "runtimeObjectTable2"]
    order_byte_hexes = stable_watch_hexes(watch_values, route_sample_count, order_byte_names)
    active_order_count_hex = watch_value_hex(watch_values, route_sample_count, "activeOrderCount")
    active_order_count = int(active_order_count_hex, 16) if active_order_count_hex else None
    active_order_hexes = order_byte_hexes[:active_order_count] if active_order_count is not None else []
    slot_first_dwords = stable_watch_hexes(watch_values, route_sample_count, active_slot_names)
    slot_base_table = stable_watch_hexes(watch_values, route_sample_count, slot_base_table_names)
    object_table = stable_watch_hexes(watch_values, route_sample_count, object_table_names)
    watched_values = {
        name: {
            "valueHex": watch_value_hex(watch_values, route_sample_count, name),
            "stable": watch_value_stable(watch_values, route_sample_count, name),
        }
        for name in ACTIVE_ORDER_WATCH_NAMES
        if watch_value_hex(watch_values, route_sample_count, name) is not None
    }
    return {
        "available": True,
        "sourcePoll": "runtime_selected_pointer_patched_public_selector_2_0_active_order_poll.json",
        "totalSequenceCount": active_order_poll.get("sequenceCount"),
        "totalSampleCount": active_order_poll.get("sampleCount"),
        "sequenceCount": len(rows),
        "sampleCount": route_sample_count,
        "routeSequenceNames": [row.get("name") for row in rows if row.get("name")],
        "nonRouteSequenceCount": max(0, len(all_rows) - len(route_rows)),
        "prelude": active_order_poll.get("prelude"),
        "caseAliasesEnabled": bool((active_order_poll.get("caseAliases") or {}).get("enabled")),
        "stagedSaveKind": active_order_poll.get("stagedSaveKind"),
        "stagedSelectors": active_order_poll.get("publicSaveSelectors") or [],
        "observedSelectors": active_order_poll.get("observedSelectors") or [],
        "observedStagedSelectors": active_order_poll.get("observedPublicSaveSelectors") or [],
        "reachedCurrentRoot": active_order_poll.get("anyReachedCurrentRoot"),
        "reachedRouteSelector": active_order_poll.get("anyReachedRouteSelectorContext"),
        "loadedBaseHex": loaded_base_hex,
        "activeOrderCountHex": active_order_count_hex,
        "activeOrderCount": active_order_count,
        "orderByteHexes": order_byte_hexes,
        "activeOrderHexes": active_order_hexes,
        "activeSlotFirstDwordsHex": slot_first_dwords,
        "activeSlotFirstDwordsStaticHex": [
            runtime_to_static_hex(value, loaded_base_hex) for value in slot_first_dwords
        ],
        "runtimeSlotBaseTableHexes": slot_base_table,
        "runtimeSlotBaseTableStaticHexes": [
            runtime_to_static_hex(value, loaded_base_hex) for value in slot_base_table
        ],
        "runtimeObjectTableHexes": object_table,
        "runtimeObjectTableStaticHexes": [
            runtime_to_static_hex(value, loaded_base_hex) for value in object_table
        ],
        "allWatchedValuesStable": all(
            watch_value_stable(watch_values, route_sample_count, name)
            for name in ACTIVE_ORDER_WATCH_NAMES
            if watch_values.get(name)
        ),
        "watchedValues": watched_values,
        "notRoutePromotionProof": True,
        "promotionStatus": "diagnostic-only",
        "nonPromotingBecause": [
            "active order/count was observed only while loading the patched public-base diagnostic save",
            "the poll keeps activeOrderCount at 0x01 and the active order at descriptor id 0, matching the public-base save shape rather than a captured selector 2:0 route save",
            "stable active-order bytes explain the diagnostic runtime state but do not prove normal gameplay executes selector 2:0 or reaches the map1_01a source trigger",
        ],
    }


def build_branch_state_runtime_evidence(branch_state_poll: dict | None) -> dict:
    branch_state_poll = branch_state_poll or {}
    if not branch_state_poll:
        return {
            "available": False,
            "sourcePoll": "runtime_selected_pointer_patched_public_selector_2_0_branch_state_poll.json",
        }
    all_rows = branch_state_poll.get("rows") or []
    route_rows = [row for row in all_rows if row.get("reachedRouteSelectorContext")]
    total_sample_count = int(branch_state_poll.get("sampleCount") or 0)
    total_watch_values = branch_state_poll.get("observedWatchValues") or aggregate_watch_values_from_rows(all_rows)
    route_sample_count = sum(int(row.get("sampleCount") or 0) for row in route_rows)
    route_watch_values = aggregate_watch_values_from_rows(route_rows)
    total_secondary_hexes = stable_watch_hexes(
        total_watch_values,
        total_sample_count,
        SECONDARY_BRANCH_STATE_WATCH_NAMES,
    )
    route_secondary_hexes = stable_watch_hexes(
        route_watch_values,
        route_sample_count,
        SECONDARY_BRANCH_STATE_WATCH_NAMES,
    )
    total_secondary_all_zero = (
        len(total_secondary_hexes) == len(SECONDARY_BRANCH_STATE_WATCH_NAMES)
        and all(value == "0x00" for value in total_secondary_hexes)
    )
    route_secondary_all_zero = (
        bool(route_rows)
        and len(route_secondary_hexes) == len(SECONDARY_BRANCH_STATE_WATCH_NAMES)
        and all(value == "0x00" for value in route_secondary_hexes)
    )
    watched_values = {
        name: {
            "valueHex": watch_value_hex(total_watch_values, total_sample_count, name),
            "stable": watch_value_stable(total_watch_values, total_sample_count, name),
        }
        for name in BRANCH_STATE_WATCH_NAMES
        if watch_value_hex(total_watch_values, total_sample_count, name) is not None
    }
    route_watched_values = {
        name: {
            "valueHex": watch_value_hex(route_watch_values, route_sample_count, name),
            "stable": watch_value_stable(route_watch_values, route_sample_count, name),
        }
        for name in BRANCH_STATE_WATCH_NAMES
        if watch_value_hex(route_watch_values, route_sample_count, name) is not None
    }
    return {
        "available": True,
        "sourcePoll": "runtime_selected_pointer_patched_public_selector_2_0_branch_state_poll.json",
        "totalSequenceCount": branch_state_poll.get("sequenceCount"),
        "totalSampleCount": total_sample_count,
        "sequenceCount": len(route_rows),
        "sampleCount": route_sample_count,
        "routeSequenceNames": [row.get("name") for row in route_rows if row.get("name")],
        "nonRouteSequenceCount": max(0, len(all_rows) - len(route_rows)),
        "prelude": branch_state_poll.get("prelude"),
        "caseAliasesEnabled": bool((branch_state_poll.get("caseAliases") or {}).get("enabled")),
        "stagedSaveKind": branch_state_poll.get("stagedSaveKind"),
        "stagedSelectors": branch_state_poll.get("publicSaveSelectors") or [],
        "observedSelectors": branch_state_poll.get("observedSelectors") or [],
        "observedStagedSelectors": branch_state_poll.get("observedPublicSaveSelectors") or [],
        "reachedCurrentRoot": branch_state_poll.get("anyReachedCurrentRoot"),
        "reachedRouteSelector": branch_state_poll.get("anyReachedRouteSelectorContext"),
        "activeSelectionFlagHex": watch_value_hex(total_watch_values, total_sample_count, "activeSelectionFlag"),
        "routeActiveSelectionFlagHex": watch_value_hex(
            route_watch_values,
            route_sample_count,
            "activeSelectionFlag",
        ),
        "opcode24Mode1SourceHex": watch_value_hex(total_watch_values, total_sample_count, "opcode24Mode1Source"),
        "opcode24RuntimeFlagHex": watch_value_hex(total_watch_values, total_sample_count, "opcode24RuntimeFlag"),
        "opcode24CurrentObjectIndexHex": watch_value_hex(
            total_watch_values,
            total_sample_count,
            "opcode24CurrentObjectIndex",
        ),
        "secondaryBranchStateHexes": total_secondary_hexes,
        "routeSecondaryBranchStateHexes": route_secondary_hexes,
        "secondaryBranchStateAllZero": total_secondary_all_zero,
        "routeSecondaryBranchStateAllZero": route_secondary_all_zero,
        "matchesPredecessorFillHypothesis": False if total_secondary_all_zero else None,
        "routeMatchesPredecessorFillHypothesis": False if route_secondary_all_zero else None,
        "allWatchedValuesStable": all(
            watch_value_stable(total_watch_values, total_sample_count, name)
            for name in BRANCH_STATE_WATCH_NAMES
            if total_watch_values.get(name)
        ),
        "watchedValues": watched_values,
        "routeWatchedValues": route_watched_values,
        "notRoutePromotionProof": True,
        "promotionStatus": "diagnostic-only",
        "nonPromotingBecause": [
            "branch-state values were observed only while loading the patched public-base diagnostic save",
            "all secondary branch-state bytes stayed 0x00 across the constructed selector 2:0 diagnostic poll",
            "an all-zero constructed diagnostic state does not prove normal gameplay executes the predecessor fill fragment",
        ],
    }


def build_exit_candidate_runtime_evidence(exit_candidate_poll: dict | None) -> dict:
    exit_candidate_poll = exit_candidate_poll or {}
    if not exit_candidate_poll:
        return {
            "available": False,
            "sourcePoll": "runtime_patched_selector_exit_candidates_poll.json",
        }
    rows = exit_candidate_poll.get("candidateRows") or []
    route_sides = [
        row.get("side")
        for row in rows
        if row.get("anyReachedRouteSelectorContext")
    ]
    staged_sides = [
        row.get("side")
        for row in rows
        if row.get("anyReachedStagedSelector")
    ]
    branch_nonzero_sides = [
        row.get("side")
        for row in rows
        if row.get("branchStateNonzero")
    ]
    return {
        "available": True,
        "sourcePoll": "runtime_patched_selector_exit_candidates_poll.json",
        "stagedKind": exit_candidate_poll.get("stagedKind"),
        "baseSave": exit_candidate_poll.get("baseSave"),
        "candidateCount": exit_candidate_poll.get("candidateCount"),
        "candidateSaveRows": exit_candidate_poll.get("candidateSaveRows") or [],
        "candidateRows": [
            {
                "side": row.get("side"),
                "tile": row.get("tile") or {},
                "autoTrigger": row.get("autoTrigger"),
                "sampleCount": row.get("sampleCount"),
                "selectorCounts": row.get("selectorCounts"),
                "observedSelectors": row.get("observedSelectors") or [],
                "reachedRouteSelector": row.get("anyReachedRouteSelectorContext"),
                "reachedStagedSelector": row.get("anyReachedStagedSelector"),
                "branchStateNonzero": row.get("branchStateNonzero"),
                "opcode24Mode1SourceValues": row.get("opcode24Mode1SourceValues"),
                "opcode24RuntimeFlagValues": row.get("opcode24RuntimeFlagValues"),
                "opcode24CurrentObjectIndexValues": row.get("opcode24CurrentObjectIndexValues"),
            }
            for row in rows
        ],
        "routeSelectorSideCount": len(route_sides),
        "routeSelectorSides": route_sides,
        "stagedSelectorSideCount": len(staged_sides),
        "stagedSelectorSides": staged_sides,
        "branchStateNonzeroSideCount": len(branch_nonzero_sides),
        "branchStateNonzeroSides": branch_nonzero_sides,
        "anyCandidateReachedRouteSelector": exit_candidate_poll.get("anyCandidateReachedRouteSelector"),
        "anyCandidateBranchStateNonzero": exit_candidate_poll.get("anyCandidateBranchStateNonzero"),
        "notRoutePromotionProof": True,
        "promotionStatus": "diagnostic-only",
        "nonPromotingBecause": [
            "candidate saves are constructed from edited selector/position bytes",
            "only observed selector 2:0 hit is from a patched diagnostic save, not captured gameplay",
            "branch-state and opcode24 watch values stay zero across candidate movement samples",
            "top/bottom/right candidate sequences did not even observe the staged selector in this calibration run",
        ],
    }


def watch_value_counts(watch_values: dict, name: str) -> str:
    rows = watch_values.get(name) or []
    return ",".join(
        f"{row.get('valueHex')}x{row.get('count')}"
        for row in rows
        if row.get("valueHex") is not None
    ) or "-"


def selector_context_counts(row: dict) -> str:
    return ",".join(
        f"{context.get('selector')}x{context.get('count')}"
        for context in row.get("uniqueSelectorContexts") or []
    ) or "-"


def left_stability_recheck_summary(source_poll: str, poll: dict | None) -> dict:
    poll = poll or {}
    if not poll:
        return {
            "available": False,
            "sourcePoll": source_poll,
        }
    rows = poll.get("rows") or []
    route_rows = [
        row
        for row in rows
        if row.get("reachedRouteSelectorContext") or int(row.get("routeSelectorHitCount") or 0) > 0
    ]
    watch_values = aggregate_watch_values_from_rows(rows)
    sample_count = int(poll.get("sampleCount") or 0)
    return {
        "available": True,
        "sourcePoll": source_poll,
        "stagedKind": poll.get("stagedSaveKind"),
        "sequenceCount": poll.get("sequenceCount"),
        "sampleCount": poll.get("sampleCount"),
        "routeSequenceCount": len(route_rows),
        "routeSequenceNames": [row.get("name") for row in route_rows if row.get("name")],
        "observedSelectors": poll.get("observedSelectors") or [],
        "observedStagedSelectors": poll.get("observedPublicSaveSelectors") or [],
        "reachedCurrentRoot": poll.get("anyReachedCurrentRoot"),
        "reachedRouteSelector": poll.get("anyReachedRouteSelectorContext"),
        "routeSelectorHitCount": sum(int(row.get("routeSelectorHitCount") or 0) for row in rows),
        "opcode24Mode1SourceValues": watch_value_counts(watch_values, "opcode24Mode1Source"),
        "opcode24RuntimeFlagValues": watch_value_counts(watch_values, "opcode24RuntimeFlag"),
        "opcode24CurrentObjectIndexValues": watch_value_counts(watch_values, "opcode24CurrentObjectIndex"),
        "activeOrderCountValues": watch_value_counts(watch_values, "activeOrderCount"),
        "activeSlot0DescriptorValues": watch_value_counts(watch_values, "activeSlot0Descriptor"),
        "runtimeSlotBaseTable0Values": watch_value_counts(watch_values, "runtimeSlotBaseTable0"),
        "allSamplesOpcode24Zero": all(
            watch_value_hex(watch_values, sample_count, name) == "0x00"
            for name in ("opcode24Mode1Source", "opcode24RuntimeFlag", "opcode24CurrentObjectIndex")
            if watch_values.get(name)
        ),
    }


def build_left_stability_runtime_evidence(
    left_stability_poll: dict | None,
    left_stability_recheck_poll: dict | None = None,
    left_active_order_poll: dict | None = None,
) -> dict:
    left_stability_poll = left_stability_poll or {}
    if not left_stability_poll:
        return {
            "available": False,
            "sourcePoll": "runtime_patched_selector_left_stability_poll.json",
        }
    rows = left_stability_poll.get("rows") or []
    route_rows = [
        row
        for row in rows
        if row.get("reachedRouteSelectorContext") or int(row.get("routeSelectorHitCount") or 0) > 0
    ]
    non_route_rows = [row for row in rows if row not in route_rows]
    sample_count = int(left_stability_poll.get("sampleCount") or 0)
    watch_values = aggregate_watch_values_from_rows(rows)
    opcode_watch_names = [
        "opcode24Mode1Source",
        "opcode24RuntimeFlag",
        "opcode24CurrentObjectIndex",
    ]
    opcode24_all_zero = all(
        watch_value_hex(watch_values, sample_count, name) == "0x00"
        for name in opcode_watch_names
        if watch_values.get(name)
    )
    recheck = left_stability_recheck_summary(
        "runtime_patched_selector_left_stability_recheck_poll.json",
        left_stability_recheck_poll,
    )
    active_order_recheck = left_stability_recheck_summary(
        "runtime_patched_selector_left_active_order_poll.json",
        left_active_order_poll,
    )
    original_route_hit_count = sum(int(row.get("routeSelectorHitCount") or 0) for row in rows)
    route_hit_reproduced_by_recheck = bool(recheck.get("routeSelectorHitCount"))
    route_hit_reproduced_with_active_order = bool(active_order_recheck.get("routeSelectorHitCount"))
    return {
        "available": True,
        "sourcePoll": "runtime_patched_selector_left_stability_poll.json",
        "stagedKind": left_stability_poll.get("stagedSaveKind"),
        "sequenceCount": left_stability_poll.get("sequenceCount"),
        "sampleCount": left_stability_poll.get("sampleCount"),
        "routeSequenceCount": len(route_rows),
        "routeSequenceNames": [row.get("name") for row in route_rows if row.get("name")],
        "nonRouteSequenceCount": len(non_route_rows),
        "nonRouteSequenceNames": [row.get("name") for row in non_route_rows if row.get("name")],
        "observedSelectors": left_stability_poll.get("observedSelectors") or [],
        "stagedSelectors": left_stability_poll.get("publicSaveSelectors") or [],
        "observedStagedSelectors": left_stability_poll.get("observedPublicSaveSelectors") or [],
        "reachedCurrentRoot": left_stability_poll.get("anyReachedCurrentRoot"),
        "reachedRouteSelector": left_stability_poll.get("anyReachedRouteSelectorContext"),
        "routeSelectorHitCount": original_route_hit_count,
        "opcode24Mode1SourceValues": watch_value_counts(watch_values, "opcode24Mode1Source"),
        "opcode24RuntimeFlagValues": watch_value_counts(watch_values, "opcode24RuntimeFlag"),
        "opcode24CurrentObjectIndexValues": watch_value_counts(watch_values, "opcode24CurrentObjectIndex"),
        "opcode24AllZero": opcode24_all_zero,
        "sequenceRows": [
            {
                "name": row.get("name"),
                "keys": row.get("keys") or [],
                "sampleCount": row.get("sampleCount"),
                "selectorCounts": selector_context_counts(row),
                "currentRootHitCount": row.get("currentRootHitCount"),
                "routeSelectorHitCount": row.get("routeSelectorHitCount"),
                "reachedRouteSelector": row.get("reachedRouteSelectorContext"),
            }
            for row in rows
        ],
        "recheck": recheck,
        "activeOrderRecheck": active_order_recheck,
        "routeHitReproducedByRecheck": route_hit_reproduced_by_recheck,
        "routeHitReproducedWithActiveOrderWatch": route_hit_reproduced_with_active_order,
        "routeHitReproducibility": (
            "not-reproduced"
            if original_route_hit_count and not route_hit_reproduced_by_recheck and not route_hit_reproduced_with_active_order
            else "reproduced"
            if route_hit_reproduced_by_recheck or route_hit_reproduced_with_active_order
            else "no-route-hit"
        ),
        "notRoutePromotionProof": True,
        "promotionStatus": "diagnostic-only",
        "nonPromotingBecause": [
            "left-exit stability poll uses a constructed public-base selector 2:0 save",
            "load-only and load-left variants stay at selector 50:0",
            "only load-right observes selector 2:0/10:0, making the hit sequence-dependent calibration",
            "selector-only and active-order rechecks did not reproduce the earlier left-load-right route hit",
            "opcode24 watch values stay 0x00 across the stability poll",
        ],
    }


def parse_hex_range(value: str | None) -> tuple[int, int] | None:
    if not value or ".." not in value:
        return None
    start, end = value.split("..", 1)
    return int(start, 16), int(end, 16)


def section_name_for_va(sections: list[dict], va: int) -> str | None:
    for section in sections:
        start = section["va"]
        end = start + section["raw_size"]
        if start <= va < end:
            return section["name"]
    return None


def read_u32(exe: bytes, sections: list[dict], va: int) -> int | None:
    offset = va_to_offset(sections, va)
    if offset is None or offset + 4 > len(exe):
        return None
    return struct.unpack_from("<I", exe, offset)[0]


def dword_window(
    exe: bytes,
    sections: list[dict],
    strings: dict[int, str],
    center_va: int,
    before: int = FOLLOWUP_POINTER_WINDOW_BEFORE,
    after: int = FOLLOWUP_POINTER_WINDOW_AFTER,
) -> list[dict]:
    rows = []
    start = center_va - before
    start -= start % 4
    end = center_va + after
    for va in range(start, end, 4):
        value = read_u32(exe, sections, va)
        if value is None:
            continue
        pointer_section = section_name_for_va(sections, value)
        row = {
            "vaHex": f"0x{va:08x}",
            "valueHex": f"0x{value:08x}",
            "lowOpcodeHex": f"0x{value & 0xff:02x}",
            "relativeToPointerHex": f"{va - center_va:+#x}",
            "isSelectedPointerDword": va == center_va,
            "pointerSection": pointer_section,
            "isPointer": pointer_section is not None,
        }
        if value in strings:
            row["cns"] = strings[value]
        rows.append(row)
    return rows


def compact_trace_rows(trace: list[dict]) -> list[dict]:
    rows = []
    for row in trace:
        compact = {
            "step": row.get("step"),
            "vaHex": row.get("vaHex"),
            "valueHex": row.get("valueHex"),
            "opcodeHex": row.get("opcodeHex"),
            "handlerVaHex": row.get("handlerVaHex"),
            "handlerSection": row.get("handlerSection"),
            "fixedAdvances": row.get("fixedAdvances") or [],
            "pointerHex": row.get("pointerHex"),
            "cns": row.get("cns"),
            "branchTargetHex": row.get("branchTargetHex"),
            "fallthroughVaHex": row.get("fallthroughVaHex"),
            "stopReason": row.get("stopReason"),
        }
        rows.append({key: value for key, value in compact.items() if value not in (None, [])})
    return rows


def trace_stop_reason(trace: list[dict]) -> str | None:
    for row in reversed(trace):
        if row.get("stopReason"):
            return row.get("stopReason")
    return None


def opcode20_descriptor_pointer(exe: bytes, sections: list[dict], trace: list[dict]) -> dict | None:
    for row in trace:
        if row.get("opcodeHex") != "0x20":
            continue
        va_hex = row.get("vaHex")
        if not va_hex:
            continue
        descriptor_va = int(va_hex, 16) + 4
        descriptor_value = read_u32(exe, sections, descriptor_va)
        if descriptor_value is None:
            return None
        return {
            "descriptorVaHex": f"0x{descriptor_va:08x}",
            "descriptorPointerHex": f"0x{descriptor_value:08x}",
            "descriptorPointerSection": section_name_for_va(sections, descriptor_value),
        }
    return None


def find_nearby_current_bridge_hits(
    followup_bridge: dict,
    pointer_va: int,
    radius: int = FOLLOWUP_POINTER_BRIDGE_RADIUS,
) -> list[dict]:
    hits = []
    for hit in ((followup_bridge.get("aliasToCurrent") or {}).get("hits") or []):
        source_hex = hit.get("sourceVaHex")
        if not source_hex:
            continue
        source_va = int(source_hex, 16)
        if pointer_va - radius <= source_va <= pointer_va + radius:
            hits.append({
                "sourceVaHex": source_hex,
                "valueHex": hit.get("valueHex"),
                "targetClass": hit.get("targetClass"),
                "sourceLocationRole": hit.get("sourceLocationRole"),
                "metadataLike": hit.get("metadataLike"),
            })
    return hits


def trace_contains_value(trace: list[dict], value_hex: str) -> bool:
    return any(row.get("valueHex") == value_hex or row.get("pointerHex") == value_hex for row in trace)


def trace_contains_range_pointer(trace: list[dict], value_range: tuple[int, int] | None) -> bool:
    if not value_range:
        return False
    start, end = value_range
    for row in trace:
        value_hex = row.get("valueHex") or row.get("pointerHex")
        if value_hex and start <= int(value_hex, 16) < end:
            return True
    return False


def trace_contains_map_string(trace: list[dict], map_name: str) -> bool:
    return any(map_name in (row.get("cns") or "") for row in trace)


def build_exact_followup_pointer_contexts(
    exe_path: Path,
    pointer_hexes: list[str],
    address_predecessor_context: dict,
    followup_bridge: dict,
) -> list[dict]:
    if not exe_path.exists():
        return [
            {
                "pointerVaHex": pointer_hex,
                "contextAvailable": False,
                "unavailableReason": f"missing executable {exe_path}",
            }
            for pointer_hex in pointer_hexes
        ]
    exe = exe_path.read_bytes()
    sections = read_sections(exe)
    strings = find_cns_strings(exe, sections)
    tail_range = parse_hex_range(
        (address_predecessor_context.get("addressPredecessorRoot") or {}).get("tailRangeAfterLastFillHex")
    )
    predecessor_range = parse_hex_range(address_predecessor_context.get("addressPredecessorRangeHex"))
    current_range = parse_hex_range(((followup_bridge.get("aliasToCurrent") or {}).get("targetRangeHex")))
    contexts = []
    for pointer_hex in pointer_hexes:
        pointer_va = int(pointer_hex, 16)
        trace = trace_stream(exe, sections, strings, pointer_va, FOLLOWUP_POINTER_TRACE_STEPS)
        compact_trace = compact_trace_rows(trace)
        descriptor = opcode20_descriptor_pointer(exe, sections, trace) or {}
        nearby_bridge_hits = find_nearby_current_bridge_hits(followup_bridge, pointer_va)
        exact_bridge_hit = any(hit.get("sourceVaHex") == pointer_hex for hit in nearby_bridge_hits)
        context = {
            "pointerVaHex": pointer_hex,
            "contextAvailable": True,
            "fileOffsetHex": f"0x{va_to_offset(sections, pointer_va):06x}"
            if va_to_offset(sections, pointer_va) is not None
            else None,
            "rootHex": FOLLOWUP_ROOT_HEX,
            "rootOffsetHex": f"0x{pointer_va - FOLLOWUP_ROOT_VA:08x}",
            "currentRootHex": CURRENT_ROOT_HEX,
            "currentRootDeltaHex": f"0x{CURRENT_ROOT_VA - pointer_va:08x}",
            "predecessorRangeHex": address_predecessor_context.get("addressPredecessorRangeHex"),
            "tailRangeAfterLastFillHex": (
                (address_predecessor_context.get("addressPredecessorRoot") or {}).get("tailRangeAfterLastFillHex")
            ),
            "withinAddressPredecessorRange": (
                bool(predecessor_range and predecessor_range[0] <= pointer_va < predecessor_range[1])
            ),
            "withinAddressPredecessorTail": bool(tail_range and tail_range[0] <= pointer_va < tail_range[1]),
            "startsAtAliasRoot": pointer_va == FOLLOWUP_ROOT_VA,
            "firstOpcodeHex": compact_trace[0].get("opcodeHex") if compact_trace else None,
            "secondOpcodeHex": compact_trace[1].get("opcodeHex") if len(compact_trace) > 1 else None,
            "opcode20DescriptorVaHex": descriptor.get("descriptorVaHex"),
            "opcode20DescriptorPointerHex": descriptor.get("descriptorPointerHex"),
            "opcode20DescriptorPointerSection": descriptor.get("descriptorPointerSection"),
            "traceStopReason": trace_stop_reason(trace),
            "trace": compact_trace,
            "traceContainsSelectedPointerGlobal": trace_contains_value(trace, SELECTED_POINTER_GLOBAL_HEX),
            "traceContainsCurrentRootExactRef": trace_contains_value(trace, CURRENT_ROOT_HEX),
            "traceContainsCurrentRootRangePointer": trace_contains_range_pointer(trace, current_range),
            "traceContainsSourceMapString": trace_contains_map_string(trace, SOURCE),
            "traceContainsTargetMapString": trace_contains_map_string(trace, TARGET),
            "exactSelectedPointerDwordIsCurrentRangeBridge": exact_bridge_hit,
            "nearbyCurrentRangeBridgeDwordCount": len(nearby_bridge_hits),
            "hasNearbyCurrentRangeBridgeDwords": bool(nearby_bridge_hits),
            "nearbyCurrentRangeBridgeDwords": nearby_bridge_hits,
            "dwordWindow": dword_window(exe, sections, strings, pointer_va),
            "promotionStatus": "blocked",
            "nonPromotingBecause": [
                "the sampled follow-up pointer lands inside the target-side address-predecessor tail, not at the 10:0 alias root or a map1_01a source record",
                "the exact selected dword is descriptor/script data and is not itself one of the nearby current-range bridge dwords",
                "the local stream trace stops before reaching a selected-pointer store, exact current-root reference, source map string, or target map string",
                "the pointer was observed only in the patched public-base diagnostic poll",
            ],
        }
        contexts.append(context)
    return contexts


def event_summary(event: dict | None) -> dict | None:
    if not event:
        return None
    context = event.get("selectorContext") or {}
    watch_values = {}
    for name, value in (event.get("watchValues") or {}).items():
        watch_values[name] = {
            "valueHex": value.get("valueHex"),
            "value": value.get("value"),
        }
    return {
        "sampleIndex": event.get("sampleIndex"),
        "elapsedMs": event.get("elapsedMs"),
        "phase": event.get("phase"),
        "selector": context.get("selector"),
        "selectedPointerStaticHex": event.get("selectedPointerStaticHex"),
        "rootHex": context.get("rootHex"),
        "offsetHex": context.get("offsetHex"),
        "pressedKeyOffsets": event.get("pressedKeyOffsets") or [],
        "watchValues": watch_values,
    }


def selector_transition_summaries(events: list[dict]) -> list[dict]:
    transitions = []
    last_selector = None
    for event in events:
        selector = (event.get("selectorContext") or {}).get("selector")
        if selector not in {CURRENT_SELECTOR, FOLLOWUP_SELECTOR}:
            continue
        if selector == last_selector:
            continue
        summary = event_summary(event)
        if summary:
            transitions.append(summary)
        last_selector = selector
    return transitions


def phase_selector_counts(events: list[dict]) -> list[dict]:
    counts: dict[tuple[str, str], int] = {}
    for event in events:
        selector = (event.get("selectorContext") or {}).get("selector")
        if selector not in {CURRENT_SELECTOR, FOLLOWUP_SELECTOR}:
            continue
        key = (str(event.get("phase")), selector)
        counts[key] = counts.get(key, 0) + 1
    return [
        {
            "phase": phase,
            "selector": selector,
            "count": count,
        }
        for (phase, selector), count in sorted(counts.items())
    ]


def poll_row_summaries(poll: dict) -> tuple[list[dict], dict[str, int]]:
    rows = []
    totals: dict[str, int] = {}
    for row in poll.get("rows") or []:
        events = row.get("events") or []
        contexts = []
        for context in row.get("uniqueSelectorContexts") or []:
            selector = context.get("selector")
            if selector not in {CURRENT_SELECTOR, FOLLOWUP_SELECTOR}:
                continue
            count = int(context.get("count") or 0)
            totals[selector] = totals.get(selector, 0) + count
            contexts.append({
                "selector": selector,
                "count": count,
                "rootHex": context.get("rootHex"),
                "fieldMaps": context.get("fieldMaps") or [],
                "containsSource": SOURCE in (context.get("fieldMaps") or []),
                "containsTarget": TARGET in (context.get("fieldMaps") or []),
            })
        first_followup_event = next(
            (
                event
                for event in events
                if (event.get("selectorContext") or {}).get("selector") == FOLLOWUP_SELECTOR
            ),
            None,
        )
        last_current_event_before_followup = None
        if first_followup_event:
            first_followup_index = int(first_followup_event.get("sampleIndex") or 0)
            current_events_before_followup = [
                event
                for event in events
                if (event.get("selectorContext") or {}).get("selector") == CURRENT_SELECTOR
                and int(event.get("sampleIndex") or 0) < first_followup_index
            ]
            if current_events_before_followup:
                last_current_event_before_followup = current_events_before_followup[-1]
        rows.append({
            "name": row.get("name"),
            "eventCount": len(events),
            "currentRootHitCount": row.get("currentRootHitCount"),
            "routeSelectorHitCount": row.get("routeSelectorHitCount"),
            "contexts": contexts,
            "selectorTransitions": selector_transition_summaries(events),
            "phaseSelectorCounts": phase_selector_counts(events),
            "firstFollowupEvent": event_summary(first_followup_event),
            "lastCurrentEventBeforeFollowup": event_summary(last_current_event_before_followup),
        })
    return rows, totals


def build_summary(
    poll: dict,
    mapset_aliases: dict,
    address_predecessor_context: dict,
    target_alias_state_effects: dict,
    target_alias_bridges: dict,
    global_selected_pointer_paths: dict,
    runtime_selector_byte_writes: dict,
    active_order_poll: dict | None = None,
    branch_state_poll: dict | None = None,
    exit_candidate_poll: dict | None = None,
    left_stability_poll: dict | None = None,
    left_stability_recheck_poll: dict | None = None,
    left_active_order_poll: dict | None = None,
    exe_path: Path = EXE,
) -> dict:
    runtime_rows, runtime_selector_sample_counts = poll_row_summaries(poll)
    transition_pair_count = sum(
        1
        for row in runtime_rows
        if [transition.get("selector") for transition in row.get("selectorTransitions") or []][:2]
        == [CURRENT_SELECTOR, FOLLOWUP_SELECTOR]
    )
    followup_selected_pointer_static_hexes = sorted({
        transition.get("selectedPointerStaticHex")
        for row in runtime_rows
        for transition in row.get("selectorTransitions") or []
        if transition.get("selector") == FOLLOWUP_SELECTOR and transition.get("selectedPointerStaticHex")
    })
    target_aliases = (mapset_aliases.get("targetAliasGroup") or {}).get("aliases") or []
    followup_alias = find_selector(target_aliases, FOLLOWUP_SELECTOR)
    followup_state = find_selector(target_alias_state_effects.get("aliasRows") or [], FOLLOWUP_SELECTOR)
    followup_bridge = find_selector(target_alias_bridges.get("aliasRows") or [], FOLLOWUP_SELECTOR)
    followup_global_path = find_selector(
        global_selected_pointer_paths.get("selectorRootScans") or [],
        FOLLOWUP_SELECTOR,
    )
    followup_selector_write_rows = find_selector_write_rows(runtime_selector_byte_writes, FOLLOWUP_SELECTOR)
    address_predecessor_root = address_predecessor_context.get("addressPredecessorRoot") or {}
    observed_selectors = poll.get("observedSelectors") or []
    staged_selectors = poll.get("publicSaveSelectors") or []
    observed_staged_selectors = poll.get("observedPublicSaveSelectors") or []
    followup_field_maps = followup_alias.get("fieldMaps") or followup_global_path.get("fieldMaps") or []
    followup_bridge_counts = {
        "aliasToCurrentHitCount": (followup_bridge.get("aliasToCurrent") or {}).get("hitCount"),
        "aliasToCurrentDataHitCount": (followup_bridge.get("aliasToCurrent") or {}).get("dataHitCount"),
        "aliasToCurrentExecutionLikeBridgeFound": followup_bridge.get("aliasToCurrentExecutionLikeBridgeFound"),
        "aliasToCurrentAfterLastFillHitCount": followup_bridge.get("aliasToCurrentAfterLastFillHitCount"),
        "aliasToCurrentAfterLastFillDataHitCount": followup_bridge.get("aliasToCurrentAfterLastFillDataHitCount"),
        "aliasToCurrentAfterLastFillPreWriterHitCount": followup_bridge.get("aliasToCurrentAfterLastFillPreWriterHitCount"),
        "aliasToCurrentAfterLastFillLeafTableHitCount": followup_bridge.get("aliasToCurrentAfterLastFillLeafTableHitCount"),
        "aliasToCurrentAfterLastFillTraceCurrentWriterHitCount": followup_bridge.get(
            "aliasToCurrentAfterLastFillTraceCurrentWriterHitCount"
        ),
        "aliasToCurrentAfterLastFillTraceCurrentReaderHitCount": followup_bridge.get(
            "aliasToCurrentAfterLastFillTraceCurrentReaderHitCount"
        ),
        "aliasToCurrentAfterLastFillTraceRouteSceneRecordHitCount": followup_bridge.get(
            "aliasToCurrentAfterLastFillTraceRouteSceneRecordHitCount"
        ),
        "aliasToCurrentAfterLastFillExecutionLikeBridgeFound": followup_bridge.get(
            "aliasToCurrentAfterLastFillExecutionLikeBridgeFound"
        ),
    }
    exact_followup_pointer_contexts = build_exact_followup_pointer_contexts(
        exe_path,
        followup_selected_pointer_static_hexes,
        address_predecessor_context,
        followup_bridge,
    )
    active_order_runtime_evidence = build_active_order_runtime_evidence(active_order_poll)
    branch_state_runtime_evidence = build_branch_state_runtime_evidence(branch_state_poll)
    exit_candidate_runtime_evidence = build_exit_candidate_runtime_evidence(exit_candidate_poll)
    left_stability_runtime_evidence = build_left_stability_runtime_evidence(
        left_stability_poll,
        left_stability_recheck_poll,
        left_active_order_poll,
    )
    global_path_counts = {
        "opcode07SelectsCurrentRootCount": followup_global_path.get("opcode07SelectsCurrentRootCount"),
        "opcode07SelectsCurrentRangeCount": followup_global_path.get("opcode07SelectsCurrentRangeCount"),
        "opcode08NearestCurrentRootProducerCount": followup_global_path.get("opcode08NearestCurrentRootProducerCount"),
        "opcode08NearestCurrentRangeProducerCount": followup_global_path.get("opcode08NearestCurrentRangeProducerCount"),
        "opcode09StoresCurrentRootCount": followup_global_path.get("opcode09StoresCurrentRootCount"),
        "opcode09StoresCurrentRangeCount": followup_global_path.get("opcode09StoresCurrentRangeCount"),
        "promotingCandidateCount": followup_global_path.get("promotingCandidateCount"),
    }
    not_route_promotion_reasons = [
        "patched public-base diagnostic save is constructed from edited selector/position bytes",
        "sampled 2:0 -> 10:0 selected-pointer movement comes from that constructed diagnostic state",
        "selector 10:0 contains the target map set but not map1_01a",
        "selector 10:0 has no public captured save sample",
        "selector 10:0 has no non-current selected-pointer producer/store candidate for the current 2:0 root",
        "target-alias bridge scans do not find an execution-like bridge into the current writer/reader",
        "poll rows do not provide a normal gameplay control-flow trace or strict source hotspot",
        "patched diagnostic branch-state watch keeps secondary branch state all-zero and cannot prove predecessor fill execution",
        "patched exit-candidate movement poll is constructed diagnostic-only and keeps branch-state/opcode24 watch values at 0x00",
        "patched left-exit stability poll is constructed diagnostic-only; its initial 2:0 load-right hit did not reproduce in selector-only or active-order rechecks",
    ]
    conclusion = (
        "The patched public-base diagnostic poll proves that the original input-path/case-alias load path can select a "
        "constructed selector 2:0 save-shaped file. Its sampled events show the selected pointer starting at the current "
        "2:0 root and later moving to a 10:0-range address in both candidate sequences. "
        "Selector 10:0 matches the target-side address-adjacent alias before the current root, contains map2_02d but not "
        "map1_01a, and its modeled fill/state and bridge evidence remain conditional. The branch-state diagnostic keeps "
        "secondary branch-state bytes at 0x00 even in the constructed selector 2:0 run, which is calibration evidence rather "
        "than predecessor-fill execution proof. The patched exit-candidate poll exercises top/bottom/left/right constructed "
        "selector 2:0 saves; only the left candidate observed selector 2:0, and all candidate samples kept branch-state and "
        "opcode24 watch values at 0x00. This is useful follow-up context, but it is not a captured gameplay save, "
        "normal-route selected-pointer trace, strict hotspot, or route promotion proof. "
        "The left stability poll initially separated load-only/load-left from load-right, but selector-only and "
        "active-order rechecks both stayed at selector 50:0. The earlier 2:0/10:0 hit is therefore non-reproducible "
        "constructed calibration, not route evidence. "
    )
    return {
        "source": SOURCE,
        "target": TARGET,
        "currentSelector": CURRENT_SELECTOR,
        "currentRootHex": CURRENT_ROOT_HEX,
        "followupSelector": FOLLOWUP_SELECTOR,
        "followupRootHex": FOLLOWUP_ROOT_HEX,
        "runtimePoll": {
            "sampleCount": poll.get("sampleCount"),
            "sequenceCount": poll.get("sequenceCount"),
            "startupWaitSeconds": poll.get("startupWaitSeconds"),
            "prelude": poll.get("prelude"),
            "caseAliasesEnabled": bool((poll.get("caseAliases") or {}).get("enabled")),
            "stagedSaveKind": poll.get("stagedSaveKind"),
            "stagedSelectors": staged_selectors,
            "observedSelectors": observed_selectors,
            "observedStagedSelectors": observed_staged_selectors,
            "reachedCurrentRoot": poll.get("anyReachedCurrentRoot"),
            "reachedRouteSelector": poll.get("anyReachedRouteSelectorContext"),
            "reachedFollowupSelector": FOLLOWUP_SELECTOR in observed_selectors,
            "promotionStatus": poll.get("promotionStatus"),
            "runtimeSelectorSampleCounts": runtime_selector_sample_counts,
            "transitionPairCount": transition_pair_count,
            "followupSelectedPointerStaticHexes": followup_selected_pointer_static_hexes,
            "rows": runtime_rows,
        },
        "followupAlias": {
            "selector": FOLLOWUP_SELECTOR,
            "role": followup_alias.get("role"),
            "rootHex": followup_alias.get("rootHex"),
            "rootAddressOrderIndex": followup_alias.get("rootAddressOrderIndex"),
            "publicSampleIds": followup_alias.get("publicSampleIds") or [],
            "hasPublicSample": bool(followup_alias.get("publicSampleIds")),
            "fieldMaps": followup_field_maps,
            "containsSource": SOURCE in followup_field_maps,
            "containsTarget": TARGET in followup_field_maps,
            "fillCount": followup_alias.get("fillCount"),
            "firstFillHex": followup_alias.get("firstFillHex"),
            "lastFillHex": followup_alias.get("lastFillHex"),
        },
        "addressPredecessorEvidence": {
            "selector": address_predecessor_context.get("addressPredecessorSelector"),
            "rootHex": address_predecessor_context.get("addressPredecessorRootHex"),
            "rangeHex": address_predecessor_context.get("addressPredecessorRangeHex"),
            "containsSource": address_predecessor_context.get("addressPredecessorContainsSource"),
            "containsTarget": address_predecessor_context.get("addressPredecessorContainsTarget"),
            "fillCount": address_predecessor_root.get("fillCount"),
            "lastFillAllStartsPassCurrentReader": address_predecessor_context.get(
                "addressPredecessorLastFillAllStartsPassCurrentReader"
            ),
            "tailExactCurrentRootRefCount": address_predecessor_context.get("addressPredecessorTailCurrentRootExactRefCount"),
            "tailFrontierReaderRefCount": address_predecessor_context.get("addressPredecessorTailFrontierReaderRefCount"),
            "tailSourceRecordRefCount": address_predecessor_context.get("addressPredecessorTailSourceRecordRefCount"),
            "tailTargetRecordRefCount": address_predecessor_context.get("addressPredecessorTailTargetRecordRefCount"),
            "executionOrderProven": address_predecessor_context.get("executionOrderProven"),
            "promotionStatus": address_predecessor_context.get("promotionStatus"),
        },
        "stateEffect": {
            "stateEffectStatus": followup_state.get("stateEffectStatus"),
            "allStartSlotsPassCurrentReader": followup_state.get("allStartSlotsPassCurrentReader"),
            "passingStartSlotCount": followup_state.get("passingStartSlotCount"),
            "uniqueFillValuesHex": followup_state.get("uniqueFillValuesHex") or [],
        },
        "bridgeEvidence": followup_bridge_counts,
        "globalSelectedPointerPathEvidence": global_path_counts,
        "exactFollowupPointerContexts": exact_followup_pointer_contexts,
        "activeOrderRuntimeEvidence": active_order_runtime_evidence,
        "branchStateRuntimeEvidence": branch_state_runtime_evidence,
        "exitCandidateRuntimeEvidence": exit_candidate_runtime_evidence,
        "leftStabilityRuntimeEvidence": left_stability_runtime_evidence,
        "selectorByteWriteEvidence": {
            "selectorWriteRows": followup_selector_write_rows,
            "selectorWriteRowCount": len(followup_selector_write_rows),
            "selectorByteWriteMechanismIdentified": runtime_selector_byte_writes.get(
                "selectorByteWriteMechanismIdentified"
            ),
            "crossWriteToCurrentSelectorCount": (runtime_selector_byte_writes.get("opcode4fDataScan") or {}).get(
                "crossWriteToCurrentSelectorCount"
            ),
            "selectorByteWritePromotesRoute": runtime_selector_byte_writes.get("selectorByteWritePromotesRoute"),
        },
        "runtimeTransitionTimelineAvailable": bool(transition_pair_count),
        "coObservedCurrentAndFollowupInDiagnosticPoll": (
            CURRENT_SELECTOR in observed_selectors and FOLLOWUP_SELECTOR in observed_selectors
        ),
        "observedCurrentThenFollowupInDiagnosticPoll": transition_pair_count > 0,
        "notRoutePromotionProof": True,
        "promotionStatus": "blocked",
        "notRoutePromotionReasons": not_route_promotion_reasons,
        "remainingProofs": [
            "capture a gameplay savedat or equivalent runtime selected-pointer trace for selector 2:0",
            "prove a normal control-flow path from selector 10:0 or another predecessor into the current 2:0 reader",
            "find a strict map1_01a source hotspot or equivalent original transition trigger",
        ],
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    runtime = summary["runtimePoll"]
    alias = summary["followupAlias"]
    address = summary["addressPredecessorEvidence"]
    state = summary["stateEffect"]
    bridge = summary["bridgeEvidence"]
    global_paths = summary["globalSelectedPointerPathEvidence"]
    exact_contexts = summary["exactFollowupPointerContexts"]
    active_order = summary["activeOrderRuntimeEvidence"]
    branch_state = summary["branchStateRuntimeEvidence"]
    exit_candidates = summary["exitCandidateRuntimeEvidence"]
    left_stability = summary["leftStabilityRuntimeEvidence"]
    selector_writes = summary["selectorByteWriteEvidence"]

    def join_values(values: list | None) -> str:
        return ", ".join(str(value) for value in values or [] if value is not None) or "-"
    lines = [
        "# Runtime Patched Selector Follow-up Context",
        "",
        f"- route: `{summary['source']}` -> `{summary['target']}`",
        f"- current selector/root: `{summary['currentSelector']}` / `{summary['currentRootHex']}`",
        f"- follow-up selector/root: `{summary['followupSelector']}` / `{summary['followupRootHex']}`",
        f"- runtime poll: {runtime['sequenceCount']} sequence(s), {runtime['sampleCount']} sample(s), "
        f"observed `{', '.join(runtime['observedSelectors']) or '-'}`",
        f"- staged kind/selectors: `{runtime['stagedSaveKind']}` / `{', '.join(runtime['stagedSelectors']) or '-'}`",
        f"- co-observed current and follow-up in diagnostic poll: {summary['coObservedCurrentAndFollowupInDiagnosticPoll']}",
        f"- sampled current -> follow-up transition rows: {runtime['transitionPairCount']}",
        f"- follow-up selected pointer(s): `{', '.join(runtime['followupSelectedPointerStaticHexes']) or '-'}`",
        f"- exit-candidate diagnostic: available={exit_candidates.get('available')} "
        f"routeSides=`{join_values(exit_candidates.get('routeSelectorSides'))}` "
        f"branchNonzeroSides=`{join_values(exit_candidates.get('branchStateNonzeroSides'))}`",
        f"- left-stability diagnostic: available={left_stability.get('available')} "
        f"routeSequences=`{join_values(left_stability.get('routeSequenceNames'))}` "
        f"nonRouteSequences=`{join_values(left_stability.get('nonRouteSequenceNames'))}` "
        f"opcode24AllZero={left_stability.get('opcode24AllZero')} "
        f"reproducibility={left_stability.get('routeHitReproducibility')}",
        f"- runtime transition timeline available: {summary['runtimeTransitionTimelineAvailable']}",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        summary["conclusion"],
        "",
        "## Runtime Rows",
        "",
        "| sequence | current hits | route hits | selector contexts | sampled transitions |",
        "| --- | ---: | ---: | --- | --- |",
    ]
    for row in runtime["rows"]:
        contexts = ", ".join(
            f"{context['selector']}:{context['count']}@{context['rootHex']}"
            for context in row["contexts"]
        ) or "-"
        transitions = " -> ".join(
            f"{transition['selector']}@{transition['selectedPointerStaticHex']}:{transition['elapsedMs']}ms"
            for transition in row["selectorTransitions"]
        ) or "-"
        lines.append(
            f"| `{row['name']}` | {row['currentRootHitCount']} | {row['routeSelectorHitCount']} | "
            f"`{contexts}` | `{transitions}` |"
        )
    lines.extend([
        "",
        "## Follow-up Selector 10:0",
        "",
        "| property | value |",
        "| --- | --- |",
        f"| role | `{alias['role']}` |",
        f"| root order | `{alias['rootAddressOrderIndex']}` |",
        f"| contains source/target | `{alias['containsSource']}` / `{alias['containsTarget']}` |",
        f"| public samples | `{', '.join(alias['publicSampleIds']) or '-'}` |",
        f"| fills | `{alias['fillCount']}` from `{alias['firstFillHex']}` to `{alias['lastFillHex']}` |",
        f"| address predecessor range | `{address['rangeHex']}` |",
        f"| address predecessor execution proven | `{address['executionOrderProven']}` |",
        f"| modeled state effect | `{state['stateEffectStatus']}`, pass starts `{state['passingStartSlotCount']}`/12 |",
        f"| alias->current hits | `{bridge['aliasToCurrentHitCount']}` total, `{bridge['aliasToCurrentDataHitCount']}` data |",
        f"| after-last-fill execution-like bridge | `{bridge['aliasToCurrentAfterLastFillExecutionLikeBridgeFound']}` |",
        f"| after-last-fill trace writer/reader/scene-record hits | "
        f"`{bridge['aliasToCurrentAfterLastFillTraceCurrentWriterHitCount']}` / "
        f"`{bridge['aliasToCurrentAfterLastFillTraceCurrentReaderHitCount']}` / "
        f"`{bridge['aliasToCurrentAfterLastFillTraceRouteSceneRecordHitCount']}` |",
        f"| selected-pointer promoting candidates | `{global_paths['promotingCandidateCount']}` |",
        f"| selector byte write rows | `{selector_writes['selectorWriteRowCount']}` |",
        "",
        "## Exact Follow-up Pointer Context",
        "",
        "| pointer | root offset | tail | root start | opcodes | opcode20 descriptor | trace stop | exact bridge | nearby bridge dwords | trace refs |",
        "| --- | ---: | --- | --- | --- | --- | --- | --- | ---: | --- |",
    ])
    for context in exact_contexts:
        trace_refs = (
            f"selectedGlobal={context.get('traceContainsSelectedPointerGlobal')}, "
            f"currentRoot={context.get('traceContainsCurrentRootExactRef')}, "
            f"currentRange={context.get('traceContainsCurrentRootRangePointer')}, "
            f"sourceMap={context.get('traceContainsSourceMapString')}, "
            f"targetMap={context.get('traceContainsTargetMapString')}"
        )
        lines.append(
            f"| `{context['pointerVaHex']}` | `{context.get('rootOffsetHex')}` | "
            f"`{context.get('withinAddressPredecessorTail')}` | `{context.get('startsAtAliasRoot')}` | "
            f"`{context.get('firstOpcodeHex')},{context.get('secondOpcodeHex')}` | "
            f"`{context.get('opcode20DescriptorPointerHex')}` | `{context.get('traceStopReason')}` | "
            f"`{context.get('exactSelectedPointerDwordIsCurrentRangeBridge')}` | "
            f"`{context.get('nearbyCurrentRangeBridgeDwordCount')}` | `{trace_refs}` |"
        )
    lines.extend([
        "",
        "### Exact Pointer Trace",
        "",
    ])
    for context in exact_contexts:
        lines.extend([
            f"#### {context['pointerVaHex']}",
            "",
            "| step | va | value | opcode | handler | stop |",
            "| ---: | --- | --- | --- | --- | --- |",
        ])
        for trace in context.get("trace") or []:
            lines.append(
                f"| {trace.get('step')} | `{trace.get('vaHex')}` | `{trace.get('valueHex')}` | "
                f"`{trace.get('opcodeHex')}` | `{trace.get('handlerVaHex')}` | "
                f"{trace.get('stopReason') or '-'} |"
            )
        lines.append("")
    lines.extend([
        "## Runtime Active Order Watch",
        "",
        "| property | value |",
        "| --- | --- |",
        f"| source poll | `{active_order.get('sourcePoll')}` |",
        f"| available | `{active_order.get('available')}` |",
        f"| route samples | `{active_order.get('sampleCount')}` across `{active_order.get('sequenceCount')}` route-reaching sequence(s) |",
        f"| total samples | `{active_order.get('totalSampleCount')}` across `{active_order.get('totalSequenceCount')}` sequence(s) |",
        f"| route sequence names | `{join_values(active_order.get('routeSequenceNames'))}` |",
        f"| non-route sequences | `{active_order.get('nonRouteSequenceCount')}` |",
        f"| observed selectors | `{join_values(active_order.get('observedSelectors'))}` |",
        f"| staged selectors | `{join_values(active_order.get('stagedSelectors'))}` |",
        f"| reached current/route | `{active_order.get('reachedCurrentRoot')}` / `{active_order.get('reachedRouteSelector')}` |",
        f"| loaded base | `{active_order.get('loadedBaseHex')}` |",
        f"| active order count | `{active_order.get('activeOrderCountHex')}` |",
        f"| active order bytes | `{join_values(active_order.get('orderByteHexes'))}` |",
        f"| active order used bytes | `{join_values(active_order.get('activeOrderHexes'))}` |",
        f"| active slot first dwords | `{join_values(active_order.get('activeSlotFirstDwordsHex'))}` |",
        f"| active slot first dwords static | `{join_values(active_order.get('activeSlotFirstDwordsStaticHex'))}` |",
        f"| runtime slot-base table | `{join_values(active_order.get('runtimeSlotBaseTableHexes'))}` |",
        f"| runtime slot-base table static | `{join_values(active_order.get('runtimeSlotBaseTableStaticHexes'))}` |",
        f"| runtime object table | `{join_values(active_order.get('runtimeObjectTableHexes'))}` |",
        f"| runtime object table static | `{join_values(active_order.get('runtimeObjectTableStaticHexes'))}` |",
        f"| all watched values stable | `{active_order.get('allWatchedValuesStable')}` |",
        f"| promotion status | `{active_order.get('promotionStatus')}` |",
        "",
    ])
    lines.extend([
        "## Runtime Branch State Watch",
        "",
        "| property | value |",
        "| --- | --- |",
        f"| source poll | `{branch_state.get('sourcePoll')}` |",
        f"| available | `{branch_state.get('available')}` |",
        f"| route samples | `{branch_state.get('sampleCount')}` across `{branch_state.get('sequenceCount')}` route-reaching sequence(s) |",
        f"| total samples | `{branch_state.get('totalSampleCount')}` across `{branch_state.get('totalSequenceCount')}` sequence(s) |",
        f"| route sequence names | `{join_values(branch_state.get('routeSequenceNames'))}` |",
        f"| non-route sequences | `{branch_state.get('nonRouteSequenceCount')}` |",
        f"| observed selectors | `{join_values(branch_state.get('observedSelectors'))}` |",
        f"| staged selectors | `{join_values(branch_state.get('stagedSelectors'))}` |",
        f"| reached current/route | `{branch_state.get('reachedCurrentRoot')}` / `{branch_state.get('reachedRouteSelector')}` |",
        f"| active selection flag | `{branch_state.get('activeSelectionFlagHex')}` |",
        f"| route active selection flag | `{branch_state.get('routeActiveSelectionFlagHex')}` |",
        f"| opcode24 mode/runtime/object | `{branch_state.get('opcode24Mode1SourceHex')}` / `{branch_state.get('opcode24RuntimeFlagHex')}` / `{branch_state.get('opcode24CurrentObjectIndexHex')}` |",
        f"| secondary branch state | `{join_values(branch_state.get('secondaryBranchStateHexes'))}` |",
        f"| route secondary branch state | `{join_values(branch_state.get('routeSecondaryBranchStateHexes'))}` |",
        f"| secondary branch state all zero | `{branch_state.get('secondaryBranchStateAllZero')}` |",
        f"| route secondary branch state all zero | `{branch_state.get('routeSecondaryBranchStateAllZero')}` |",
        f"| matches predecessor fill hypothesis | `{branch_state.get('matchesPredecessorFillHypothesis')}` |",
        f"| all watched values stable | `{branch_state.get('allWatchedValuesStable')}` |",
        f"| promotion status | `{branch_state.get('promotionStatus')}` |",
        "",
    ])
    lines.extend([
        "## Exit-candidate Diagnostic",
        "",
        "| side | tile | samples | selectors | route 2:0 | branch nonzero | mode1 | runtime flag | object index |",
        "| --- | --- | ---: | --- | --- | --- | --- | --- | --- |",
    ])
    for row in exit_candidates.get("candidateRows") or []:
        tile = row.get("tile") or {}
        lines.append(
            f"| {row.get('side')} | `{tile.get('x')},{tile.get('y')}` | {row.get('sampleCount')} | "
            f"`{row.get('selectorCounts') or '-'}` | {row.get('reachedRouteSelector')} | "
            f"{row.get('branchStateNonzero')} | `{row.get('opcode24Mode1SourceValues')}` | "
            f"`{row.get('opcode24RuntimeFlagValues')}` | `{row.get('opcode24CurrentObjectIndexValues')}` |"
        )
    lines.append("")
    lines.extend([
        "## Left-stability Diagnostic",
        "",
        "| sequence | keys | samples | selectors | route hits | mode1 | runtime flag | object index |",
        "| --- | --- | ---: | --- | ---: | --- | --- | --- |",
    ])
    for row in left_stability.get("sequenceRows") or []:
        lines.append(
            f"| `{row.get('name')}` | `{join_values(row.get('keys'))}` | {row.get('sampleCount')} | "
            f"`{row.get('selectorCounts') or '-'}` | {row.get('routeSelectorHitCount')} | "
            f"`{left_stability.get('opcode24Mode1SourceValues')}` | "
            f"`{left_stability.get('opcode24RuntimeFlagValues')}` | "
            f"`{left_stability.get('opcode24CurrentObjectIndexValues')}` |"
        )
    lines.append("")
    for label, recheck in [
        ("selector-only recheck", left_stability.get("recheck") or {}),
        ("active-order recheck", left_stability.get("activeOrderRecheck") or {}),
    ]:
        lines.extend([
            f"### {label}",
            "",
            "| source poll | samples | selectors | route sequences | route hits | active order count | slot0 descriptor | runtime slot-base table0 | opcode24 all zero |",
            "| --- | ---: | --- | --- | ---: | --- | --- | --- | --- |",
            f"| `{recheck.get('sourcePoll') or '-'}` | {recheck.get('sampleCount')} | "
            f"`{join_values(recheck.get('observedSelectors'))}` | "
            f"`{join_values(recheck.get('routeSequenceNames'))}` | "
            f"{recheck.get('routeSelectorHitCount')} | "
            f"`{recheck.get('activeOrderCountValues') or '-'}` | "
            f"`{recheck.get('activeSlot0DescriptorValues') or '-'}` | "
            f"`{recheck.get('runtimeSlotBaseTable0Values') or '-'}` | "
            f"{recheck.get('allSamplesOpcode24Zero')} |",
            "",
        ])
    lines.extend([
        "## Non-promotion Reasons",
        "",
    ])
    lines.extend(f"- {reason}" for reason in summary["notRoutePromotionReasons"])
    lines.extend(["", "## Remaining Proofs", ""])
    lines.extend(f"- {proof}" for proof in summary["remainingProofs"])
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    runtime = summary["runtimePoll"]
    alias = summary["followupAlias"]
    address = summary["addressPredecessorEvidence"]
    state = summary["stateEffect"]
    bridge = summary["bridgeEvidence"]
    global_paths = summary["globalSelectedPointerPathEvidence"]
    exact_contexts = summary["exactFollowupPointerContexts"]
    active_order = summary["activeOrderRuntimeEvidence"]
    branch_state = summary["branchStateRuntimeEvidence"]
    exit_candidates = summary["exitCandidateRuntimeEvidence"]
    left_stability = summary["leftStabilityRuntimeEvidence"]
    selector_writes = summary["selectorByteWriteEvidence"]

    def join_values(values: list | None) -> str:
        return ", ".join(str(value) for value in values or [] if value is not None) or "-"

    def context_text(row: dict) -> str:
        return ", ".join(
            f"{context['selector']}:{context['count']}@{context['rootHex']}"
            for context in row["contexts"]
        ) or "-"

    def transition_text(row: dict) -> str:
        return " -> ".join(
            f"{transition['selector']}@{transition['selectedPointerStaticHex']}:{transition['elapsedMs']}ms"
            for transition in row["selectorTransitions"]
        ) or "-"

    runtime_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(row['name']))}</code></td>"
        f"<td>{html.escape(str(row['currentRootHitCount']))}</td>"
        f"<td>{html.escape(str(row['routeSelectorHitCount']))}</td>"
        f"<td><code>{html.escape(context_text(row))}</code></td>"
        f"<td><code>{html.escape(transition_text(row))}</code></td>"
        "</tr>"
        for row in runtime["rows"]
    )
    exact_context_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(context['pointerVaHex']))}</code></td>"
        f"<td><code>{html.escape(str(context.get('rootOffsetHex')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('withinAddressPredecessorTail')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('startsAtAliasRoot')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('firstOpcodeHex')))},"
        f"{html.escape(str(context.get('secondOpcodeHex')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('opcode20DescriptorPointerHex')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('traceStopReason')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('exactSelectedPointerDwordIsCurrentRangeBridge')))}</code></td>"
        f"<td><code>{html.escape(str(context.get('nearbyCurrentRangeBridgeDwordCount')))}</code></td>"
        "<td><code>"
        f"selectedGlobal={html.escape(str(context.get('traceContainsSelectedPointerGlobal')))}, "
        f"currentRoot={html.escape(str(context.get('traceContainsCurrentRootExactRef')))}, "
        f"currentRange={html.escape(str(context.get('traceContainsCurrentRootRangePointer')))}, "
        f"sourceMap={html.escape(str(context.get('traceContainsSourceMapString')))}, "
        f"targetMap={html.escape(str(context.get('traceContainsTargetMapString')))}"
        "</code></td>"
        "</tr>"
        for context in exact_contexts
    )
    exact_trace_sections = []
    for context in exact_contexts:
        trace_rows = "\n".join(
            "<tr>"
            f"<td>{html.escape(str(trace.get('step')))}</td>"
            f"<td><code>{html.escape(str(trace.get('vaHex')))}</code></td>"
            f"<td><code>{html.escape(str(trace.get('valueHex')))}</code></td>"
            f"<td><code>{html.escape(str(trace.get('opcodeHex')))}</code></td>"
            f"<td><code>{html.escape(str(trace.get('handlerVaHex')))}</code></td>"
            f"<td>{html.escape(str(trace.get('stopReason') or '-'))}</td>"
            "</tr>"
            for trace in context.get("trace") or []
        )
        exact_trace_sections.append(
            f"<h3><code>{html.escape(str(context['pointerVaHex']))}</code></h3>"
            "<table><thead><tr><th>step</th><th>va</th><th>value</th><th>opcode</th><th>handler</th><th>stop</th></tr></thead><tbody>"
            f"{trace_rows}</tbody></table>"
        )
    active_order_rows = "\n".join(
        [
            f"<tr><th>source poll</th><td><code>{html.escape(str(active_order.get('sourcePoll')))}</code></td></tr>",
            f"<tr><th>available</th><td><code>{html.escape(str(active_order.get('available')))}</code></td></tr>",
            f"<tr><th>route samples</th><td><code>{html.escape(str(active_order.get('sampleCount')))}</code> across <code>{html.escape(str(active_order.get('sequenceCount')))}</code> route-reaching sequence(s)</td></tr>",
            f"<tr><th>total samples</th><td><code>{html.escape(str(active_order.get('totalSampleCount')))}</code> across <code>{html.escape(str(active_order.get('totalSequenceCount')))}</code> sequence(s)</td></tr>",
            f"<tr><th>route sequence names</th><td><code>{html.escape(join_values(active_order.get('routeSequenceNames')))}</code></td></tr>",
            f"<tr><th>non-route sequences</th><td><code>{html.escape(str(active_order.get('nonRouteSequenceCount')))}</code></td></tr>",
            f"<tr><th>observed selectors</th><td><code>{html.escape(join_values(active_order.get('observedSelectors')))}</code></td></tr>",
            f"<tr><th>staged selectors</th><td><code>{html.escape(join_values(active_order.get('stagedSelectors')))}</code></td></tr>",
            f"<tr><th>reached current/route</th><td><code>{html.escape(str(active_order.get('reachedCurrentRoot')))}</code> / <code>{html.escape(str(active_order.get('reachedRouteSelector')))}</code></td></tr>",
            f"<tr><th>loaded base</th><td><code>{html.escape(str(active_order.get('loadedBaseHex')))}</code></td></tr>",
            f"<tr><th>active order count</th><td><code>{html.escape(str(active_order.get('activeOrderCountHex')))}</code></td></tr>",
            f"<tr><th>active order bytes</th><td><code>{html.escape(join_values(active_order.get('orderByteHexes')))}</code></td></tr>",
            f"<tr><th>active order used bytes</th><td><code>{html.escape(join_values(active_order.get('activeOrderHexes')))}</code></td></tr>",
            f"<tr><th>active slot first dwords</th><td><code>{html.escape(join_values(active_order.get('activeSlotFirstDwordsHex')))}</code></td></tr>",
            f"<tr><th>active slot first dwords static</th><td><code>{html.escape(join_values(active_order.get('activeSlotFirstDwordsStaticHex')))}</code></td></tr>",
            f"<tr><th>runtime slot-base table</th><td><code>{html.escape(join_values(active_order.get('runtimeSlotBaseTableHexes')))}</code></td></tr>",
            f"<tr><th>runtime slot-base table static</th><td><code>{html.escape(join_values(active_order.get('runtimeSlotBaseTableStaticHexes')))}</code></td></tr>",
            f"<tr><th>runtime object table</th><td><code>{html.escape(join_values(active_order.get('runtimeObjectTableHexes')))}</code></td></tr>",
            f"<tr><th>runtime object table static</th><td><code>{html.escape(join_values(active_order.get('runtimeObjectTableStaticHexes')))}</code></td></tr>",
            f"<tr><th>all watched values stable</th><td><code>{html.escape(str(active_order.get('allWatchedValuesStable')))}</code></td></tr>",
            f"<tr><th>promotion status</th><td><code>{html.escape(str(active_order.get('promotionStatus')))}</code></td></tr>",
        ]
    )
    branch_state_rows = "\n".join(
        [
            f"<tr><th>source poll</th><td><code>{html.escape(str(branch_state.get('sourcePoll')))}</code></td></tr>",
            f"<tr><th>available</th><td><code>{html.escape(str(branch_state.get('available')))}</code></td></tr>",
            f"<tr><th>route samples</th><td><code>{html.escape(str(branch_state.get('sampleCount')))}</code> across <code>{html.escape(str(branch_state.get('sequenceCount')))}</code> route-reaching sequence(s)</td></tr>",
            f"<tr><th>total samples</th><td><code>{html.escape(str(branch_state.get('totalSampleCount')))}</code> across <code>{html.escape(str(branch_state.get('totalSequenceCount')))}</code> sequence(s)</td></tr>",
            f"<tr><th>route sequence names</th><td><code>{html.escape(join_values(branch_state.get('routeSequenceNames')))}</code></td></tr>",
            f"<tr><th>non-route sequences</th><td><code>{html.escape(str(branch_state.get('nonRouteSequenceCount')))}</code></td></tr>",
            f"<tr><th>observed selectors</th><td><code>{html.escape(join_values(branch_state.get('observedSelectors')))}</code></td></tr>",
            f"<tr><th>staged selectors</th><td><code>{html.escape(join_values(branch_state.get('stagedSelectors')))}</code></td></tr>",
            f"<tr><th>reached current/route</th><td><code>{html.escape(str(branch_state.get('reachedCurrentRoot')))}</code> / <code>{html.escape(str(branch_state.get('reachedRouteSelector')))}</code></td></tr>",
            f"<tr><th>active selection flag</th><td><code>{html.escape(str(branch_state.get('activeSelectionFlagHex')))}</code></td></tr>",
            f"<tr><th>route active selection flag</th><td><code>{html.escape(str(branch_state.get('routeActiveSelectionFlagHex')))}</code></td></tr>",
            f"<tr><th>opcode24 mode/runtime/object</th><td><code>{html.escape(str(branch_state.get('opcode24Mode1SourceHex')))}</code> / <code>{html.escape(str(branch_state.get('opcode24RuntimeFlagHex')))}</code> / <code>{html.escape(str(branch_state.get('opcode24CurrentObjectIndexHex')))}</code></td></tr>",
            f"<tr><th>secondary branch state</th><td><code>{html.escape(join_values(branch_state.get('secondaryBranchStateHexes')))}</code></td></tr>",
            f"<tr><th>route secondary branch state</th><td><code>{html.escape(join_values(branch_state.get('routeSecondaryBranchStateHexes')))}</code></td></tr>",
            f"<tr><th>secondary branch state all zero</th><td><code>{html.escape(str(branch_state.get('secondaryBranchStateAllZero')))}</code></td></tr>",
            f"<tr><th>route secondary branch state all zero</th><td><code>{html.escape(str(branch_state.get('routeSecondaryBranchStateAllZero')))}</code></td></tr>",
            f"<tr><th>matches predecessor fill hypothesis</th><td><code>{html.escape(str(branch_state.get('matchesPredecessorFillHypothesis')))}</code></td></tr>",
            f"<tr><th>all watched values stable</th><td><code>{html.escape(str(branch_state.get('allWatchedValuesStable')))}</code></td></tr>",
            f"<tr><th>promotion status</th><td><code>{html.escape(str(branch_state.get('promotionStatus')))}</code></td></tr>",
        ]
    )
    exit_candidate_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(str(row.get('side')))}</td>"
        f"<td><code>{html.escape(str((row.get('tile') or {}).get('x')) + ',' + str((row.get('tile') or {}).get('y')))}</code></td>"
        f"<td>{html.escape(str(row.get('sampleCount')))}</td>"
        f"<td><code>{html.escape(str(row.get('selectorCounts') or '-'))}</code></td>"
        f"<td>{html.escape(str(row.get('reachedRouteSelector')))}</td>"
        f"<td>{html.escape(str(row.get('branchStateNonzero')))}</td>"
        f"<td><code>{html.escape(str(row.get('opcode24Mode1SourceValues')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('opcode24RuntimeFlagValues')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('opcode24CurrentObjectIndexValues')))}</code></td>"
        "</tr>"
        for row in exit_candidates.get("candidateRows") or []
    )
    left_stability_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(row.get('name')))}</code></td>"
        f"<td><code>{html.escape(join_values(row.get('keys')))}</code></td>"
        f"<td>{html.escape(str(row.get('sampleCount')))}</td>"
        f"<td><code>{html.escape(str(row.get('selectorCounts') or '-'))}</code></td>"
        f"<td>{html.escape(str(row.get('routeSelectorHitCount')))}</td>"
        f"<td><code>{html.escape(str(left_stability.get('opcode24Mode1SourceValues')))}</code></td>"
        f"<td><code>{html.escape(str(left_stability.get('opcode24RuntimeFlagValues')))}</code></td>"
        f"<td><code>{html.escape(str(left_stability.get('opcode24CurrentObjectIndexValues')))}</code></td>"
        "</tr>"
        for row in left_stability.get("sequenceRows") or []
    )
    left_stability_recheck_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(label)}</td>"
        f"<td><code>{html.escape(str(recheck.get('sourcePoll') or '-'))}</code></td>"
        f"<td>{html.escape(str(recheck.get('sampleCount')))}</td>"
        f"<td><code>{html.escape(join_values(recheck.get('observedSelectors')))}</code></td>"
        f"<td><code>{html.escape(join_values(recheck.get('routeSequenceNames')))}</code></td>"
        f"<td>{html.escape(str(recheck.get('routeSelectorHitCount')))}</td>"
        f"<td><code>{html.escape(str(recheck.get('activeOrderCountValues') or '-'))}</code></td>"
        f"<td><code>{html.escape(str(recheck.get('activeSlot0DescriptorValues') or '-'))}</code></td>"
        f"<td><code>{html.escape(str(recheck.get('runtimeSlotBaseTable0Values') or '-'))}</code></td>"
        f"<td>{html.escape(str(recheck.get('allSamplesOpcode24Zero')))}</td>"
        "</tr>"
        for label, recheck in [
            ("selector-only recheck", left_stability.get("recheck") or {}),
            ("active-order recheck", left_stability.get("activeOrderRecheck") or {}),
        ]
    )
    reasons = "".join(f"<li>{html.escape(reason)}</li>" for reason in summary["notRoutePromotionReasons"])
    proofs = "".join(f"<li>{html.escape(proof)}</li>" for proof in summary["remainingProofs"])
    return "\n".join([
        "<!doctype html><meta charset=\"utf-8\"><title>Runtime Patched Selector Follow-up Context</title>",
        "<style>body{font-family:system-ui,sans-serif;background:#111;color:#eee;max-width:1120px;margin:24px auto}table{border-collapse:collapse;width:100%;margin:16px 0}td,th{border:1px solid #444;padding:6px 8px;vertical-align:top}code{color:#9bd4ff}</style>",
        "<h1>Runtime Patched Selector Follow-up Context</h1>",
        "<ul>",
        f"<li>route: <code>{html.escape(summary['source'])}</code> -&gt; <code>{html.escape(summary['target'])}</code></li>",
        f"<li>current selector/root: <code>{html.escape(summary['currentSelector'])}</code> / <code>{html.escape(summary['currentRootHex'])}</code></li>",
        f"<li>follow-up selector/root: <code>{html.escape(summary['followupSelector'])}</code> / <code>{html.escape(summary['followupRootHex'])}</code></li>",
        f"<li>runtime poll: {html.escape(str(runtime['sequenceCount']))} sequence(s), {html.escape(str(runtime['sampleCount']))} sample(s), observed <code>{html.escape(', '.join(runtime['observedSelectors']) or '-')}</code></li>",
        f"<li>staged kind/selectors: <code>{html.escape(str(runtime['stagedSaveKind']))}</code> / <code>{html.escape(', '.join(runtime['stagedSelectors']) or '-')}</code></li>",
        f"<li>co-observed current and follow-up in diagnostic poll: {summary['coObservedCurrentAndFollowupInDiagnosticPoll']}</li>",
        f"<li>sampled current -&gt; follow-up transition rows: {html.escape(str(runtime['transitionPairCount']))}</li>",
        f"<li>follow-up selected pointer(s): <code>{html.escape(', '.join(runtime['followupSelectedPointerStaticHexes']) or '-')}</code></li>",
        f"<li>exit-candidate diagnostic: available={html.escape(str(exit_candidates.get('available')))}, routeSides=<code>{html.escape(join_values(exit_candidates.get('routeSelectorSides')))}</code>, branchNonzeroSides=<code>{html.escape(join_values(exit_candidates.get('branchStateNonzeroSides')))}</code></li>",
        f"<li>left-stability diagnostic: available={html.escape(str(left_stability.get('available')))}, routeSequences=<code>{html.escape(join_values(left_stability.get('routeSequenceNames')))}</code>, nonRouteSequences=<code>{html.escape(join_values(left_stability.get('nonRouteSequenceNames')))}</code>, opcode24AllZero=<code>{html.escape(str(left_stability.get('opcode24AllZero')))}</code>, reproducibility=<code>{html.escape(str(left_stability.get('routeHitReproducibility')))}</code></li>",
        f"<li>runtime transition timeline available: {summary['runtimeTransitionTimelineAvailable']}</li>",
        f"<li>promotion status: <code>{html.escape(summary['promotionStatus'])}</code></li>",
        "</ul>",
        f"<p>{html.escape(summary['conclusion'])}</p>",
        "<h2>Runtime Rows</h2>",
        "<table><thead><tr><th>sequence</th><th>current hits</th><th>route hits</th><th>selector contexts</th><th>sampled transitions</th></tr></thead><tbody>",
        runtime_rows,
        "</tbody></table>",
        "<h2>Follow-up Selector 10:0</h2>",
        "<table><tbody>",
        f"<tr><th>role</th><td><code>{html.escape(str(alias['role']))}</code></td></tr>",
        f"<tr><th>root order</th><td><code>{html.escape(str(alias['rootAddressOrderIndex']))}</code></td></tr>",
        f"<tr><th>contains source/target</th><td><code>{alias['containsSource']}</code> / <code>{alias['containsTarget']}</code></td></tr>",
        f"<tr><th>public samples</th><td><code>{html.escape(', '.join(alias['publicSampleIds']) or '-')}</code></td></tr>",
        f"<tr><th>fills</th><td><code>{html.escape(str(alias['fillCount']))}</code> from <code>{html.escape(str(alias['firstFillHex']))}</code> to <code>{html.escape(str(alias['lastFillHex']))}</code></td></tr>",
        f"<tr><th>address predecessor range</th><td><code>{html.escape(str(address['rangeHex']))}</code></td></tr>",
        f"<tr><th>address predecessor execution proven</th><td><code>{html.escape(str(address['executionOrderProven']))}</code></td></tr>",
        f"<tr><th>modeled state effect</th><td><code>{html.escape(str(state['stateEffectStatus']))}</code>, pass starts <code>{html.escape(str(state['passingStartSlotCount']))}</code>/12</td></tr>",
        f"<tr><th>alias-&gt;current hits</th><td><code>{html.escape(str(bridge['aliasToCurrentHitCount']))}</code> total, <code>{html.escape(str(bridge['aliasToCurrentDataHitCount']))}</code> data</td></tr>",
        f"<tr><th>after-last-fill execution-like bridge</th><td><code>{html.escape(str(bridge['aliasToCurrentAfterLastFillExecutionLikeBridgeFound']))}</code></td></tr>",
        f"<tr><th>after-last-fill trace writer/reader/scene-record hits</th><td><code>{html.escape(str(bridge['aliasToCurrentAfterLastFillTraceCurrentWriterHitCount']))}</code> / <code>{html.escape(str(bridge['aliasToCurrentAfterLastFillTraceCurrentReaderHitCount']))}</code> / <code>{html.escape(str(bridge['aliasToCurrentAfterLastFillTraceRouteSceneRecordHitCount']))}</code></td></tr>",
        f"<tr><th>selected-pointer promoting candidates</th><td><code>{html.escape(str(global_paths['promotingCandidateCount']))}</code></td></tr>",
        f"<tr><th>selector byte write rows</th><td><code>{html.escape(str(selector_writes['selectorWriteRowCount']))}</code></td></tr>",
        "</tbody></table>",
        "<h2>Exact Follow-up Pointer Context</h2>",
        "<table><thead><tr><th>pointer</th><th>root offset</th><th>tail</th><th>root start</th><th>opcodes</th><th>opcode20 descriptor</th><th>trace stop</th><th>exact bridge</th><th>nearby bridge dwords</th><th>trace refs</th></tr></thead><tbody>",
        exact_context_rows,
        "</tbody></table>",
        "<h2>Exact Pointer Trace</h2>",
        "\n".join(exact_trace_sections),
        "<h2>Runtime Active Order Watch</h2>",
        "<table><tbody>",
        active_order_rows,
        "</tbody></table>",
        "<h2>Runtime Branch State Watch</h2>",
        "<table><tbody>",
        branch_state_rows,
        "</tbody></table>",
        "<h2>Exit-candidate Diagnostic</h2>",
        "<table><thead><tr><th>side</th><th>tile</th><th>samples</th><th>selectors</th><th>route 2:0</th><th>branch nonzero</th><th>mode1</th><th>runtime flag</th><th>object index</th></tr></thead><tbody>",
        exit_candidate_rows,
        "</tbody></table>",
        "<h2>Left-stability Diagnostic</h2>",
        "<table><thead><tr><th>sequence</th><th>keys</th><th>samples</th><th>selectors</th><th>route hits</th><th>mode1</th><th>runtime flag</th><th>object index</th></tr></thead><tbody>",
        left_stability_rows,
        "</tbody></table>",
        "<h3>Left-stability Rechecks</h3>",
        "<table><thead><tr><th>kind</th><th>source poll</th><th>samples</th><th>selectors</th><th>route sequences</th><th>route hits</th><th>active order count</th><th>slot0 descriptor</th><th>runtime slot-base table0</th><th>opcode24 all zero</th></tr></thead><tbody>",
        left_stability_recheck_rows,
        "</tbody></table>",
        "<h2>Non-promotion Reasons</h2>",
        f"<ul>{reasons}</ul>",
        "<h2>Remaining Proofs</h2>",
        f"<ul>{proofs}</ul>",
    ])


def write_outputs(summary: dict, out_dir: Path = OUT, html_out: Path | None = None) -> Path:
    out_dir.mkdir(parents=True, exist_ok=True)
    json_out = out_dir / "runtime_patched_selector_followup_context.json"
    json_out.write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    if html_out is not None:
        html_out.parent.mkdir(parents=True, exist_ok=True)
        html_out.write_text(html_page(summary), encoding="utf-8")
    return json_out


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--poll",
        type=Path,
        default=OUT / "runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.json",
    )
    parser.add_argument("--mapset-aliases", type=Path, default=OUT / "save_selector_mapset_aliases.json")
    parser.add_argument(
        "--address-predecessor-context",
        type=Path,
        default=OUT / "save_selector_address_predecessor_context.json",
    )
    parser.add_argument(
        "--target-alias-state-effects",
        type=Path,
        default=OUT / "save_selector_target_alias_state_effects.json",
    )
    parser.add_argument("--target-alias-bridges", type=Path, default=OUT / "save_selector_target_alias_bridges.json")
    parser.add_argument(
        "--global-selected-pointer-paths",
        type=Path,
        default=OUT / "save_selector_global_selected_pointer_paths.json",
    )
    parser.add_argument(
        "--runtime-selector-byte-writes",
        type=Path,
        default=OUT / "save_selector_runtime_selector_byte_writes.json",
    )
    parser.add_argument(
        "--active-order-poll",
        type=Path,
        default=OUT / "runtime_selected_pointer_patched_public_selector_2_0_active_order_poll.json",
    )
    parser.add_argument(
        "--branch-state-poll",
        type=Path,
        default=OUT / "runtime_selected_pointer_patched_public_selector_2_0_branch_state_poll.json",
    )
    parser.add_argument(
        "--exit-candidate-poll",
        type=Path,
        default=OUT / "runtime_patched_selector_exit_candidates_poll.json",
    )
    parser.add_argument(
        "--left-stability-poll",
        type=Path,
        default=OUT / "runtime_patched_selector_left_stability_poll.json",
    )
    parser.add_argument(
        "--left-stability-recheck-poll",
        type=Path,
        default=OUT / "runtime_patched_selector_left_stability_recheck_poll.json",
    )
    parser.add_argument(
        "--left-active-order-poll",
        type=Path,
        default=OUT / "runtime_patched_selector_left_active_order_poll.json",
    )
    parser.add_argument("--exe", type=Path, default=EXE)
    parser.add_argument("--out-dir", type=Path, default=OUT)
    parser.add_argument(
        "--html-out",
        type=Path,
        default=None,
        help="Optional legacy HTML output path. JSON is the default retained artifact.",
    )
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.poll, {}),
        load_json(args.mapset_aliases, {}),
        load_json(args.address_predecessor_context, {}),
        load_json(args.target_alias_state_effects, {}),
        load_json(args.target_alias_bridges, {}),
        load_json(args.global_selected_pointer_paths, {}),
        load_json(args.runtime_selector_byte_writes, {}),
        load_json(args.active_order_poll, {}),
        load_json(args.branch_state_poll, {}),
        load_json(args.exit_candidate_poll, {}),
        load_json(args.left_stability_poll, {}),
        load_json(args.left_stability_recheck_poll, {}),
        load_json(args.left_active_order_poll, {}),
        args.exe,
    )
    json_out = write_outputs(summary, args.out_dir, args.html_out)
    print(f"wrote runtime patched selector follow-up context -> {json_out}")


if __name__ == "__main__":
    main()
