#!/usr/bin/env python3
"""Consolidate selected-root execution evidence for the current route blocker."""
from __future__ import annotations

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

from probe_exe_scene_tables import read_sections
from summarize_save_selector_predecessor_fill_execution_order_gap import (
    bounded_code_window,
    count_rows_by_group,
    dword_immediate_hits,
    hex32,
    hex_to_int,
    rel32_transfer_rows,
)


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"

SOURCE = "map1_01a"
TARGET = "map2_02d"
CURRENT_SELECTOR = "2:0"
CURRENT_ROOT_HEX = "0x00540714"
SELECTED_POINTER_GLOBAL_HEX = "0x0059de30"
WATCH_VALUE_ORDER = (
    "opcode24Mode1Source",
    "opcode24CurrentObjectIndex",
    "opcode24RuntimeFlag",
)
SELECTED_POINTER_HANDLER_MAX_BYTES = 0x400
SELECTED_POINTER_HANDLER_CALLEE_MAX_BYTES = 0x300
SELECTED_POINTER_HANDLER_CALL_GRAPH_MAX_DEPTH = 3
SELECTED_POINTER_HANDLER_CALL_GRAPH_DEPTH_SENSITIVITY_DEPTHS = [1, 2, 3, 4]


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


def watch_value(summary: dict, name: str) -> dict:
    for row in summary.get("watchValues") or []:
        if row.get("name") == name:
            return row
    return {}


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


def predecessor_route_attempt_summary(context: dict | None) -> str:
    if not context:
        return "-"
    public_context = context.get("publicPredecessorSelectorContext") or {}
    return (
        f"files={context.get('sourceFileCount')}; "
        f"seq={context.get('totalSequenceCount')}; "
        f"samples={context.get('totalSampleCount')}; "
        f"publicFiles={context.get('publicPredecessorObservedFileCount')}; "
        f"routeHits={context.get('routeSelectorHitCount')}; "
        f"currentRootHits={context.get('currentRootHitCount')}; "
        f"dominantDiversion={context.get('dominantDiversionSelector')}; "
        "diversionContexts="
        f"{context.get('diversionSelectorContextCount')}/"
        f"{context.get('fieldMapDiversionSelectorCount')}/"
        f"{context.get('resourceOnlyDiversionSelectorCount')}; "
        f"diversionRouteEvidence={context.get('diversionRoutePromotionEvidenceFound')}; "
        f"publicContext={public_context.get('classification')}; "
        f"status={context.get('promotionStatus')}"
    )


def selected_pointer_handler_target_rows(selected_pointer_usage: dict) -> list[dict]:
    target_specs = [
        ("selected-pointer-global", "selected-pointer-global", "selected-pointer"),
        ("selector-group-table", "selector-group-table", "selector-table"),
        ("source-selector-row-0:0", "source-selector-row", "route-selector"),
        ("source-selector-root-0:0", "source-selector-root", "route-selector"),
        ("target-selector-row-1:0", "target-selector-row", "route-selector"),
        ("target-selector-root-1:0", "target-selector-root", "route-selector"),
        ("current-selector-row-2:0", "current-selector-row", "current"),
        ("current-selector-root-2:0", "current-selector-root", "current"),
        ("current-second-level-table-2:0", "current-second-level-table", "current"),
        ("current-frontier-leaf-2:0", "current-frontier-leaf", "current"),
        ("current-frontier-reader-2:0", "current-frontier-reader", "current"),
        ("current-source-record-map1_01a", "current-source-record", "route-record"),
        ("current-target-record-map2_02d", "current-target-record", "route-record"),
    ]
    fallback_hexes = {
        "selected-pointer-global": SELECTED_POINTER_GLOBAL_HEX,
        "current-selector-root-2:0": CURRENT_ROOT_HEX,
        "current-frontier-reader-2:0": "0x00542b0c",
        "current-source-record-map1_01a": "0x00542b44",
        "current-target-record-map2_02d": "0x00542bac",
    }
    rows: list[dict] = []
    seen: set[int] = set()

    def add_row(label: str, va_hex: str | None, group: str) -> None:
        va = hex_to_int(va_hex)
        if va is None or va in seen:
            return
        seen.add(va)
        rows.append({
            "label": label,
            "va": va,
            "vaHex": hex32(va),
            "group": group,
        })

    for name, label, group in target_specs:
        row = watch_value(selected_pointer_usage, name)
        add_row(label, row.get("valueHex") or fallback_hexes.get(name), group)
    for index in range(12):
        va = 0x0059E360 + index
        add_row(f"secondary-branch-state-{index}", hex32(va), "branch-state")
    return rows


def selected_pointer_handler_call_graph_roots(selected_pointer_usage: dict) -> list[dict]:
    rows = []
    seen: set[int] = set()
    for context in selected_pointer_usage.get("selectedPointerHandlerContexts") or []:
        handler_hex = context.get("handlerVaHex")
        handler_va = hex_to_int(handler_hex)
        if handler_va is None or handler_va in seen:
            continue
        seen.add(handler_va)
        rows.append({
            "label": context.get("name") or f"handler:{handler_hex}",
            "handlerVaHex": handler_hex,
            "hookVaHexes": context.get("hookVaHexes") or [],
            "va": handler_va,
        })
    if rows:
        return rows
    for hook in selected_pointer_usage.get("runtimeTraceHookPoints") or []:
        hook_hex = hook.get("vaHex")
        hook_va = hex_to_int(hook_hex)
        if hook_va is None or hook_va in seen:
            continue
        seen.add(hook_va)
        rows.append({
            "label": f"{hook.get('mechanism') or 'hook'}:{hook_hex}",
            "handlerVaHex": hook_hex,
            "hookVaHexes": [hook_hex],
            "va": hook_va,
        })
    return rows


def selected_pointer_handler_encoded_hits(window: dict, targets: list[dict]) -> list[dict]:
    data = window.get("data")
    start_va = hex_to_int(window.get("startVaHex"))
    if not isinstance(data, (bytes, bytearray)) or start_va is None:
        return []
    route_relevant_targets = [
        target for target in targets
        if target.get("group") in {"current", "route-record", "route-selector", "branch-state"}
    ]
    rows = []
    seen: set[tuple[str, int, int]] = set()
    for offset in range(len(data)):
        site_va = start_va + offset
        values = []
        if offset + 2 <= len(data):
            u16_value = int.from_bytes(data[offset:offset + 2], "little", signed=False)
            s16_value = int.from_bytes(data[offset:offset + 2], "little", signed=True)
            values.extend([
                ("abs16-low", u16_value, None),
                ("signed-rel16-site-plus2", s16_value, site_va + 2),
            ])
        if offset + 4 <= len(data):
            s32_value = int.from_bytes(data[offset:offset + 4], "little", signed=True)
            values.append(("signed-rel32-site-plus4", s32_value, site_va + 4))
        for kind, value, rel_base in values:
            for target in route_relevant_targets:
                target_va = target.get("va")
                if not isinstance(target_va, int):
                    continue
                if kind == "abs16-low":
                    matches = value == (target_va & 0xFFFF)
                else:
                    matches = rel_base is not None and rel_base + value == target_va
                if not matches:
                    continue
                key = (kind, site_va, target_va)
                if key in seen:
                    continue
                seen.add(key)
                rows.append({
                    "siteVaHex": hex32(site_va),
                    "kind": kind,
                    "valueHex": hex32(value & 0xFFFFFFFF),
                    "targetHex": hex32(target_va),
                    "targetLabel": target.get("label"),
                    "targetGroup": target.get("group"),
                    "sourceSection": window.get("section"),
                    "promotionStatus": "blocked",
                    "promotesRouteExecution": False,
                })
    return rows


def encoded_target_summary(rows: list[dict]) -> dict:
    group_counts: dict[str, int] = {}
    label_counts: dict[str, int] = {}
    kind_counts: dict[str, int] = {}
    for row in rows:
        group = row.get("targetGroup")
        label = row.get("targetLabel")
        kind = row.get("kind")
        if group:
            group_counts[group] = group_counts.get(group, 0) + 1
        if label:
            label_counts[label] = label_counts.get(label, 0) + 1
        if kind:
            kind_counts[kind] = kind_counts.get(kind, 0) + 1
    proof_rows = [
        row for row in rows
        if row.get("targetGroup") in {"current", "route-record"}
    ]
    context_rows = [
        row for row in rows
        if row.get("targetGroup") in {"route-selector", "branch-state"}
    ]
    classification = (
        "handler-encoded-route-target-scalars-nonpromoting"
        if rows
        else "no-encoded-route-target-scalars-in-handler-graph"
    )
    return {
        "classification": classification,
        "rawScalarCandidateCount": len(rows),
        "routeProofRawScalarCandidateCount": len(proof_rows),
        "routeContextRawScalarCandidateCount": len(context_rows),
        "promotingCandidateCount": 0,
        "targetGroupCounts": dict(sorted(group_counts.items())),
        "targetLabelCounts": dict(sorted(label_counts.items())),
        "kindCounts": dict(sorted(kind_counts.items())),
        "sampleRows": rows[:24],
        "promotionStatus": "blocked",
    }


def selected_pointer_handler_call_graph_contrast(
    exe: bytes | None,
    selected_pointer_usage: dict,
    max_depth: int = SELECTED_POINTER_HANDLER_CALL_GRAPH_MAX_DEPTH,
) -> dict:
    if exe is None:
        return {
            "available": False,
            "classification": "selected-pointer-handler-callgraph-unavailable",
            "promotionStatus": "blocked",
            "proofFound": False,
            "routeProofFound": False,
            "routeContextFound": False,
            "unavailableReason": "missing-exe",
        }
    sections = read_sections(exe)
    roots = selected_pointer_handler_call_graph_roots(selected_pointer_usage)
    targets = selected_pointer_handler_target_rows(selected_pointer_usage)
    if not roots:
        return {
            "available": False,
            "classification": "selected-pointer-handler-callgraph-unavailable",
            "promotionStatus": "blocked",
            "proofFound": False,
            "routeProofFound": False,
            "routeContextFound": False,
            "unavailableReason": "missing-handler-roots",
        }
    queue = [
        {
            "label": root["label"],
            "handlerVaHex": root.get("handlerVaHex"),
            "hookVaHexes": root.get("hookVaHexes") or [],
            "va": int(root["va"]),
            "depth": 0,
            "path": [root["label"]],
        }
        for root in roots
    ]
    visited_vas: set[int] = set()
    queued_vas = {int(item["va"]) for item in queue}
    reachable_functions = []
    call_edges = []
    immediate_counts: dict[str, int] = {}
    transfer_counts: dict[str, int] = {}
    encoded_rows: list[dict] = []
    max_observed_depth = 0
    direct_call_edge_count = 0
    mapped_direct_call_edge_count = 0
    text_direct_call_edge_count = 0
    unmapped_direct_call_edge_count = 0

    while queue:
        item = queue.pop(0)
        function_va = int(item["va"])
        if function_va in visited_vas:
            continue
        visited_vas.add(function_va)
        depth = int(item["depth"])
        max_observed_depth = max(max_observed_depth, depth)
        max_bytes = (
            SELECTED_POINTER_HANDLER_MAX_BYTES
            if depth == 0
            else SELECTED_POINTER_HANDLER_CALLEE_MAX_BYTES
        )
        window = bounded_code_window(exe, sections, function_va, max_bytes=max_bytes)
        immediate_hits = dword_immediate_hits(window, targets)
        transfers = rel32_transfer_rows(window, targets, sections)
        encoded_hits = [
            {
                **hit,
                "functionVaHex": hex32(function_va),
                "functionDepth": depth,
                "functionLabel": item["label"],
            }
            for hit in selected_pointer_handler_encoded_hits(window, targets)
        ]
        transfer_hits = [transfer for transfer in transfers if transfer.get("group")]
        call_rows = [transfer for transfer in transfers if transfer.get("kind") == "call"]
        mapped_call_rows = [transfer for transfer in call_rows if transfer.get("targetSection")]
        text_call_rows = [
            transfer for transfer in mapped_call_rows
            if transfer.get("targetSection") == ".text"
        ]
        row_immediate_counts = count_rows_by_group(immediate_hits)
        row_transfer_counts = count_rows_by_group(transfer_hits)
        for group, count in row_immediate_counts.items():
            immediate_counts[group] = immediate_counts.get(group, 0) + int(count)
        for group, count in row_transfer_counts.items():
            transfer_counts[group] = transfer_counts.get(group, 0) + int(count)
        encoded_rows.extend(encoded_hits)
        direct_call_edge_count += len(call_rows)
        mapped_direct_call_edge_count += len(mapped_call_rows)
        text_direct_call_edge_count += len(text_call_rows)
        unmapped_direct_call_edge_count += len(call_rows) - len(mapped_call_rows)
        reachable_functions.append({
            "label": item["label"],
            "handlerVaHex": item.get("handlerVaHex"),
            "hookVaHexes": item.get("hookVaHexes") or [],
            "depth": depth,
            "functionVaHex": hex32(function_va),
            "windowStartVaHex": window.get("startVaHex"),
            "windowEndVaHex": window.get("endVaHex"),
            "windowByteCount": window.get("byteCount"),
            "windowTermination": window.get("termination"),
            "path": item["path"],
            "immediateHitCount": len(immediate_hits),
            "immediateHitCountsByGroup": row_immediate_counts,
            "directTransferCount": len(transfers),
            "directCallCount": len(call_rows),
            "mappedDirectCallCount": len(mapped_call_rows),
            "textDirectCallCount": len(text_call_rows),
            "directTransferTargetHitCount": len(transfer_hits),
            "directTransferTargetHitCountsByGroup": row_transfer_counts,
            "encodedTargetRawScalarCandidateCount": len(encoded_hits),
        })
        if depth >= max_depth:
            continue
        for transfer in call_rows:
            target_va = hex_to_int(transfer.get("targetVaHex"))
            edge = {
                "fromLabel": item["label"],
                "fromVaHex": hex32(function_va),
                "depth": depth + 1,
                "callVaHex": transfer.get("siteVaHex"),
                "targetVaHex": transfer.get("targetVaHex"),
                "targetSection": transfer.get("targetSection"),
                "targetLabel": transfer.get("targetLabel")
                or (f"sub_{target_va:08x}" if target_va is not None else None),
                "path": [
                    *item["path"],
                    f"{transfer.get('siteVaHex')}->{transfer.get('targetVaHex')}",
                ],
            }
            if len(call_edges) < 128:
                call_edges.append(edge)
            if (
                target_va is None
                or transfer.get("targetSection") != ".text"
                or target_va in visited_vas
                or target_va in queued_vas
            ):
                continue
            queued_vas.add(target_va)
            queue.append({
                "label": edge["targetLabel"] or f"sub_{target_va:08x}",
                "handlerVaHex": None,
                "hookVaHexes": [],
                "va": target_va,
                "depth": depth + 1,
                "path": edge["path"],
            })

    immediate_counts = dict(sorted(immediate_counts.items()))
    transfer_counts = dict(sorted(transfer_counts.items()))
    proof_groups = {"current", "route-record"}
    review_context_groups = {"route-selector", "branch-state"}
    expected_context_groups = {"selected-pointer", "selector-table"}
    route_immediate_count = sum(immediate_counts.get(group, 0) for group in proof_groups)
    route_context_immediate_count = sum(
        immediate_counts.get(group, 0) for group in review_context_groups
    )
    expected_context_immediate_count = sum(
        immediate_counts.get(group, 0) for group in expected_context_groups
    )
    route_transfer_hit_count = sum(transfer_counts.get(group, 0) for group in proof_groups)
    route_context_transfer_hit_count = sum(
        transfer_counts.get(group, 0) for group in review_context_groups
    )
    expected_context_transfer_hit_count = sum(
        transfer_counts.get(group, 0) for group in expected_context_groups
    )
    proof_found = route_immediate_count > 0 or route_transfer_hit_count > 0
    route_context_hit_count = route_context_immediate_count + route_context_transfer_hit_count
    expected_context_hit_count = expected_context_immediate_count + expected_context_transfer_hit_count
    route_context_found = route_context_hit_count > 0
    only_expected_context = (
        expected_context_hit_count > 0
        and not proof_found
        and not route_context_found
    )
    if proof_found:
        classification = "selected-pointer-handler-callgraph-route-hit-review"
        promotion_status = "review-required"
    elif route_context_found:
        classification = "selected-pointer-handler-callgraph-route-context-review"
        promotion_status = "review-required"
    elif only_expected_context:
        classification = "selected-pointer-handler-callgraph-generic-only-contrast"
        promotion_status = "blocked"
    else:
        classification = "selected-pointer-handler-callgraph-nonroute-contrast"
        promotion_status = "blocked"
    encoded_scan = encoded_target_summary(encoded_rows)
    return {
        "available": True,
        "classification": classification,
        "promotionStatus": promotion_status,
        "proofFound": proof_found,
        "routeProofFound": proof_found,
        "routeContextFound": route_context_found,
        "routeContextHitCount": route_context_hit_count,
        "expectedContextHitCount": expected_context_hit_count,
        "onlyExpectedContext": only_expected_context,
        "maxDepth": max_depth,
        "observedMaxDepth": max_observed_depth,
        "rootCount": len(roots),
        "rootRows": [
            {key: value for key, value in row.items() if key != "va"}
            for row in roots
        ],
        "targetRows": [
            {key: value for key, value in row.items() if key != "va"}
            for row in targets
        ],
        "reachableFunctionCount": len(reachable_functions),
        "directCallEdgeCount": direct_call_edge_count,
        "mappedDirectCallEdgeCount": mapped_direct_call_edge_count,
        "textDirectCallEdgeCount": text_direct_call_edge_count,
        "unmappedDirectCallEdgeCount": unmapped_direct_call_edge_count,
        "immediateHitCount": sum(immediate_counts.values()),
        "immediateHitCountsByGroup": immediate_counts,
        "routeImmediateHitCount": route_immediate_count,
        "currentImmediateHitCount": immediate_counts.get("current", 0),
        "routeRecordImmediateHitCount": immediate_counts.get("route-record", 0),
        "routeSelectorImmediateHitCount": immediate_counts.get("route-selector", 0),
        "selectedPointerImmediateHitCount": immediate_counts.get("selected-pointer", 0),
        "selectorTableImmediateHitCount": immediate_counts.get("selector-table", 0),
        "branchStateImmediateHitCount": immediate_counts.get("branch-state", 0),
        "directTransferTargetHitCount": sum(transfer_counts.values()),
        "directTransferTargetHitCountsByGroup": transfer_counts,
        "routeDirectTransferHitCount": route_transfer_hit_count,
        "currentDirectTransferHitCount": transfer_counts.get("current", 0),
        "routeRecordDirectTransferHitCount": transfer_counts.get("route-record", 0),
        "routeSelectorDirectTransferHitCount": transfer_counts.get("route-selector", 0),
        "selectedPointerDirectTransferHitCount": transfer_counts.get("selected-pointer", 0),
        "selectorTableDirectTransferHitCount": transfer_counts.get("selector-table", 0),
        "branchStateDirectTransferHitCount": transfer_counts.get("branch-state", 0),
        "encodedTargetScan": encoded_scan,
        "encodedTargetClassification": encoded_scan.get("classification"),
        "encodedTargetRawScalarCandidateCount": encoded_scan.get(
            "rawScalarCandidateCount"
        ),
        "encodedTargetRouteProofRawScalarCandidateCount": encoded_scan.get(
            "routeProofRawScalarCandidateCount"
        ),
        "encodedTargetRouteContextRawScalarCandidateCount": encoded_scan.get(
            "routeContextRawScalarCandidateCount"
        ),
        "encodedTargetPromotingCandidateCount": encoded_scan.get(
            "promotingCandidateCount"
        ),
        "encodedTargetGroupCounts": encoded_scan.get("targetGroupCounts"),
        "encodedTargetLabelCounts": encoded_scan.get("targetLabelCounts"),
        "encodedTargetKindCounts": encoded_scan.get("kindCounts"),
        "sampleReachableFunctions": reachable_functions[:32],
        "sampleCallEdges": call_edges[:64],
        "conclusion": (
            "A bounded direct-call graph rooted at the selected-pointer handlers reaches only expected "
            "generic selected-pointer/selector-table context, with no current selector root, route record, "
            "route selector, or branch-state hits."
            if only_expected_context
            else "The selected-pointer handler direct-call graph requires review before it can be treated as non-route contrast."
        ),
    }


def compact_selected_pointer_handler_call_graph_depth_row(max_depth: int, evidence: dict) -> dict:
    return {
        "maxDepth": max_depth,
        "classification": evidence.get("classification"),
        "promotionStatus": evidence.get("promotionStatus"),
        "proofFound": evidence.get("proofFound"),
        "routeContextFound": evidence.get("routeContextFound"),
        "routeContextHitCount": evidence.get("routeContextHitCount"),
        "expectedContextHitCount": evidence.get("expectedContextHitCount"),
        "onlyExpectedContext": evidence.get("onlyExpectedContext"),
        "observedMaxDepth": evidence.get("observedMaxDepth"),
        "rootCount": evidence.get("rootCount"),
        "reachableFunctionCount": evidence.get("reachableFunctionCount"),
        "directCallEdgeCount": evidence.get("directCallEdgeCount"),
        "mappedDirectCallEdgeCount": evidence.get("mappedDirectCallEdgeCount"),
        "textDirectCallEdgeCount": evidence.get("textDirectCallEdgeCount"),
        "routeImmediateHitCount": evidence.get("routeImmediateHitCount"),
        "currentImmediateHitCount": evidence.get("currentImmediateHitCount"),
        "routeRecordImmediateHitCount": evidence.get("routeRecordImmediateHitCount"),
        "routeSelectorImmediateHitCount": evidence.get("routeSelectorImmediateHitCount"),
        "selectedPointerImmediateHitCount": evidence.get("selectedPointerImmediateHitCount"),
        "selectorTableImmediateHitCount": evidence.get("selectorTableImmediateHitCount"),
        "branchStateImmediateHitCount": evidence.get("branchStateImmediateHitCount"),
        "routeDirectTransferHitCount": evidence.get("routeDirectTransferHitCount"),
        "routeSelectorDirectTransferHitCount": evidence.get("routeSelectorDirectTransferHitCount"),
        "branchStateDirectTransferHitCount": evidence.get("branchStateDirectTransferHitCount"),
        "encodedTargetClassification": evidence.get("encodedTargetClassification"),
        "encodedTargetRawScalarCandidateCount": evidence.get(
            "encodedTargetRawScalarCandidateCount"
        ),
        "encodedTargetRouteProofRawScalarCandidateCount": evidence.get(
            "encodedTargetRouteProofRawScalarCandidateCount"
        ),
        "encodedTargetRouteContextRawScalarCandidateCount": evidence.get(
            "encodedTargetRouteContextRawScalarCandidateCount"
        ),
        "encodedTargetPromotingCandidateCount": evidence.get(
            "encodedTargetPromotingCandidateCount"
        ),
    }


def selected_pointer_handler_call_graph_depth_sensitivity(
    exe: bytes | None,
    selected_pointer_usage: dict,
    depths: list[int] | None = None,
) -> dict:
    checked_depths = sorted(set(depths or SELECTED_POINTER_HANDLER_CALL_GRAPH_DEPTH_SENSITIVITY_DEPTHS))
    rows = [
        compact_selected_pointer_handler_call_graph_depth_row(
            max_depth,
            selected_pointer_handler_call_graph_contrast(
                exe,
                selected_pointer_usage,
                max_depth=max_depth,
            ),
        )
        for max_depth in checked_depths
    ]
    default_row = next(
        (row for row in rows if row.get("maxDepth") == SELECTED_POINTER_HANDLER_CALL_GRAPH_MAX_DEPTH),
        rows[-1] if rows else {},
    )
    stable_keys = [
        "reachableFunctionCount",
        "directCallEdgeCount",
        "mappedDirectCallEdgeCount",
        "textDirectCallEdgeCount",
        "routeImmediateHitCount",
        "currentImmediateHitCount",
        "routeRecordImmediateHitCount",
        "routeSelectorImmediateHitCount",
        "selectedPointerImmediateHitCount",
        "selectorTableImmediateHitCount",
        "branchStateImmediateHitCount",
        "routeDirectTransferHitCount",
        "routeSelectorDirectTransferHitCount",
        "branchStateDirectTransferHitCount",
        "encodedTargetRawScalarCandidateCount",
        "encodedTargetRouteProofRawScalarCandidateCount",
        "encodedTargetRouteContextRawScalarCandidateCount",
        "encodedTargetPromotingCandidateCount",
    ]
    baseline = tuple(default_row.get(key) for key in stable_keys)
    rows_at_or_beyond_default = [
        row for row in rows
        if isinstance(row.get("maxDepth"), int)
        and row["maxDepth"] >= SELECTED_POINTER_HANDLER_CALL_GRAPH_MAX_DEPTH
    ]
    proof_absent = all(
        row.get("proofFound") is False and row.get("routeContextFound") is False
        for row in rows
    )
    counts_stable = bool(rows_at_or_beyond_default) and all(
        tuple(row.get(key) for key in stable_keys) == baseline
        for row in rows_at_or_beyond_default
    )
    depth_text = ",".join(str(depth) for depth in checked_depths) or "-"
    return {
        "depthsChecked": checked_depths,
        "defaultDepth": SELECTED_POINTER_HANDLER_CALL_GRAPH_MAX_DEPTH,
        "maxDepthChecked": max(checked_depths) if checked_depths else None,
        "proofAbsentAcrossCheckedDepths": proof_absent,
        "countsStableAtAndBeyondDefaultDepth": counts_stable,
        "defaultDepthRow": default_row,
        "rows": rows,
        "conclusion": (
            f"Depth sensitivity over max depths {depth_text} found no selected-pointer handler "
            "current/root/route-selector/branch-state call-graph hits and no promoting encoded target scalars."
        ),
    }


def current_writer_paths_for(rows: list[dict] | None) -> dict:
    rows = rows or []
    route_rows = [
        row for row in rows
        if SOURCE in (row.get("rootFieldMaps") or []) and TARGET in (row.get("rootFieldMaps") or [])
    ]
    selected_store_vas = []
    activation_store_vas = []
    for row in route_rows:
        for step in row.get("trace") or []:
            if step.get("opcodeHex") == "0x09" and SELECTED_POINTER_GLOBAL_HEX in (step.get("meaning") or ""):
                va = step.get("vaHex")
                if va and va not in selected_store_vas:
                    selected_store_vas.append(va)
        for item in (row.get("activationContext") or {}).get("activators") or []:
            if item.get("kind") == "opcode09Mode0NextStream":
                va = item.get("vaHex")
                if va and va not in activation_store_vas:
                    activation_store_vas.append(va)
    return {
        "writerCount": len(route_rows),
        "writerVaHexes": [row.get("writerVaHex") for row in route_rows if row.get("writerVaHex")],
        "streamStartHexes": sorted({row.get("streamStartHex") for row in route_rows if row.get("streamStartHex")}),
        "rootHexes": sorted({row.get("rootHex") for row in route_rows if row.get("rootHex")}),
        "rootLabels": sorted({label for row in route_rows for label in row.get("rootLabels") or []}),
        "selectedPointerStoreVaHexes": selected_store_vas,
        "activationStoreVaHexes": activation_store_vas,
        "proofFound": route_rows[0].get("proofFound") if route_rows else False,
        "currentWriterPathProofFound": route_rows[0].get("currentWriterPathProofFound") if route_rows else False,
        "failedCurrentWriterPathGateIds": route_rows[0].get("failedCurrentWriterPathGateIds") if route_rows else [],
        "missingEvidence": route_rows[0].get("missingEvidence") if route_rows else [],
        "remainingProofs": route_rows[0].get("remainingProofs") if route_rows else [],
        "outOfRangeHelperMentioned": any(
            "out-of-range values" in (row.get("opcode10HelperRule") or "")
            or any(
                "out-of-range argument 0x20" in (context.get("meaning") or "")
                for context in (row.get("activationContext") or {}).get("contextRows") or []
            )
            for row in route_rows
        ),
        "currentInternalOnly": bool(route_rows),
        "promotionStatus": "blocked-current-internal-only" if route_rows else "missing",
    }


def hook_requirement_kind(row: dict) -> str:
    mechanism = row.get("mechanism")
    if mechanism == "save-loader-writer":
        return "requires-captured-save-selector"
    if mechanism == "opcode07-indexed-writer":
        return "requires-indexed-slot-current-root"
    if mechanism in {"opcode08-zero-check", "opcode08-activator-read"}:
        return "requires-prior-selected-pointer-current-root"
    if mechanism == "opcode09-mode0-writer":
        return "requires-current-stream-in-current-range"
    if mechanism == "opcode09-mode1-writer":
        return "requires-stream-operand-in-current-range"
    if row.get("routeRequirement"):
        return "requires-route-prerequisite"
    return "self-contained"


def selected_pointer_hook_window_context(edge_trigger_gap: dict | None) -> dict:
    context = (edge_trigger_gap or {}).get("selectedPointerImmediateContextEvidence") or {}
    route_specific_hit_count = context.get("routeSpecificWindowHitCount")
    return {
        "hookWindowScannedRefCount": context.get("immediateRefCount"),
        "hookWindowRouteSpecificHitCount": route_specific_hit_count,
        "hookWindowCurrentRootHitCount": context.get("currentSelectorRootImmediateWindowHitCount"),
        "hookWindowSourceStringHitCount": context.get("sourceMapStringImmediateWindowHitCount"),
        "hookWindowTargetStringHitCount": context.get("targetMapStringImmediateWindowHitCount"),
        "hookWindowMapLoaderRelHitCount": context.get("mapLoaderWindowRelHitCount"),
        "hookWindowScriptRunnerRelHitCount": context.get("scriptRunnerWindowRelHitCount"),
        "hookWindowSelectorTableRelHitCount": context.get("selectorTableWindowRelHitCount"),
        "hookWindowAllRouteSpecificZero": route_specific_hit_count == 0,
    }


def selected_pointer_hook_prerequisite_summary(
    selected_pointer_usage: dict,
    edge_trigger_gap: dict | None = None,
    handler_call_graph: dict | None = None,
    handler_call_graph_depth_sensitivity: dict | None = None,
) -> dict:
    hooks = [
        row
        for row in selected_pointer_usage.get("runtimeTraceHookPoints") or []
        if row.get("present") is not False
    ]
    prerequisite_rows = [row for row in hooks if row.get("routeRequirement")]
    self_proving_rows = [row for row in hooks if not row.get("routeRequirement")]
    hook_requirements = [
        {
            "vaHex": row.get("vaHex"),
            "access": row.get("access"),
            "mechanism": row.get("mechanism"),
            "routeRequirementKind": hook_requirement_kind(row),
            "routeRequirement": row.get("routeRequirement"),
        }
        for row in hooks
    ]
    requirement_kinds = []
    for row in hook_requirements:
        kind = row.get("routeRequirementKind")
        if kind and kind not in requirement_kinds:
            requirement_kinds.append(kind)
    hook_count = len(hooks)
    prerequisite_unproven_count = len(prerequisite_rows)
    hook_promoting_count = 0
    hook_window = selected_pointer_hook_window_context(edge_trigger_gap)
    handler_call_graph = handler_call_graph or {}
    handler_call_graph_depth_sensitivity = handler_call_graph_depth_sensitivity or {}
    encoded_scan = handler_call_graph.get("encodedTargetScan") or {}
    return {
        "traceHookPointCount": hook_count,
        "presentHookPointCount": hook_count,
        "writerHookCount": selected_pointer_usage.get("selectedPointerWriterHookCount"),
        "readerHookCount": selected_pointer_usage.get("selectedPointerReaderHookCount"),
        "selectedPointerGlobalTextRefCount": selected_pointer_usage.get("selectedPointerGlobalTextRefCount"),
        "hookVaHexes": [row.get("vaHex") for row in hooks if row.get("vaHex")],
        "hookMechanisms": [row.get("mechanism") for row in hooks if row.get("mechanism")],
        "routeRequirementKinds": requirement_kinds,
        "routeRequirementRows": hook_requirements,
        "routePrerequisiteUnprovenCount": prerequisite_unproven_count,
        "hookSelfProvingCount": len(self_proving_rows),
        "hookPromotingCount": hook_promoting_count,
        **hook_window,
        "hookHandlerCallGraph": handler_call_graph,
        "hookHandlerCallGraphDepthSensitivity": handler_call_graph_depth_sensitivity,
        "hookHandlerCallGraphClassification": handler_call_graph.get("classification"),
        "hookHandlerCallGraphProofFound": handler_call_graph.get("proofFound"),
        "hookHandlerCallGraphRouteContextFound": handler_call_graph.get("routeContextFound"),
        "hookHandlerCallGraphRouteContextHitCount": handler_call_graph.get("routeContextHitCount"),
        "hookHandlerCallGraphExpectedContextHitCount": handler_call_graph.get("expectedContextHitCount"),
        "hookHandlerCallGraphOnlyExpectedContext": handler_call_graph.get("onlyExpectedContext"),
        "hookHandlerCallGraphMaxDepth": handler_call_graph.get("maxDepth"),
        "hookHandlerCallGraphRootCount": handler_call_graph.get("rootCount"),
        "hookHandlerCallGraphReachableFunctionCount": handler_call_graph.get("reachableFunctionCount"),
        "hookHandlerCallGraphDirectCallEdgeCount": handler_call_graph.get("directCallEdgeCount"),
        "hookHandlerCallGraphMappedDirectCallEdgeCount": handler_call_graph.get(
            "mappedDirectCallEdgeCount"
        ),
        "hookHandlerCallGraphTextDirectCallEdgeCount": handler_call_graph.get(
            "textDirectCallEdgeCount"
        ),
        "hookHandlerCallGraphRouteImmediateHitCount": handler_call_graph.get(
            "routeImmediateHitCount"
        ),
        "hookHandlerCallGraphCurrentImmediateHitCount": handler_call_graph.get(
            "currentImmediateHitCount"
        ),
        "hookHandlerCallGraphRouteRecordImmediateHitCount": handler_call_graph.get(
            "routeRecordImmediateHitCount"
        ),
        "hookHandlerCallGraphRouteSelectorImmediateHitCount": handler_call_graph.get(
            "routeSelectorImmediateHitCount"
        ),
        "hookHandlerCallGraphSelectedPointerImmediateHitCount": handler_call_graph.get(
            "selectedPointerImmediateHitCount"
        ),
        "hookHandlerCallGraphSelectorTableImmediateHitCount": handler_call_graph.get(
            "selectorTableImmediateHitCount"
        ),
        "hookHandlerCallGraphBranchStateImmediateHitCount": handler_call_graph.get(
            "branchStateImmediateHitCount"
        ),
        "hookHandlerCallGraphRouteDirectTransferHitCount": handler_call_graph.get(
            "routeDirectTransferHitCount"
        ),
        "hookHandlerCallGraphDepthSensitivityMaxDepthChecked": (
            handler_call_graph_depth_sensitivity.get("maxDepthChecked")
        ),
        "hookHandlerCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
            handler_call_graph_depth_sensitivity.get("proofAbsentAcrossCheckedDepths")
        ),
        "hookHandlerCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth": (
            handler_call_graph_depth_sensitivity.get("countsStableAtAndBeyondDefaultDepth")
        ),
        "hookHandlerEncodedTargetScan": encoded_scan,
        "hookHandlerEncodedTargetClassification": handler_call_graph.get(
            "encodedTargetClassification"
        ),
        "hookHandlerEncodedTargetRawScalarCandidateCount": handler_call_graph.get(
            "encodedTargetRawScalarCandidateCount"
        ),
        "hookHandlerEncodedTargetRouteProofRawScalarCandidateCount": handler_call_graph.get(
            "encodedTargetRouteProofRawScalarCandidateCount"
        ),
        "hookHandlerEncodedTargetRouteContextRawScalarCandidateCount": handler_call_graph.get(
            "encodedTargetRouteContextRawScalarCandidateCount"
        ),
        "hookHandlerEncodedTargetPromotingCandidateCount": handler_call_graph.get(
            "encodedTargetPromotingCandidateCount"
        ),
        "hookHandlerEncodedTargetGroupCounts": handler_call_graph.get(
            "encodedTargetGroupCounts"
        ) or {},
        "hookHandlerEncodedTargetLabelCounts": handler_call_graph.get(
            "encodedTargetLabelCounts"
        ) or {},
        "hookHandlerEncodedTargetKindCounts": handler_call_graph.get(
            "encodedTargetKindCounts"
        ) or {},
        "hookPrerequisitesAllUnproven": hook_count > 0 and prerequisite_unproven_count == hook_count,
        "textRefsAreTraceTargetsOnly": (
            (selected_pointer_usage.get("selectedPointerGlobalTextRefCount") or 0) > 0
            and hook_promoting_count == 0
            and handler_call_graph.get("encodedTargetPromotingCandidateCount", 0) == 0
            and hook_window.get("hookWindowAllRouteSpecificZero") is True
            and handler_call_graph.get("proofFound") is not True
            and handler_call_graph.get("routeContextFound") is not True
        ),
        "gateStatus": "trace-targets-prerequisites-unproven",
        "promotionStatus": "blocked",
    }


def runtime_probe_summary(
    memory_snapshot_context: dict,
    input_probe: dict,
    key_sequence_probe: dict,
    selected_pointer_poll: dict,
    selected_pointer_prelude_poll: dict,
    selected_pointer_long_poll: dict,
    selected_pointer_late_poll: dict,
    route_watch_values_poll: dict,
    selected_pointer_savedata_load_poll: dict,
    selected_pointer_multislot_savedata_load_poll: dict,
    selected_pointer_multislot_savedata_load_case_alias_poll: dict,
    selected_pointer_multislot_savedata_load_input_path_case_alias_poll: dict,
    selected_pointer_predecessor_direction_sweep_poll: dict,
    selected_pointer_predecessor_left_overrun_activation_sweep_poll: dict,
    selected_pointer_predecessor_route_attempt_context: dict,
    selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll: dict,
    selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll: dict,
    save_file_io_strace_attach_load_candidates_probe: dict,
    save_file_io_strace_attach_load_candidates_case_alias_probe: dict,
) -> dict:
    poll_reached_current_root_values = [
        selected_pointer_poll.get("anyReachedCurrentRoot"),
        selected_pointer_prelude_poll.get("anyReachedCurrentRoot"),
        selected_pointer_long_poll.get("anyReachedCurrentRoot"),
        selected_pointer_late_poll.get("anyReachedCurrentRoot"),
        route_watch_values_poll.get("anyReachedCurrentRoot"),
        selected_pointer_savedata_load_poll.get("anyReachedCurrentRoot"),
        selected_pointer_multislot_savedata_load_poll.get("anyReachedCurrentRoot"),
        selected_pointer_multislot_savedata_load_case_alias_poll.get("anyReachedCurrentRoot"),
        selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("anyReachedCurrentRoot"),
        selected_pointer_predecessor_direction_sweep_poll.get("anyReachedCurrentRoot"),
        selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("anyReachedCurrentRoot"),
        selected_pointer_predecessor_route_attempt_context.get("anyReachedCurrentRoot"),
    ]
    poll_reached_route_selector_values = [
        selected_pointer_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_prelude_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_long_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_late_poll.get("anyReachedRouteSelectorContext"),
        route_watch_values_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_savedata_load_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_multislot_savedata_load_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_multislot_savedata_load_case_alias_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_predecessor_direction_sweep_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("anyReachedRouteSelectorContext"),
        selected_pointer_predecessor_route_attempt_context.get("anyReachedRouteSelectorContext"),
    ]
    predecessor_route_public_context = (
        selected_pointer_predecessor_route_attempt_context.get("publicPredecessorSelectorContext") or {}
    )
    return {
        "memorySnapshotStatus": memory_snapshot_context.get("snapshotStatus"),
        "memorySelectedSelector": memory_snapshot_context.get("selectedPointerContextSelector"),
        "memorySelectedPointerHex": memory_snapshot_context.get("selectedPointerStaticValueHex"),
        "memoryEqualsCurrentRoot": memory_snapshot_context.get("selectedPointerEqualsCurrentRouteRoot"),
        "inputBaselineSelector": (input_probe.get("baselineSelectedPointerContext") or {}).get("selector"),
        "inputFinalSelector": (input_probe.get("finalSelectedPointerContext") or {}).get("selector"),
        "inputHeldKeyPressedDetected": input_probe.get("heldKeyPressedDetected"),
        "inputXEventChangedSelectedPointer": input_probe.get("xEventChangedSelectedPointer"),
        "inputKeyBufferPokeChangedSelectedPointer": input_probe.get("keyBufferPokeChangedSelectedPointer"),
        "keySequenceCount": key_sequence_probe.get("sequenceCount"),
        "keySequenceReachedCurrentRoot": key_sequence_probe.get("anyReachedCurrentRoot"),
        "keySequenceReachedRouteSelector": key_sequence_probe.get("anyReachedRouteSelectorContext"),
        "pollSequenceCount": selected_pointer_poll.get("sequenceCount"),
        "pollSampleCount": selected_pointer_poll.get("sampleCount"),
        "pollObservedSelectors": selected_pointer_poll.get("observedSelectors") or [],
        "pollReachedCurrentRoot": selected_pointer_poll.get("anyReachedCurrentRoot"),
        "pollReachedRouteSelector": selected_pointer_poll.get("anyReachedRouteSelectorContext"),
        "preludePollSequenceCount": selected_pointer_prelude_poll.get("sequenceCount"),
        "preludePollSampleCount": selected_pointer_prelude_poll.get("sampleCount"),
        "preludePollObservedSelectors": selected_pointer_prelude_poll.get("observedSelectors") or [],
        "preludePollReachedCurrentRoot": selected_pointer_prelude_poll.get("anyReachedCurrentRoot"),
        "preludePollReachedRouteSelector": selected_pointer_prelude_poll.get("anyReachedRouteSelectorContext"),
        "longPollSequenceCount": selected_pointer_long_poll.get("sequenceCount"),
        "longPollSampleCount": selected_pointer_long_poll.get("sampleCount"),
        "longPollObservedSelectors": selected_pointer_long_poll.get("observedSelectors") or [],
        "longPollReachedCurrentRoot": selected_pointer_long_poll.get("anyReachedCurrentRoot"),
        "longPollReachedRouteSelector": selected_pointer_long_poll.get("anyReachedRouteSelectorContext"),
        "latePollSequenceCount": selected_pointer_late_poll.get("sequenceCount"),
        "latePollSampleCount": selected_pointer_late_poll.get("sampleCount"),
        "latePollStartupWaitSeconds": selected_pointer_late_poll.get("startupWaitSeconds"),
        "latePollObservedSelectors": selected_pointer_late_poll.get("observedSelectors") or [],
        "latePollReachedCurrentRoot": selected_pointer_late_poll.get("anyReachedCurrentRoot"),
        "latePollReachedRouteSelector": selected_pointer_late_poll.get("anyReachedRouteSelectorContext"),
        "routeWatchPollSequenceCount": route_watch_values_poll.get("sequenceCount"),
        "routeWatchPollSampleCount": route_watch_values_poll.get("sampleCount"),
        "routeWatchPollStartupWaitSeconds": route_watch_values_poll.get("startupWaitSeconds"),
        "routeWatchPollObservedSelectors": route_watch_values_poll.get("observedSelectors") or [],
        "routeWatchPollReachedCurrentRoot": route_watch_values_poll.get("anyReachedCurrentRoot"),
        "routeWatchPollReachedRouteSelector": route_watch_values_poll.get("anyReachedRouteSelectorContext"),
        "routeWatchPollValues": watch_value_summary(route_watch_values_poll),
        "savedataLoadPollSequenceCount": selected_pointer_savedata_load_poll.get("sequenceCount"),
        "savedataLoadPollSampleCount": selected_pointer_savedata_load_poll.get("sampleCount"),
        "savedataLoadPollStartupWaitSeconds": selected_pointer_savedata_load_poll.get("startupWaitSeconds"),
        "savedataLoadPollObservedSelectors": selected_pointer_savedata_load_poll.get("observedSelectors") or [],
        "savedataLoadPollReachedCurrentRoot": selected_pointer_savedata_load_poll.get("anyReachedCurrentRoot"),
        "savedataLoadPollReachedRouteSelector": selected_pointer_savedata_load_poll.get(
            "anyReachedRouteSelectorContext"
        ),
        "savedataLoadPollValues": watch_value_summary(selected_pointer_savedata_load_poll),
        "multislotSavedataLoadPollSequenceCount": selected_pointer_multislot_savedata_load_poll.get("sequenceCount"),
        "multislotSavedataLoadPollSampleCount": selected_pointer_multislot_savedata_load_poll.get("sampleCount"),
        "multislotSavedataLoadPollStartupWaitSeconds": selected_pointer_multislot_savedata_load_poll.get(
            "startupWaitSeconds"
        ),
        "multislotSavedataLoadPollObservedSelectors": (
            selected_pointer_multislot_savedata_load_poll.get("observedSelectors") or []
        ),
        "multislotSavedataLoadPollPublicSaveSelectors": (
            selected_pointer_multislot_savedata_load_poll.get("publicSaveSelectors") or []
        ),
        "multislotSavedataLoadPollObservedPublicSaveSelectors": (
            selected_pointer_multislot_savedata_load_poll.get("observedPublicSaveSelectors") or []
        ),
        "multislotSavedataLoadPollReachedPublicSaveSelector": selected_pointer_multislot_savedata_load_poll.get(
            "anyReachedPublicSaveSelector"
        ),
        "multislotSavedataLoadPollReachedCurrentRoot": selected_pointer_multislot_savedata_load_poll.get(
            "anyReachedCurrentRoot"
        ),
        "multislotSavedataLoadPollReachedRouteSelector": selected_pointer_multislot_savedata_load_poll.get(
            "anyReachedRouteSelectorContext"
        ),
        "multislotSavedataLoadPollValues": watch_value_summary(selected_pointer_multislot_savedata_load_poll),
        "caseAliasMultislotSavedataLoadPollSequenceCount": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("sequenceCount")
        ),
        "caseAliasMultislotSavedataLoadPollSampleCount": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("sampleCount")
        ),
        "caseAliasMultislotSavedataLoadPollStartupWaitSeconds": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("startupWaitSeconds")
        ),
        "caseAliasMultislotSavedataLoadPollCaseAliasesEnabled": (
            (selected_pointer_multislot_savedata_load_case_alias_poll.get("caseAliases") or {}).get("enabled")
        ),
        "caseAliasMultislotSavedataLoadPollPublicSaveSelectors": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("publicSaveSelectors") or []
        ),
        "caseAliasMultislotSavedataLoadPollObservedSelectors": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("observedSelectors") or []
        ),
        "caseAliasMultislotSavedataLoadPollObservedPublicSaveSelectors": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("observedPublicSaveSelectors") or []
        ),
        "caseAliasMultislotSavedataLoadPollReachedPublicSaveSelector": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("anyReachedPublicSaveSelector")
        ),
        "caseAliasMultislotSavedataLoadPollReachedCurrentRoot": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("anyReachedCurrentRoot")
        ),
        "caseAliasMultislotSavedataLoadPollReachedRouteSelector": (
            selected_pointer_multislot_savedata_load_case_alias_poll.get("anyReachedRouteSelectorContext")
        ),
        "caseAliasMultislotSavedataLoadPollValues": watch_value_summary(
            selected_pointer_multislot_savedata_load_case_alias_poll
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollSequenceCount": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("sequenceCount")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollSampleCount": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("sampleCount")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollStartupWaitSeconds": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("startupWaitSeconds")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollCaseAliasesEnabled": (
            (selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("caseAliases") or {}).get("enabled")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollPublicSaveSelectors": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("publicSaveSelectors") or []
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollObservedSelectors": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("observedSelectors") or []
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollObservedPublicSaveSelectors": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("observedPublicSaveSelectors") or []
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollReachedPublicSaveSelector": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("anyReachedPublicSaveSelector")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollReachedCurrentRoot": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("anyReachedCurrentRoot")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollReachedRouteSelector": (
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll.get("anyReachedRouteSelectorContext")
        ),
        "inputPathCaseAliasMultislotSavedataLoadPollValues": watch_value_summary(
            selected_pointer_multislot_savedata_load_input_path_case_alias_poll
        ),
        "predecessorDirectionSweepPollSequenceCount": selected_pointer_predecessor_direction_sweep_poll.get(
            "sequenceCount"
        ),
        "predecessorDirectionSweepPollSampleCount": selected_pointer_predecessor_direction_sweep_poll.get(
            "sampleCount"
        ),
        "predecessorDirectionSweepPollStartupWaitSeconds": selected_pointer_predecessor_direction_sweep_poll.get(
            "startupWaitSeconds"
        ),
        "predecessorDirectionSweepPollCaseAliasesEnabled": (
            (selected_pointer_predecessor_direction_sweep_poll.get("caseAliases") or {}).get("enabled")
        ),
        "predecessorDirectionSweepPollStagedSaveKind": selected_pointer_predecessor_direction_sweep_poll.get(
            "stagedSaveKind"
        ),
        "predecessorDirectionSweepPollPublicSaveSelectors": (
            selected_pointer_predecessor_direction_sweep_poll.get("publicSaveSelectors") or []
        ),
        "predecessorDirectionSweepPollObservedSelectors": (
            selected_pointer_predecessor_direction_sweep_poll.get("observedSelectors") or []
        ),
        "predecessorDirectionSweepPollObservedPublicSaveSelectors": (
            selected_pointer_predecessor_direction_sweep_poll.get("observedPublicSaveSelectors") or []
        ),
        "predecessorDirectionSweepPollReachedPublicSaveSelector": (
            selected_pointer_predecessor_direction_sweep_poll.get("anyReachedPublicSaveSelector")
        ),
        "predecessorDirectionSweepPollReachedCurrentRoot": (
            selected_pointer_predecessor_direction_sweep_poll.get("anyReachedCurrentRoot")
        ),
        "predecessorDirectionSweepPollReachedRouteSelector": (
            selected_pointer_predecessor_direction_sweep_poll.get("anyReachedRouteSelectorContext")
        ),
        "predecessorDirectionSweepPollValues": watch_value_summary(
            selected_pointer_predecessor_direction_sweep_poll
        ),
        "predecessorLeftOverrunActivationSweepPollSequenceCount": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("sequenceCount")
        ),
        "predecessorLeftOverrunActivationSweepPollSampleCount": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("sampleCount")
        ),
        "predecessorLeftOverrunActivationSweepPollStartupWaitSeconds": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("startupWaitSeconds")
        ),
        "predecessorLeftOverrunActivationSweepPollCaseAliasesEnabled": (
            (selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("caseAliases") or {}).get("enabled")
        ),
        "predecessorLeftOverrunActivationSweepPollStagedSaveKind": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("stagedSaveKind")
        ),
        "predecessorLeftOverrunActivationSweepPollPublicSaveSelectors": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("publicSaveSelectors") or []
        ),
        "predecessorLeftOverrunActivationSweepPollObservedSelectors": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("observedSelectors") or []
        ),
        "predecessorLeftOverrunActivationSweepPollObservedPublicSaveSelectors": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("observedPublicSaveSelectors") or []
        ),
        "predecessorLeftOverrunActivationSweepPollReachedPublicSaveSelector": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("anyReachedPublicSaveSelector")
        ),
        "predecessorLeftOverrunActivationSweepPollReachedCurrentRoot": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("anyReachedCurrentRoot")
        ),
        "predecessorLeftOverrunActivationSweepPollReachedRouteSelector": (
            selected_pointer_predecessor_left_overrun_activation_sweep_poll.get("anyReachedRouteSelectorContext")
        ),
        "predecessorLeftOverrunActivationSweepPollValues": watch_value_summary(
            selected_pointer_predecessor_left_overrun_activation_sweep_poll
        ),
        "predecessorRouteAttemptSummary": predecessor_route_attempt_summary(
            selected_pointer_predecessor_route_attempt_context
        ),
        "predecessorRouteAttemptPromotionStatus": (
            selected_pointer_predecessor_route_attempt_context.get("promotionStatus")
        ),
        "predecessorRouteAttemptProofFound": (
            selected_pointer_predecessor_route_attempt_context.get("proofFound")
        ),
        "predecessorRouteAttemptRuntimeProofFound": (
            selected_pointer_predecessor_route_attempt_context.get("predecessorRouteAttemptProofFound")
        ),
        "predecessorRouteAttemptSourceFileCount": (
            selected_pointer_predecessor_route_attempt_context.get("sourceFileCount")
        ),
        "predecessorRouteAttemptTotalSequenceCount": (
            selected_pointer_predecessor_route_attempt_context.get("totalSequenceCount")
        ),
        "predecessorRouteAttemptTotalSampleCount": (
            selected_pointer_predecessor_route_attempt_context.get("totalSampleCount")
        ),
        "predecessorRouteAttemptPublicObservedFileCount": (
            selected_pointer_predecessor_route_attempt_context.get("publicPredecessorObservedFileCount")
        ),
        "predecessorRouteAttemptReachedRouteSelector": (
            selected_pointer_predecessor_route_attempt_context.get("anyReachedRouteSelectorContext")
        ),
        "predecessorRouteAttemptReachedCurrentRoot": (
            selected_pointer_predecessor_route_attempt_context.get("anyReachedCurrentRoot")
        ),
        "predecessorRouteAttemptRouteSelectorHitCount": (
            selected_pointer_predecessor_route_attempt_context.get("routeSelectorHitCount")
        ),
        "predecessorRouteAttemptCurrentRootHitCount": (
            selected_pointer_predecessor_route_attempt_context.get("currentRootHitCount")
        ),
        "predecessorRouteAttemptObservedSelectorCounts": (
            selected_pointer_predecessor_route_attempt_context.get("observedSelectorCounts") or {}
        ),
        "predecessorRouteAttemptDominantDiversionSelector": (
            selected_pointer_predecessor_route_attempt_context.get("dominantDiversionSelector")
        ),
        "predecessorRouteAttemptDiversionSelectorContextCount": (
            selected_pointer_predecessor_route_attempt_context.get("diversionSelectorContextCount")
        ),
        "predecessorRouteAttemptFieldMapDiversionSelectorCount": (
            selected_pointer_predecessor_route_attempt_context.get("fieldMapDiversionSelectorCount")
        ),
        "predecessorRouteAttemptResourceOnlyDiversionSelectorCount": (
            selected_pointer_predecessor_route_attempt_context.get("resourceOnlyDiversionSelectorCount")
        ),
        "predecessorRouteAttemptDiversionRoutePromotionEvidenceFound": (
            selected_pointer_predecessor_route_attempt_context.get("diversionRoutePromotionEvidenceFound")
        ),
        "predecessorRouteAttemptPublicSelectorContextClassification": (
            predecessor_route_public_context.get("classification")
        ),
        "predecessorRouteAttemptPublicSelectorCurrentProofCount": (
            predecessor_route_public_context.get("selectedPointerPathSelectsOrStoresCurrentCount")
        ),
        "syntheticSelector20InputPathCaseAliasPollSequenceCount": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("sequenceCount")
        ),
        "syntheticSelector20InputPathCaseAliasPollSampleCount": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("sampleCount")
        ),
        "syntheticSelector20InputPathCaseAliasPollStartupWaitSeconds": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("startupWaitSeconds")
        ),
        "syntheticSelector20InputPathCaseAliasPollCaseAliasesEnabled": (
            (selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("caseAliases") or {}).get(
                "enabled"
            )
        ),
        "syntheticSelector20InputPathCaseAliasPollStagedSelectors": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("publicSaveSelectors") or []
        ),
        "syntheticSelector20InputPathCaseAliasPollObservedSelectors": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("observedSelectors") or []
        ),
        "syntheticSelector20InputPathCaseAliasPollObservedStagedSelectors": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("observedPublicSaveSelectors")
            or []
        ),
        "syntheticSelector20InputPathCaseAliasPollReachedStagedSelector": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("anyReachedPublicSaveSelector")
        ),
        "syntheticSelector20InputPathCaseAliasPollReachedCurrentRoot": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get("anyReachedCurrentRoot")
        ),
        "syntheticSelector20InputPathCaseAliasPollReachedRouteSelector": (
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.get(
                "anyReachedRouteSelectorContext"
            )
        ),
        "syntheticSelector20InputPathCaseAliasPollValues": watch_value_summary(
            selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll
        ),
        "patchedPublicSelector20InputPathCaseAliasPollSequenceCount": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("sequenceCount")
        ),
        "patchedPublicSelector20InputPathCaseAliasPollSampleCount": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("sampleCount")
        ),
        "patchedPublicSelector20InputPathCaseAliasPollStartupWaitSeconds": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("startupWaitSeconds")
        ),
        "patchedPublicSelector20InputPathCaseAliasPollCaseAliasesEnabled": (
            (selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("caseAliases") or {}).get(
                "enabled"
            )
        ),
        "patchedPublicSelector20InputPathCaseAliasPollStagedSaveKind": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("stagedSaveKind")
        ),
        "patchedPublicSelector20InputPathCaseAliasPollStagedSelectors": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("publicSaveSelectors") or []
        ),
        "patchedPublicSelector20InputPathCaseAliasPollObservedSelectors": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("observedSelectors") or []
        ),
        "patchedPublicSelector20InputPathCaseAliasPollObservedStagedSelectors": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get(
                "observedPublicSaveSelectors"
            )
            or []
        ),
        "patchedPublicSelector20InputPathCaseAliasPollReachedStagedSelector": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get(
                "anyReachedPublicSaveSelector"
            )
        ),
        "patchedPublicSelector20InputPathCaseAliasPollReachedCurrentRoot": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get("anyReachedCurrentRoot")
        ),
        "patchedPublicSelector20InputPathCaseAliasPollReachedRouteSelector": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get(
                "anyReachedRouteSelectorContext"
            )
        ),
        "patchedPublicSelector20InputPathCaseAliasPollValues": watch_value_summary(
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll
        ),
        "constructedDiagnosticPollReachedRouteSelector": (
            selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.get(
                "anyReachedRouteSelectorContext"
            )
            is True
        ),
        "fileIoAttachLoadBackend": save_file_io_strace_attach_load_candidates_probe.get("backend"),
        "fileIoAttachLoadSequenceCount": save_file_io_strace_attach_load_candidates_probe.get("sequenceCount"),
        "fileIoAttachLoadSequenceWithPidCount": save_file_io_strace_attach_load_candidates_probe.get(
            "sequenceWithPidCount"
        ),
        "fileIoAttachLoadSequenceWithKeyWritesCount": save_file_io_strace_attach_load_candidates_probe.get(
            "sequenceWithKeyWritesCount"
        ),
        "fileIoAttachLoadInputTraceUsable": save_file_io_strace_attach_load_candidates_probe.get("inputTraceUsable"),
        "fileIoAttachLoadMatchedLineCount": save_file_io_strace_attach_load_candidates_probe.get("matchedLineCount"),
        "fileIoAttachLoadAnySavedat1Access": save_file_io_strace_attach_load_candidates_probe.get(
            "anySavedat1DatAccess"
        ),
        "fileIoAttachCaseAliasLoadBackend": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("backend")
        ),
        "fileIoAttachCaseAliasLoadSequenceCount": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("sequenceCount")
        ),
        "fileIoAttachCaseAliasLoadSequenceWithPidCount": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("sequenceWithPidCount")
        ),
        "fileIoAttachCaseAliasLoadSequenceWithKeyWritesCount": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("sequenceWithKeyWritesCount")
        ),
        "fileIoAttachCaseAliasLoadInputTraceUsable": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("inputTraceUsable")
        ),
        "fileIoAttachCaseAliasLoadMatchedLineCount": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("matchedLineCount")
        ),
        "fileIoAttachCaseAliasLoadAnySavedat1Access": (
            save_file_io_strace_attach_load_candidates_case_alias_probe.get("anySavedat1DatAccess")
        ),
        "fileIoAttachCaseAliasLoadCaseAliasesEnabled": (
            (save_file_io_strace_attach_load_candidates_case_alias_probe.get("caseAliases") or {}).get("enabled")
        ),
        "anyRuntimePollReachedCurrentRoot": any(value is True for value in poll_reached_current_root_values),
        "anyRuntimePollReachedRouteSelector": any(value is True for value in poll_reached_route_selector_values),
        "promotionStatus": "blocked",
    }


def diagnostic_exclusion_summary(runtime_patched_selector_followup_context: dict | None) -> dict:
    context = runtime_patched_selector_followup_context or {}
    if not context:
        return {"available": False}
    runtime = context.get("runtimePoll") or {}
    active_order = context.get("activeOrderRuntimeEvidence") or {}
    branch_state = context.get("branchStateRuntimeEvidence") or {}
    exit_candidates = context.get("exitCandidateRuntimeEvidence") or {}
    left_stability = context.get("leftStabilityRuntimeEvidence") or {}
    left_stability_recheck = left_stability.get("recheck") or {}
    left_active_order_recheck = left_stability.get("activeOrderRecheck") or {}
    followup_alias = context.get("followupAlias") or {}
    bridge = context.get("bridgeEvidence") or {}
    global_paths = context.get("globalSelectedPointerPathEvidence") or {}
    exact_contexts = context.get("exactFollowupPointerContexts") or []
    exact_pointer_hexes = [
        row.get("pointerVaHex")
        for row in exact_contexts
        if row.get("pointerVaHex")
    ]
    exact_trace_stop_reasons = sorted({
        row.get("traceStopReason")
        for row in exact_contexts
        if row.get("traceStopReason")
    })
    return {
        "available": True,
        "notRoutePromotionProof": context.get("notRoutePromotionProof"),
        "promotionStatus": context.get("promotionStatus"),
        "currentSelector": context.get("currentSelector"),
        "followupSelector": context.get("followupSelector"),
        "currentRootHex": context.get("currentRootHex"),
        "followupRootHex": context.get("followupRootHex"),
        "runtimePollSampleCount": runtime.get("sampleCount"),
        "runtimePollObservedSelectors": runtime.get("observedSelectors") or [],
        "runtimeSelectorSampleCounts": runtime.get("runtimeSelectorSampleCounts") or {},
        "runtimeTransitionTimelineAvailable": context.get("runtimeTransitionTimelineAvailable"),
        "observedCurrentThenFollowupInDiagnosticPoll": context.get("observedCurrentThenFollowupInDiagnosticPoll"),
        "coObservedCurrentAndFollowupInDiagnosticPoll": context.get("coObservedCurrentAndFollowupInDiagnosticPoll"),
        "activeOrderSourcePoll": active_order.get("sourcePoll"),
        "activeOrderSampleCount": active_order.get("sampleCount"),
        "activeOrderCountHex": active_order.get("activeOrderCountHex"),
        "activeOrderHexes": active_order.get("activeOrderHexes") or [],
        "activeSlotFirstDwordsStaticHex": active_order.get("activeSlotFirstDwordsStaticHex") or [],
        "runtimeSlotBaseTableStaticHexes": active_order.get("runtimeSlotBaseTableStaticHexes") or [],
        "runtimeObjectTableStaticHexes": active_order.get("runtimeObjectTableStaticHexes") or [],
        "branchStateSourcePoll": branch_state.get("sourcePoll"),
        "branchStateTotalSampleCount": branch_state.get("totalSampleCount"),
        "branchStateRouteSampleCount": branch_state.get("sampleCount"),
        "branchStateObservedSelectors": branch_state.get("observedSelectors") or [],
        "branchStateObservedStagedSelectors": branch_state.get("observedStagedSelectors") or [],
        "branchStateReachedCurrentRoot": branch_state.get("reachedCurrentRoot"),
        "branchStateReachedRouteSelector": branch_state.get("reachedRouteSelector"),
        "branchStateActiveSelectionFlagHex": branch_state.get("activeSelectionFlagHex"),
        "branchStateRouteActiveSelectionFlagHex": branch_state.get("routeActiveSelectionFlagHex"),
        "branchStateSecondaryHexes": branch_state.get("secondaryBranchStateHexes") or [],
        "branchStateRouteSecondaryHexes": branch_state.get("routeSecondaryBranchStateHexes") or [],
        "branchStateSecondaryAllZero": branch_state.get("secondaryBranchStateAllZero"),
        "branchStateRouteSecondaryAllZero": branch_state.get("routeSecondaryBranchStateAllZero"),
        "branchStateMatchesPredecessorFillHypothesis": branch_state.get("matchesPredecessorFillHypothesis"),
        "branchStatePromotionStatus": branch_state.get("promotionStatus"),
        "exitCandidateSourcePoll": exit_candidates.get("sourcePoll"),
        "exitCandidateCount": exit_candidates.get("candidateCount"),
        "exitCandidateRouteSelectorSides": exit_candidates.get("routeSelectorSides") or [],
        "exitCandidateBranchStateNonzeroSides": exit_candidates.get("branchStateNonzeroSides") or [],
        "exitCandidatePromotionStatus": exit_candidates.get("promotionStatus"),
        "leftStabilitySourcePoll": left_stability.get("sourcePoll"),
        "leftStabilitySampleCount": left_stability.get("sampleCount"),
        "leftStabilityRouteSequenceNames": left_stability.get("routeSequenceNames") or [],
        "leftStabilityNonRouteSequenceNames": left_stability.get("nonRouteSequenceNames") or [],
        "leftStabilityObservedSelectors": left_stability.get("observedSelectors") or [],
        "leftStabilityRouteSelectorHitCount": left_stability.get("routeSelectorHitCount"),
        "leftStabilityOpcode24AllZero": left_stability.get("opcode24AllZero"),
        "leftStabilityRouteHitReproducibility": left_stability.get("routeHitReproducibility"),
        "leftStabilityRecheckSourcePoll": left_stability_recheck.get("sourcePoll"),
        "leftStabilityRecheckSampleCount": left_stability_recheck.get("sampleCount"),
        "leftStabilityRecheckObservedSelectors": left_stability_recheck.get("observedSelectors") or [],
        "leftStabilityRecheckRouteSelectorHitCount": left_stability_recheck.get("routeSelectorHitCount"),
        "leftActiveOrderRecheckSourcePoll": left_active_order_recheck.get("sourcePoll"),
        "leftActiveOrderRecheckSampleCount": left_active_order_recheck.get("sampleCount"),
        "leftActiveOrderRecheckObservedSelectors": left_active_order_recheck.get("observedSelectors") or [],
        "leftActiveOrderRecheckRouteSelectorHitCount": left_active_order_recheck.get("routeSelectorHitCount"),
        "leftActiveOrderRecheckActiveOrderCountValues": left_active_order_recheck.get("activeOrderCountValues"),
        "leftActiveOrderRecheckSlot0DescriptorValues": left_active_order_recheck.get("activeSlot0DescriptorValues"),
        "leftStabilityPromotionStatus": left_stability.get("promotionStatus"),
        "followupAliasRole": followup_alias.get("role"),
        "followupAliasContainsSource": followup_alias.get("containsSource"),
        "followupAliasContainsTarget": followup_alias.get("containsTarget"),
        "followupAliasHasPublicSample": followup_alias.get("hasPublicSample"),
        "followupAliasPublicSampleIds": followup_alias.get("publicSampleIds") or [],
        "followupAliasFieldMaps": followup_alias.get("fieldMaps") or [],
        "aliasToCurrentExecutionLikeBridgeFound": bridge.get("aliasToCurrentExecutionLikeBridgeFound"),
        "aliasToCurrentAfterLastFillExecutionLikeBridgeFound": bridge.get(
            "aliasToCurrentAfterLastFillExecutionLikeBridgeFound"
        ),
        "globalPromotingCandidateCount": global_paths.get("promotingCandidateCount"),
        "exactFollowupPointerHexes": exact_pointer_hexes,
        "exactTraceStopReasons": exact_trace_stop_reasons,
        "exactTraceContainsSelectedPointerGlobal": any(
            row.get("traceContainsSelectedPointerGlobal") is True for row in exact_contexts
        ),
        "exactTraceContainsCurrentRootExactRef": any(
            row.get("traceContainsCurrentRootExactRef") is True for row in exact_contexts
        ),
        "exactTraceContainsSourceMapString": any(
            row.get("traceContainsSourceMapString") is True for row in exact_contexts
        ),
        "exactTraceContainsTargetMapString": any(
            row.get("traceContainsTargetMapString") is True for row in exact_contexts
        ),
        "excludedFromSelectedRootExecutionProof": True,
    }


def selected_root_execution_rejection_summary(
    selected_root_execution_ref_found: bool,
    save_gate: dict,
    static_ref_gate: dict,
    hook_prerequisite_gate: dict,
    dispatch_gate: dict,
    opcode_gate: dict,
    current_writers: dict,
    runtime: dict,
    diagnostic_exclusion: dict,
) -> dict:
    non_current_root_counts = [
        opcode_gate.get("nonCurrentOpcode07CurrentRootSelectCount"),
        opcode_gate.get("nonCurrentOpcode09CurrentRootStoreCount"),
        opcode_gate.get("nonCurrentOpcode08NearestCurrentRootProducerCount"),
    ]
    non_current_range_counts = [
        opcode_gate.get("nonCurrentOpcode07CurrentRangeSelectCount"),
        opcode_gate.get("nonCurrentOpcode09CurrentRangeStoreCount"),
        opcode_gate.get("nonCurrentOpcode08NearestCurrentRangeProducerCount"),
    ]
    no_real_selected_root = (
        save_gate.get("currentSelectorRealSaveCount") == 0
        and save_gate.get("selectedPointerRealSaveCount") == 0
        and save_gate.get("routePairRealSaveCount") == 0
        and save_gate.get("routePromotionRealSaveCount") == 0
        and save_gate.get("syntheticDiagnosticExcluded") is True
    )
    no_static_execution_ref = (
        static_ref_gate.get("currentCodeRefCount") == 0
        and static_ref_gate.get("currentSelectorRootTextRefCount") == 0
        and static_ref_gate.get("currentSecondLevelTableTextRefCount") == 0
        and static_ref_gate.get("currentFrontierReaderRefCount") == 0
    )
    hooks_are_unproven_trace_targets = (
        hook_prerequisite_gate.get("traceHookPointCount") == hook_prerequisite_gate.get(
            "routePrerequisiteUnprovenCount"
        )
        and hook_prerequisite_gate.get("hookSelfProvingCount") == 0
        and hook_prerequisite_gate.get("hookPromotingCount") == 0
        and hook_prerequisite_gate.get("hookWindowRouteSpecificHitCount") == 0
        and hook_prerequisite_gate.get("hookWindowAllRouteSpecificZero") is True
        and hook_prerequisite_gate.get("hookHandlerCallGraphProofFound") is not True
        and hook_prerequisite_gate.get("hookHandlerCallGraphRouteContextFound") is not True
        and hook_prerequisite_gate.get("hookHandlerEncodedTargetPromotingCandidateCount") == 0
    )
    dispatch_is_static_slice_only = (
        dispatch_gate.get("selectedRootExecutionDispatchRefFound") is False
        and dispatch_gate.get("saveSelectorSliceDirectRuntimeDispatchProofFound") is False
        and dispatch_gate.get("saveSelectorDirectDwordRefCount") == 0
        and dispatch_gate.get("saveSelectorIndexedDispatchCount") == 0
    )
    no_non_current_opcode_producer = (
        all(value == 0 for value in non_current_root_counts)
        and all(value == 0 for value in non_current_range_counts)
        and opcode_gate.get("selectedRootExecutionRefFound") is False
        and opcode_gate.get("promotingSelectedPointerPathCount") == 0
    )
    runtime_has_no_real_route_hit = runtime.get("anyRuntimePollReachedRouteSelector") is False
    constructed_diagnostic_excluded = (
        runtime.get("constructedDiagnosticPollReachedRouteSelector") is True
        and diagnostic_exclusion.get("excludedFromSelectedRootExecutionProof") is True
        and diagnostic_exclusion.get("notRoutePromotionProof") is True
    )
    current_writers_are_internal_only = current_writers.get("currentInternalOnly") is True
    classification = None
    if (
        not selected_root_execution_ref_found
        and no_real_selected_root
        and no_static_execution_ref
        and hooks_are_unproven_trace_targets
        and dispatch_is_static_slice_only
        and no_non_current_opcode_producer
        and current_writers_are_internal_only
        and runtime_has_no_real_route_hit
        and constructed_diagnostic_excluded
    ):
        classification = "selected-root-no-real-selector-no-execution-ref-diagnostic-excluded"
    return {
        "classification": classification,
        "proofFound": selected_root_execution_ref_found,
        "noRealSelectedRoot": no_real_selected_root,
        "noStaticExecutionRef": no_static_execution_ref,
        "hooksAreUnprovenTraceTargets": hooks_are_unproven_trace_targets,
        "dispatchIsStaticSliceOnly": dispatch_is_static_slice_only,
        "noNonCurrentOpcodeProducer": no_non_current_opcode_producer,
        "currentWritersAreInternalOnly": current_writers_are_internal_only,
        "runtimeHasNoRealRouteHit": runtime_has_no_real_route_hit,
        "constructedDiagnosticExcluded": constructed_diagnostic_excluded,
        "realSaveCounts": {
            "validRealCandidateCount": save_gate.get("validRealCandidateCount"),
            "currentSelectorRealSaveCount": save_gate.get("currentSelectorRealSaveCount"),
            "selectedPointerRealSaveCount": save_gate.get("selectedPointerRealSaveCount"),
            "routePairRealSaveCount": save_gate.get("routePairRealSaveCount"),
            "routePromotionRealSaveCount": save_gate.get("routePromotionRealSaveCount"),
            "syntheticDiagnosticExcluded": save_gate.get("syntheticDiagnosticExcluded"),
        },
        "staticRefCounts": {
            "currentCodeRefCount": static_ref_gate.get("currentCodeRefCount"),
            "currentSelectorRootTextRefCount": static_ref_gate.get("currentSelectorRootTextRefCount"),
            "currentSecondLevelTableTextRefCount": static_ref_gate.get(
                "currentSecondLevelTableTextRefCount"
            ),
            "currentFrontierReaderRefCount": static_ref_gate.get("currentFrontierReaderRefCount"),
        },
        "hookCounts": {
            "traceHookPointCount": hook_prerequisite_gate.get("traceHookPointCount"),
            "routePrerequisiteUnprovenCount": hook_prerequisite_gate.get(
                "routePrerequisiteUnprovenCount"
            ),
            "hookSelfProvingCount": hook_prerequisite_gate.get("hookSelfProvingCount"),
            "hookPromotingCount": hook_prerequisite_gate.get("hookPromotingCount"),
            "hookWindowScannedRefCount": hook_prerequisite_gate.get("hookWindowScannedRefCount"),
            "hookWindowRouteSpecificHitCount": hook_prerequisite_gate.get(
                "hookWindowRouteSpecificHitCount"
            ),
            "hookWindowAllRouteSpecificZero": hook_prerequisite_gate.get(
                "hookWindowAllRouteSpecificZero"
            ),
            "hookHandlerCallGraphClassification": hook_prerequisite_gate.get(
                "hookHandlerCallGraphClassification"
            ),
            "hookHandlerCallGraphProofFound": hook_prerequisite_gate.get(
                "hookHandlerCallGraphProofFound"
            ),
            "hookHandlerCallGraphRouteContextFound": hook_prerequisite_gate.get(
                "hookHandlerCallGraphRouteContextFound"
            ),
            "hookHandlerCallGraphExpectedContextHitCount": hook_prerequisite_gate.get(
                "hookHandlerCallGraphExpectedContextHitCount"
            ),
            "hookHandlerCallGraphReachableFunctionCount": hook_prerequisite_gate.get(
                "hookHandlerCallGraphReachableFunctionCount"
            ),
            "hookHandlerCallGraphDirectCallEdgeCount": hook_prerequisite_gate.get(
                "hookHandlerCallGraphDirectCallEdgeCount"
            ),
            "hookHandlerCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
                hook_prerequisite_gate.get(
                    "hookHandlerCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths"
                )
            ),
            "hookHandlerEncodedTargetClassification": hook_prerequisite_gate.get(
                "hookHandlerEncodedTargetClassification"
            ),
            "hookHandlerEncodedTargetRawScalarCandidateCount": hook_prerequisite_gate.get(
                "hookHandlerEncodedTargetRawScalarCandidateCount"
            ),
            "hookHandlerEncodedTargetRouteProofRawScalarCandidateCount": (
                hook_prerequisite_gate.get(
                    "hookHandlerEncodedTargetRouteProofRawScalarCandidateCount"
                )
            ),
            "hookHandlerEncodedTargetRouteContextRawScalarCandidateCount": (
                hook_prerequisite_gate.get(
                    "hookHandlerEncodedTargetRouteContextRawScalarCandidateCount"
                )
            ),
            "hookHandlerEncodedTargetPromotingCandidateCount": hook_prerequisite_gate.get(
                "hookHandlerEncodedTargetPromotingCandidateCount"
            ),
        },
        "dispatchCounts": {
            "saveSelectorHandlerTableHex": dispatch_gate.get("saveSelectorHandlerTableHex"),
            "saveSelectorSliceOffsetHex": dispatch_gate.get("saveSelectorSliceOffsetHex"),
            "saveSelectorDirectDwordRefCount": dispatch_gate.get("saveSelectorDirectDwordRefCount"),
            "saveSelectorIndexedDispatchCount": dispatch_gate.get("saveSelectorIndexedDispatchCount"),
            "dynamicIndexedDispatchRowCount": dispatch_gate.get("dynamicIndexedDispatchRowCount"),
            "dynamicScopeTableCallbackCount": dispatch_gate.get(
                "dynamicScopeTableCallbackCount"
            ),
            "dynamicSaveSelectorTableImmediateNearCount": dispatch_gate.get(
                "dynamicSaveSelectorTableImmediateNearCount"
            ),
            "saveSelectorTableBaseArithmeticRowCount": dispatch_gate.get(
                "saveSelectorTableBaseArithmeticRowCount"
            ),
            "saveSelectorTableBaseArithmeticCandidateCount": dispatch_gate.get(
                "saveSelectorTableBaseArithmeticCandidateCount"
            ),
            "saveSelectorTableBaseArithmeticCandidateFound": dispatch_gate.get(
                "saveSelectorTableBaseArithmeticCandidateFound"
            ),
            "routeRelevantSliceRequiresTableBaseSwitchCount": dispatch_gate.get(
                "routeRelevantSliceRequiresTableBaseSwitchCount"
            ),
            "routeRelevantSliceDataDescriptorGenericByteReachableCount": dispatch_gate.get(
                "routeRelevantSliceDataDescriptorGenericByteReachableCount"
            ),
            "saveSelectorSliceDirectRuntimeDispatchProofFound": dispatch_gate.get(
                "saveSelectorSliceDirectRuntimeDispatchProofFound"
            ),
            "selectedRootExecutionDispatchRefFound": dispatch_gate.get(
                "selectedRootExecutionDispatchRefFound"
            ),
        },
        "opcodeCounts": {
            "nonCurrentRootProducerCounts": non_current_root_counts,
            "nonCurrentRangeProducerCounts": non_current_range_counts,
            "currentInternalOpcode09CurrentRangeStoreCount": opcode_gate.get(
                "currentInternalOpcode09CurrentRangeStoreCount"
            ),
            "currentInternalOpcode08NearestCurrentRangeProducerCount": opcode_gate.get(
                "currentInternalOpcode08NearestCurrentRangeProducerCount"
            ),
            "promotingSelectedPointerPathCount": opcode_gate.get("promotingSelectedPointerPathCount"),
        },
        "runtimeCounts": {
            "pollSampleCount": runtime.get("pollSampleCount"),
            "pollObservedSelectors": runtime.get("pollObservedSelectors") or [],
            "preludePollSampleCount": runtime.get("preludePollSampleCount"),
            "preludePollObservedSelectors": runtime.get("preludePollObservedSelectors") or [],
            "longPollSampleCount": runtime.get("longPollSampleCount"),
            "longPollObservedSelectors": runtime.get("longPollObservedSelectors") or [],
            "latePollSampleCount": runtime.get("latePollSampleCount"),
            "latePollObservedSelectors": runtime.get("latePollObservedSelectors") or [],
            "anyRuntimePollReachedRouteSelector": runtime.get("anyRuntimePollReachedRouteSelector"),
            "constructedDiagnosticPollReachedRouteSelector": runtime.get(
                "constructedDiagnosticPollReachedRouteSelector"
            ),
        },
        "diagnosticCounts": {
            "excludedFromSelectedRootExecutionProof": diagnostic_exclusion.get(
                "excludedFromSelectedRootExecutionProof"
            ),
            "notRoutePromotionProof": diagnostic_exclusion.get("notRoutePromotionProof"),
            "runtimePollObservedSelectors": diagnostic_exclusion.get("runtimePollObservedSelectors") or [],
            "followupSelector": diagnostic_exclusion.get("followupSelector"),
            "followupAliasContainsSource": diagnostic_exclusion.get("followupAliasContainsSource"),
            "followupAliasContainsTarget": diagnostic_exclusion.get("followupAliasContainsTarget"),
            "aliasToCurrentExecutionLikeBridgeFound": diagnostic_exclusion.get(
                "aliasToCurrentExecutionLikeBridgeFound"
            ),
            "exactTraceStopReasons": diagnostic_exclusion.get("exactTraceStopReasons") or [],
        },
    }


def build_summary(
    selected_pointer_usage: dict,
    global_selected_pointer_paths: dict,
    selected_pointer_opcode_paths: dict,
    current_writer_paths: list[dict],
    dispatch_table_context: dict,
    real_savedata_gap: dict,
    runtime_memory_snapshot_context: dict,
    runtime_input_path_probe: dict,
    runtime_key_sequence_probe: dict,
    runtime_selected_pointer_poll: dict,
    runtime_selected_pointer_prelude_poll: dict,
    runtime_selected_pointer_long_poll: dict,
    runtime_selected_pointer_late_poll: dict,
    runtime_route_watch_values_poll: dict,
    runtime_selected_pointer_savedata_load_poll: dict,
    runtime_selected_pointer_multislot_savedata_load_poll: dict,
    runtime_selected_pointer_multislot_savedata_load_case_alias_poll: dict,
    runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll: dict,
    runtime_selected_pointer_predecessor_direction_sweep_poll: dict,
    runtime_selected_pointer_predecessor_left_overrun_activation_sweep_poll: dict,
    runtime_predecessor_route_attempt_context: dict,
    runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll: dict,
    runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll: dict,
    runtime_save_file_io_strace_attach_load_candidates_probe: dict,
    runtime_save_file_io_strace_attach_load_candidates_case_alias_probe: dict,
    edge_trigger_gap: dict | None = None,
    runtime_patched_selector_followup_context: dict | None = None,
    exe: bytes | None = None,
) -> dict:
    current_root = watch_value(selected_pointer_usage, "current-selector-root-2:0")
    current_second_level = watch_value(selected_pointer_usage, "current-second-level-table-2:0")
    current_frontier_reader = watch_value(selected_pointer_usage, "current-frontier-reader-2:0")
    source_record = watch_value(selected_pointer_usage, "current-source-record-map1_01a")
    target_record = watch_value(selected_pointer_usage, "current-target-record-map2_02d")
    current_writers = current_writer_paths_for(current_writer_paths)
    runtime = runtime_probe_summary(
        runtime_memory_snapshot_context,
        runtime_input_path_probe,
        runtime_key_sequence_probe,
        runtime_selected_pointer_poll,
        runtime_selected_pointer_prelude_poll,
        runtime_selected_pointer_long_poll,
        runtime_selected_pointer_late_poll,
        runtime_route_watch_values_poll,
        runtime_selected_pointer_savedata_load_poll,
        runtime_selected_pointer_multislot_savedata_load_poll,
        runtime_selected_pointer_multislot_savedata_load_case_alias_poll,
        runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll,
        runtime_selected_pointer_predecessor_direction_sweep_poll,
        runtime_selected_pointer_predecessor_left_overrun_activation_sweep_poll,
        runtime_predecessor_route_attempt_context,
        runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll,
        runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll,
        runtime_save_file_io_strace_attach_load_candidates_probe,
        runtime_save_file_io_strace_attach_load_candidates_case_alias_probe,
    )
    diagnostic_exclusion = diagnostic_exclusion_summary(runtime_patched_selector_followup_context)
    handler_call_graph = selected_pointer_handler_call_graph_contrast(exe, selected_pointer_usage)
    handler_call_graph_depth_sensitivity = selected_pointer_handler_call_graph_depth_sensitivity(
        exe,
        selected_pointer_usage,
    )
    dispatch_gate = {
        "generalHandlerTableHex": dispatch_table_context.get("generalHandlerTableHex"),
        "saveSelectorHandlerTableHex": dispatch_table_context.get("saveSelectorHandlerTableHex"),
        "saveSelectorSliceOffsetEntries": dispatch_table_context.get("saveSelectorSliceOffsetEntries"),
        "saveSelectorSliceOffsetHex": dispatch_table_context.get("saveSelectorSliceOffsetHex"),
        "saveSelectorSliceOffsetBytesHex": dispatch_table_context.get("saveSelectorSliceOffsetBytesHex"),
        "generalIndexedDispatchCount": (dispatch_table_context.get("generalTable") or {}).get("indexedDispatchCount"),
        "saveSelectorDirectDwordRefCount": (dispatch_table_context.get("saveSelectorTable") or {}).get("directDwordRefCount"),
        "saveSelectorIndexedDispatchCount": (dispatch_table_context.get("saveSelectorTable") or {}).get("indexedDispatchCount"),
        "dynamicIndexedDispatchRowCount": dispatch_table_context.get(
            "dynamicIndexedDispatchRowCount"
        ),
        "dynamicDwordScaledDispatchRowCount": dispatch_table_context.get(
            "dynamicDwordScaledDispatchRowCount"
        ),
        "dynamicScopeTableCallbackCount": dispatch_table_context.get(
            "dynamicScopeTableCallbackCount"
        ),
        "dynamicSaveSelectorTableImmediateNearCount": dispatch_table_context.get(
            "dynamicSaveSelectorTableImmediateNearCount"
        ),
        "dynamicSaveSelectorTableBaseSwitchStaticCandidateFound": dispatch_table_context.get(
            "dynamicSaveSelectorTableBaseSwitchStaticCandidateFound"
        ),
        "saveSelectorTableBaseArithmeticScanWindowBytes": dispatch_table_context.get(
            "saveSelectorTableBaseArithmeticScanWindowBytes"
        ),
        "saveSelectorTableBaseArithmeticRowCount": dispatch_table_context.get(
            "saveSelectorTableBaseArithmeticRowCount"
        ),
        "saveSelectorTableBaseArithmeticCandidateCount": dispatch_table_context.get(
            "saveSelectorTableBaseArithmeticCandidateCount"
        ),
        "saveSelectorTableBaseArithmeticCandidateFound": dispatch_table_context.get(
            "saveSelectorTableBaseArithmeticCandidateFound"
        ),
        "selectedPointerRelativeHandlerCount": dispatch_table_context.get("selectedPointerRelativeHandlerCount"),
        "selectedPointerRelativeHandlersVerified": dispatch_table_context.get(
            "selectedPointerRelativeHandlersVerified"
        ),
        "saveSelectorSliceAnchored": dispatch_table_context.get("saveSelectorSliceAnchored"),
        "saveSelectorSliceDirectRuntimeDispatchProofFound": dispatch_table_context.get(
            "saveSelectorSliceDirectRuntimeDispatchProofFound"
        ),
        "descriptorBoundaryDependsOnSaveSelectorSliceModel": dispatch_table_context.get(
            "descriptorBoundaryDependsOnSaveSelectorSliceModel"
        ),
        "routeRelevantSliceDataDescriptorCount": dispatch_table_context.get(
            "routeRelevantSliceDataDescriptorCount"
        ),
        "routeRelevantRawGeneralDefaultCount": dispatch_table_context.get(
            "routeRelevantRawGeneralDefaultCount"
        ),
        "routeRelevantSliceRequiresTableBaseSwitchCount": dispatch_table_context.get(
            "routeRelevantSliceRequiresTableBaseSwitchCount"
        ),
        "routeRelevantSliceDataDescriptorGenericByteReachableCount": dispatch_table_context.get(
            "routeRelevantSliceDataDescriptorGenericByteReachableCount"
        ),
        "selectedRootExecutionDispatchRefFound": dispatch_table_context.get(
            "selectedRootExecutionDispatchRefFound"
        ),
        "promotionStatus": dispatch_table_context.get("promotionStatus"),
    }
    save_gate = {
        "realCandidateCount": real_savedata_gap.get("realCandidateCount"),
        "validRealCandidateCount": real_savedata_gap.get("validRealCandidateCount"),
        "currentSelectorRealSaveCount": real_savedata_gap.get("currentSelectorRealSaveCount"),
        "selectedPointerRealSaveCount": real_savedata_gap.get("selectedPointerRealSaveCount"),
        "routePairRealSaveCount": real_savedata_gap.get("routePairRealSaveCount"),
        "routePromotionRealSaveCount": real_savedata_gap.get("routePromotionRealSaveCount"),
        "syntheticDiagnosticExcluded": real_savedata_gap.get("syntheticDiagnosticExcluded"),
        "requiredSelectorBytes": {"0x0002": "0x02", "0x0003": "0x00"},
        "promotionStatus": real_savedata_gap.get("promotionStatus"),
    }
    static_ref_gate = {
        "currentCodeRefCount": selected_pointer_usage.get("currentCodeRefCount"),
        "noStaticDirectCurrentSelectorCodeRef": selected_pointer_usage.get("noStaticDirectCurrentSelectorCodeRef"),
        "selectedPointerGlobalTextRefCount": selected_pointer_usage.get("selectedPointerGlobalTextRefCount"),
        "currentSelectorRootTextRefCount": current_root.get("textRefCount"),
        "currentSecondLevelTableTextRefCount": current_second_level.get("textRefCount"),
        "currentFrontierReaderRefCount": current_frontier_reader.get("refCount"),
        "currentSourceRecordRefCount": source_record.get("refCount"),
        "currentTargetRecordRefCount": target_record.get("refCount"),
        "selectedPointerWriterHookCount": selected_pointer_usage.get("selectedPointerWriterHookCount"),
        "selectedPointerReaderHookCount": selected_pointer_usage.get("selectedPointerReaderHookCount"),
        "selectedPointerWriteMechanisms": selected_pointer_usage.get("selectedPointerWriteMechanisms") or [],
        "selectedPointerReadMechanisms": selected_pointer_usage.get("selectedPointerReadMechanisms") or [],
        "promotionStatus": selected_pointer_usage.get("routePromotionStatus"),
    }
    hook_prerequisite_gate = selected_pointer_hook_prerequisite_summary(
        selected_pointer_usage,
        edge_trigger_gap,
        handler_call_graph,
        handler_call_graph_depth_sensitivity,
    )
    opcode_gate = {
        "selectorRowCount": global_selected_pointer_paths.get("selectorRowCount"),
        "selectorRootCount": global_selected_pointer_paths.get("selectorRootCount"),
        "scannedRootCount": global_selected_pointer_paths.get("scannedRootCount"),
        "opcode07RowCount": global_selected_pointer_paths.get("opcode07RowCount"),
        "opcode08RowCount": global_selected_pointer_paths.get("opcode08RowCount"),
        "opcode09RowCount": global_selected_pointer_paths.get("opcode09RowCount"),
        "nonCurrentOpcode07CurrentRootSelectCount": global_selected_pointer_paths.get(
            "nonCurrentOpcode07CurrentRootSelectCount"
        ),
        "nonCurrentOpcode07CurrentRangeSelectCount": global_selected_pointer_paths.get(
            "nonCurrentOpcode07CurrentRangeSelectCount"
        ),
        "nonCurrentOpcode09CurrentRootStoreCount": global_selected_pointer_paths.get(
            "nonCurrentOpcode09CurrentRootStoreCount"
        ),
        "nonCurrentOpcode09CurrentRangeStoreCount": global_selected_pointer_paths.get(
            "nonCurrentOpcode09CurrentRangeStoreCount"
        ),
        "nonCurrentOpcode08NearestCurrentRootProducerCount": global_selected_pointer_paths.get(
            "nonCurrentOpcode08NearestCurrentRootProducerCount"
        ),
        "nonCurrentOpcode08NearestCurrentRangeProducerCount": global_selected_pointer_paths.get(
            "nonCurrentOpcode08NearestCurrentRangeProducerCount"
        ),
        "currentInternalOpcode09CurrentRangeStoreCount": global_selected_pointer_paths.get(
            "currentInternalOpcode09CurrentRangeStoreCount"
        ),
        "currentInternalOpcode08NearestCurrentRangeProducerCount": global_selected_pointer_paths.get(
            "currentInternalOpcode08NearestCurrentRangeProducerCount"
        ),
        "sourceOrPredecessorOpcode08ActivatorCount": selected_pointer_opcode_paths.get(
            "sourceOrPredecessorOpcode08ActivatorCount"
        ),
        "sourceOrPredecessorCurrentRootWriterCount": selected_pointer_opcode_paths.get(
            "sourceOrPredecessorCurrentRootWriterCount"
        ),
        "sourceOrPredecessorCurrentRangeWriterCount": selected_pointer_opcode_paths.get(
            "sourceOrPredecessorCurrentRangeWriterCount"
        ),
        "currentInternalOpcode09StoreCount": selected_pointer_opcode_paths.get("currentInternalOpcode09StoreCount"),
        "selectedPointerOpcodePathPromotesRoute": selected_pointer_opcode_paths.get(
            "selectedPointerOpcodePathPromotesRoute"
        ),
        "selectedRootExecutionRefFound": global_selected_pointer_paths.get("selectedRootExecutionRefFound"),
        "promotingSelectedPointerPathCount": global_selected_pointer_paths.get("promotingSelectedPointerPathCount"),
        "promotionStatus": global_selected_pointer_paths.get("promotionStatus"),
    }
    gate_rows = [
        {
            "gate": "save-loader selected root",
            "status": "missing-current-selector",
            "evidence": (
                f"real={save_gate.get('validRealCandidateCount')}; "
                f"selector2:0={save_gate.get('currentSelectorRealSaveCount')}; "
                f"selectedPointer={save_gate.get('selectedPointerRealSaveCount')}; "
                f"routePair={save_gate.get('routePairRealSaveCount')}; "
                f"syntheticExcluded={save_gate.get('syntheticDiagnosticExcluded')}"
            ),
            "impact": "no real captured save currently selects 2:0 / 0x00540714",
        },
        {
            "gate": "save-selector dispatch table anchor",
            "status": "static-slice-only",
            "evidence": (
                f"generalTable={dispatch_gate.get('generalHandlerTableHex')}; "
                f"saveTable={dispatch_gate.get('saveSelectorHandlerTableHex')}; "
                f"sliceOffset={dispatch_gate.get('saveSelectorSliceOffsetHex')}; "
                f"genericDispatches={dispatch_gate.get('generalIndexedDispatchCount')}; "
                f"saveTableRefs={dispatch_gate.get('saveSelectorDirectDwordRefCount')}; "
                f"saveDispatches={dispatch_gate.get('saveSelectorIndexedDispatchCount')}; "
                f"dynamicDispatches={dispatch_gate.get('dynamicIndexedDispatchRowCount')}/"
                f"{dispatch_gate.get('dynamicScopeTableCallbackCount')}/"
                f"{dispatch_gate.get('dynamicSaveSelectorTableImmediateNearCount')}; "
                f"tableBaseArithmetic={dispatch_gate.get('saveSelectorTableBaseArithmeticRowCount')}/"
                f"{dispatch_gate.get('saveSelectorTableBaseArithmeticCandidateCount')}; "
                f"tableBaseSwitch={dispatch_gate.get('routeRelevantSliceRequiresTableBaseSwitchCount')}/"
                f"{dispatch_gate.get('routeRelevantSliceDataDescriptorGenericByteReachableCount')}; "
                f"selectedPointerHandlers={dispatch_gate.get('selectedPointerRelativeHandlerCount')}; "
                f"handlersVerified={dispatch_gate.get('selectedPointerRelativeHandlersVerified')}; "
                f"sliceRuntimeProof={dispatch_gate.get('saveSelectorSliceDirectRuntimeDispatchProofFound')}; "
                f"routeDescriptorRows={dispatch_gate.get('routeRelevantSliceDataDescriptorCount')}; "
                f"rawGeneralDefaultRows={dispatch_gate.get('routeRelevantRawGeneralDefaultCount')}; "
                "descriptorDependsOnSlice="
                f"{dispatch_gate.get('descriptorBoundaryDependsOnSaveSelectorSliceModel')}; "
                f"dispatchRef={dispatch_gate.get('selectedRootExecutionDispatchRefFound')}"
            ),
            "impact": "the 0x00440720 decoder slice and descriptor boundaries are statically anchored but do not prove selector 2:0 execution",
        },
        {
            "gate": "static current-root references",
            "status": "table-only-no-text-ref",
            "evidence": (
                f"currentCodeRefs={static_ref_gate.get('currentCodeRefCount')}; "
                f"rootTextRefs={static_ref_gate.get('currentSelectorRootTextRefCount')}; "
                f"secondLevelTextRefs={static_ref_gate.get('currentSecondLevelTableTextRefCount')}; "
                f"readerRefs={static_ref_gate.get('currentFrontierReaderRefCount')}; "
                f"writerHooks={static_ref_gate.get('selectedPointerWriterHookCount')}; "
                f"readerHooks={static_ref_gate.get('selectedPointerReaderHookCount')}"
            ),
            "impact": "current selector 2:0 is table data, not directly code-referenced route execution",
        },
        {
            "gate": "selected-pointer hook prerequisites",
            "status": hook_prerequisite_gate.get("gateStatus"),
            "evidence": (
                f"hooks={hook_prerequisite_gate.get('traceHookPointCount')}; "
                f"present={hook_prerequisite_gate.get('presentHookPointCount')}; "
                f"writers={hook_prerequisite_gate.get('writerHookCount')}; "
                f"readers={hook_prerequisite_gate.get('readerHookCount')}; "
                f"textRefs={hook_prerequisite_gate.get('selectedPointerGlobalTextRefCount')}; "
                f"prereqUnproven={hook_prerequisite_gate.get('routePrerequisiteUnprovenCount')}; "
                f"selfProving={hook_prerequisite_gate.get('hookSelfProvingCount')}; "
                f"promoting={hook_prerequisite_gate.get('hookPromotingCount')}; "
                f"windows={hook_prerequisite_gate.get('hookWindowScannedRefCount')}/"
                f"{hook_prerequisite_gate.get('hookWindowRouteSpecificHitCount')}; "
                "windowRefs="
                f"{hook_prerequisite_gate.get('hookWindowCurrentRootHitCount')}/"
                f"{hook_prerequisite_gate.get('hookWindowSourceStringHitCount')}/"
                f"{hook_prerequisite_gate.get('hookWindowTargetStringHitCount')}/"
                f"{hook_prerequisite_gate.get('hookWindowMapLoaderRelHitCount')}/"
                f"{hook_prerequisite_gate.get('hookWindowScriptRunnerRelHitCount')}/"
                f"{hook_prerequisite_gate.get('hookWindowSelectorTableRelHitCount')}; "
                "handlerCallGraph="
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphClassification')}; "
                "handlerGraphRoots/Fns/Calls="
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphRootCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphReachableFunctionCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphDirectCallEdgeCount')}; "
                "handlerGraphRoute/current/record/selector/branch="
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphRouteImmediateHitCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphCurrentImmediateHitCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphRouteRecordImmediateHitCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphRouteSelectorImmediateHitCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphBranchStateImmediateHitCount')}; "
                "handlerGraphGeneric="
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphSelectedPointerImmediateHitCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphSelectorTableImmediateHitCount')}; "
                "handlerGraphDepth="
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphDepthSensitivityMaxDepthChecked')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths')}/"
                f"{hook_prerequisite_gate.get('hookHandlerCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth')}; "
                "handlerEncoded="
                f"{hook_prerequisite_gate.get('hookHandlerEncodedTargetRawScalarCandidateCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerEncodedTargetRouteProofRawScalarCandidateCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerEncodedTargetRouteContextRawScalarCandidateCount')}/"
                f"{hook_prerequisite_gate.get('hookHandlerEncodedTargetPromotingCandidateCount')}; "
                "handlerEncodedClass="
                f"{hook_prerequisite_gate.get('hookHandlerEncodedTargetClassification')}; "
                "mechanisms="
                f"{','.join(hook_prerequisite_gate.get('hookMechanisms') or []) or '-'}; "
                "requirementKinds="
                f"{','.join(hook_prerequisite_gate.get('routeRequirementKinds') or []) or '-'}"
            ),
            "impact": "the selected-pointer text refs are trace hook targets; their prerequisites and handler call graph still do not reach selector 2:0 route evidence",
        },
        {
            "gate": "global opcode 07/08/09 selected-pointer paths",
            "status": "no-non-current-producer",
            "evidence": (
                f"roots={opcode_gate.get('scannedRootCount')}; "
                f"op7/8/9={opcode_gate.get('opcode07RowCount')}/"
                f"{opcode_gate.get('opcode08RowCount')}/"
                f"{opcode_gate.get('opcode09RowCount')}; "
                "nonCurrentRoot="
                f"{opcode_gate.get('nonCurrentOpcode07CurrentRootSelectCount')}/"
                f"{opcode_gate.get('nonCurrentOpcode09CurrentRootStoreCount')}/"
                f"{opcode_gate.get('nonCurrentOpcode08NearestCurrentRootProducerCount')}; "
                "nonCurrentRange="
                f"{opcode_gate.get('nonCurrentOpcode07CurrentRangeSelectCount')}/"
                f"{opcode_gate.get('nonCurrentOpcode09CurrentRangeStoreCount')}/"
                f"{opcode_gate.get('nonCurrentOpcode08NearestCurrentRangeProducerCount')}; "
                f"currentInternal={opcode_gate.get('currentInternalOpcode09CurrentRangeStoreCount')}/"
                f"{opcode_gate.get('currentInternalOpcode08NearestCurrentRangeProducerCount')}; "
                f"promoters={opcode_gate.get('promotingSelectedPointerPathCount')}"
            ),
            "impact": "source/predecessor roots do not select or store the current 2:0 root/range",
        },
        {
            "gate": "current-root writer paths",
            "status": "current-internal-only",
            "evidence": (
                f"writers={current_writers.get('writerCount')}; "
                f"starts={','.join(current_writers.get('streamStartHexes') or []) or '-'}; "
                f"selectedStores={','.join(current_writers.get('selectedPointerStoreVaHexes') or []) or '-'}; "
                f"activators={','.join(current_writers.get('activationStoreVaHexes') or []) or '-'}; "
                f"outOfRangeHelper={current_writers.get('outOfRangeHelperMentioned')}; "
                f"proofFound={current_writers.get('proofFound')}; "
                f"failedGates={','.join(current_writers.get('failedCurrentWriterPathGateIds') or [])}; "
                f"missingEvidenceCount={len(current_writers.get('missingEvidence') or [])}"
            ),
            "impact": "stores inside selector 2:0 cannot prove how normal route execution enters selector 2:0",
        },
        {
            "gate": "runtime selected-pointer probes",
            "status": "no-real-selector-2:0-observed",
            "evidence": (
                f"memory={runtime.get('memorySelectedSelector')}; "
                f"input={runtime.get('inputBaselineSelector')}->{runtime.get('inputFinalSelector')}; "
                f"keySeq={runtime.get('keySequenceReachedRouteSelector')}; "
                f"pollSamples={runtime.get('pollSampleCount')}; "
                f"pollObserved={','.join(runtime.get('pollObservedSelectors') or []) or '-'}; "
                f"pollRoute={runtime.get('pollReachedRouteSelector')}; "
                f"preludePollSamples={runtime.get('preludePollSampleCount')}; "
                f"preludePollObserved={','.join(runtime.get('preludePollObservedSelectors') or []) or '-'}; "
                f"preludePollRoute={runtime.get('preludePollReachedRouteSelector')}; "
                f"longPollSamples={runtime.get('longPollSampleCount')}; "
                f"longPollObserved={','.join(runtime.get('longPollObservedSelectors') or []) or '-'}; "
                f"longPollRoute={runtime.get('longPollReachedRouteSelector')}; "
                f"latePollSamples={runtime.get('latePollSampleCount')}; "
                f"latePollObserved={','.join(runtime.get('latePollObservedSelectors') or []) or '-'}; "
                f"latePollRoute={runtime.get('latePollReachedRouteSelector')}; "
                f"routeWatchSamples={runtime.get('routeWatchPollSampleCount')}; "
                f"routeWatchObserved={','.join(runtime.get('routeWatchPollObservedSelectors') or []) or '-'}; "
                f"routeWatchValues={runtime.get('routeWatchPollValues')}; "
                f"routeWatchRoute={runtime.get('routeWatchPollReachedRouteSelector')}; "
                f"saveLoadPollSamples={runtime.get('savedataLoadPollSampleCount')}; "
                f"saveLoadPollObserved={','.join(runtime.get('savedataLoadPollObservedSelectors') or []) or '-'}; "
                f"saveLoadPollRoute={runtime.get('savedataLoadPollReachedRouteSelector')}; "
                f"multiSaveLoadPollSamples={runtime.get('multislotSavedataLoadPollSampleCount')}; "
                "multiSaveLoadPollPublicSelectors="
                f"{','.join(runtime.get('multislotSavedataLoadPollPublicSaveSelectors') or []) or '-'}; "
                "multiSaveLoadPollObserved="
                f"{','.join(runtime.get('multislotSavedataLoadPollObservedSelectors') or []) or '-'}; "
                f"multiSaveLoadPollPublicHit={runtime.get('multislotSavedataLoadPollReachedPublicSaveSelector')}; "
                f"multiSaveLoadPollRoute={runtime.get('multislotSavedataLoadPollReachedRouteSelector')}; "
                f"caseAliasMultiSaveLoadPollSamples={runtime.get('caseAliasMultislotSavedataLoadPollSampleCount')}; "
                "caseAliasMultiSaveLoadPollObserved="
                f"{','.join(runtime.get('caseAliasMultislotSavedataLoadPollObservedSelectors') or []) or '-'}; "
                f"caseAliasMultiSaveLoadPollPublicHit={runtime.get('caseAliasMultislotSavedataLoadPollReachedPublicSaveSelector')}; "
                f"caseAliasMultiSaveLoadPollRoute={runtime.get('caseAliasMultislotSavedataLoadPollReachedRouteSelector')}; "
                f"inputPathCaseAliasMultiSaveLoadPollSamples={runtime.get('inputPathCaseAliasMultislotSavedataLoadPollSampleCount')}; "
                "inputPathCaseAliasMultiSaveLoadPollObserved="
                f"{','.join(runtime.get('inputPathCaseAliasMultislotSavedataLoadPollObservedSelectors') or []) or '-'}; "
                "inputPathCaseAliasMultiSaveLoadPollPublicHit="
                f"{runtime.get('inputPathCaseAliasMultislotSavedataLoadPollReachedPublicSaveSelector')}; "
                f"inputPathCaseAliasMultiSaveLoadPollRoute={runtime.get('inputPathCaseAliasMultislotSavedataLoadPollReachedRouteSelector')}; "
                f"predecessorDirectionSweepPollSamples={runtime.get('predecessorDirectionSweepPollSampleCount')}; "
                "predecessorDirectionSweepPollKind="
                f"{runtime.get('predecessorDirectionSweepPollStagedSaveKind')}; "
                "predecessorDirectionSweepPollObserved="
                f"{','.join(runtime.get('predecessorDirectionSweepPollObservedSelectors') or []) or '-'}; "
                "predecessorDirectionSweepPollObservedPublic="
                f"{','.join(runtime.get('predecessorDirectionSweepPollObservedPublicSaveSelectors') or []) or '-'}; "
                "predecessorDirectionSweepPollPublicHit="
                f"{runtime.get('predecessorDirectionSweepPollReachedPublicSaveSelector')}; "
                "predecessorDirectionSweepPollRoute="
                f"{runtime.get('predecessorDirectionSweepPollReachedRouteSelector')}; "
                f"predecessorDirectionSweepPollValues={runtime.get('predecessorDirectionSweepPollValues')}; "
                "predecessorLeftOverrunActivationSweepPollSamples="
                f"{runtime.get('predecessorLeftOverrunActivationSweepPollSampleCount')}; "
                "predecessorLeftOverrunActivationSweepPollKind="
                f"{runtime.get('predecessorLeftOverrunActivationSweepPollStagedSaveKind')}; "
                "predecessorLeftOverrunActivationSweepPollObserved="
                f"{','.join(runtime.get('predecessorLeftOverrunActivationSweepPollObservedSelectors') or []) or '-'}; "
                "predecessorLeftOverrunActivationSweepPollObservedPublic="
                f"{','.join(runtime.get('predecessorLeftOverrunActivationSweepPollObservedPublicSaveSelectors') or []) or '-'}; "
                "predecessorLeftOverrunActivationSweepPollPublicHit="
                f"{runtime.get('predecessorLeftOverrunActivationSweepPollReachedPublicSaveSelector')}; "
                "predecessorLeftOverrunActivationSweepPollRoute="
                f"{runtime.get('predecessorLeftOverrunActivationSweepPollReachedRouteSelector')}; "
                "predecessorLeftOverrunActivationSweepPollValues="
                f"{runtime.get('predecessorLeftOverrunActivationSweepPollValues')}; "
                f"predecessorRouteAttempt={runtime.get('predecessorRouteAttemptSummary')}; "
                f"syntheticSelector20PollSamples={runtime.get('syntheticSelector20InputPathCaseAliasPollSampleCount')}; "
                "syntheticSelector20PollObserved="
                f"{','.join(runtime.get('syntheticSelector20InputPathCaseAliasPollObservedSelectors') or []) or '-'}; "
                "syntheticSelector20PollObservedStaged="
                f"{','.join(runtime.get('syntheticSelector20InputPathCaseAliasPollObservedStagedSelectors') or []) or '-'}; "
                f"syntheticSelector20PollStagedHit={runtime.get('syntheticSelector20InputPathCaseAliasPollReachedStagedSelector')}; "
                f"syntheticSelector20PollRoute={runtime.get('syntheticSelector20InputPathCaseAliasPollReachedRouteSelector')}; "
                f"patchedPublicSelector20PollSamples={runtime.get('patchedPublicSelector20InputPathCaseAliasPollSampleCount')}; "
                "patchedPublicSelector20PollKind="
                f"{runtime.get('patchedPublicSelector20InputPathCaseAliasPollStagedSaveKind')}; "
                "patchedPublicSelector20PollObserved="
                f"{','.join(runtime.get('patchedPublicSelector20InputPathCaseAliasPollObservedSelectors') or []) or '-'}; "
                f"patchedPublicSelector20PollRoute={runtime.get('patchedPublicSelector20InputPathCaseAliasPollReachedRouteSelector')}; "
                f"constructedDiagnosticRoute={runtime.get('constructedDiagnosticPollReachedRouteSelector')}; "
                f"fileIoAttachLoadBackend={runtime.get('fileIoAttachLoadBackend')}; "
                "fileIoAttachLoadPidRuns="
                f"{runtime.get('fileIoAttachLoadSequenceWithPidCount')}/"
                f"{runtime.get('fileIoAttachLoadSequenceCount')}; "
                "fileIoAttachLoadKeyWrites="
                f"{runtime.get('fileIoAttachLoadSequenceWithKeyWritesCount')}/"
                f"{runtime.get('fileIoAttachLoadSequenceCount')}; "
                f"fileIoAttachLoadUsable={runtime.get('fileIoAttachLoadInputTraceUsable')}; "
                f"fileIoAttachLoadSavedat1={runtime.get('fileIoAttachLoadAnySavedat1Access')}; "
                f"fileIoAttachCaseAliasLoadBackend={runtime.get('fileIoAttachCaseAliasLoadBackend')}; "
                "fileIoAttachCaseAliasLoadPidRuns="
                f"{runtime.get('fileIoAttachCaseAliasLoadSequenceWithPidCount')}/"
                f"{runtime.get('fileIoAttachCaseAliasLoadSequenceCount')}; "
                "fileIoAttachCaseAliasLoadKeyWrites="
                f"{runtime.get('fileIoAttachCaseAliasLoadSequenceWithKeyWritesCount')}/"
                f"{runtime.get('fileIoAttachCaseAliasLoadSequenceCount')}; "
                f"fileIoAttachCaseAliasLoadUsable={runtime.get('fileIoAttachCaseAliasLoadInputTraceUsable')}; "
                f"fileIoAttachCaseAliasLoadSavedat1={runtime.get('fileIoAttachCaseAliasLoadAnySavedat1Access')}; "
                f"anyPollRoute={runtime.get('anyRuntimePollReachedRouteSelector')}"
            ),
            "impact": "real/public runtime probes have not observed 0x0059de30 reaching 0x00540714; the constructed selector 2:0 hit is diagnostic-only",
        },
        {
            "gate": "constructed selector 2:0 diagnostic exclusion",
            "status": "diagnostic-excluded",
            "evidence": (
                f"notRouteProof={diagnostic_exclusion.get('notRoutePromotionProof')}; "
                f"runtimeSamples={diagnostic_exclusion.get('runtimePollSampleCount')}; "
                f"observed={','.join(diagnostic_exclusion.get('runtimePollObservedSelectors') or []) or '-'}; "
                f"activeOrder={diagnostic_exclusion.get('activeOrderCountHex')}/"
                f"{','.join(diagnostic_exclusion.get('activeOrderHexes') or []) or '-'}; "
                "activeDescriptor="
                f"{(diagnostic_exclusion.get('activeSlotFirstDwordsStaticHex') or [None])[0]}; "
                f"followup={diagnostic_exclusion.get('followupSelector')}@"
                f"{diagnostic_exclusion.get('followupRootHex')}; "
                f"followupSource={diagnostic_exclusion.get('followupAliasContainsSource')}; "
                f"followupTarget={diagnostic_exclusion.get('followupAliasContainsTarget')}; "
                f"followupPublic={diagnostic_exclusion.get('followupAliasHasPublicSample')}; "
                f"bridgeExec={diagnostic_exclusion.get('aliasToCurrentExecutionLikeBridgeFound')}; "
                f"exactPointers={','.join(diagnostic_exclusion.get('exactFollowupPointerHexes') or []) or '-'}; "
                f"traceStops={','.join(diagnostic_exclusion.get('exactTraceStopReasons') or []) or '-'}; "
                f"branchStateSamples={diagnostic_exclusion.get('branchStateTotalSampleCount')}; "
                f"branchStateRouteSamples={diagnostic_exclusion.get('branchStateRouteSampleCount')}; "
                "branchStateObserved="
                f"{','.join(diagnostic_exclusion.get('branchStateObservedSelectors') or []) or '-'}; "
                f"branchStateActive={diagnostic_exclusion.get('branchStateActiveSelectionFlagHex')}; "
                f"branchStateAllZero={diagnostic_exclusion.get('branchStateSecondaryAllZero')}; "
                "branchStateMatchesFill="
                f"{diagnostic_exclusion.get('branchStateMatchesPredecessorFillHypothesis')}; "
                f"exitCandidates={diagnostic_exclusion.get('exitCandidateCount')}; "
                "exitRouteSides="
                f"{','.join(diagnostic_exclusion.get('exitCandidateRouteSelectorSides') or []) or '-'}; "
                "exitBranchNonzero="
                f"{','.join(diagnostic_exclusion.get('exitCandidateBranchStateNonzeroSides') or []) or '-'}; "
                f"exitCandidateStatus={diagnostic_exclusion.get('exitCandidatePromotionStatus')}; "
                f"leftStabilitySamples={diagnostic_exclusion.get('leftStabilitySampleCount')}; "
                "leftStabilityRouteSeq="
                f"{','.join(diagnostic_exclusion.get('leftStabilityRouteSequenceNames') or []) or '-'}; "
                "leftStabilityNonRouteSeq="
                f"{','.join(diagnostic_exclusion.get('leftStabilityNonRouteSequenceNames') or []) or '-'}; "
                "leftStabilityObserved="
                f"{','.join(diagnostic_exclusion.get('leftStabilityObservedSelectors') or []) or '-'}; "
                f"leftStabilityRouteHits={diagnostic_exclusion.get('leftStabilityRouteSelectorHitCount')}; "
                f"leftStabilityOpcode24AllZero={diagnostic_exclusion.get('leftStabilityOpcode24AllZero')}; "
                f"leftStabilityRepro={diagnostic_exclusion.get('leftStabilityRouteHitReproducibility')}; "
                f"leftRecheckSamples={diagnostic_exclusion.get('leftStabilityRecheckSampleCount')}; "
                "leftRecheckObserved="
                f"{','.join(diagnostic_exclusion.get('leftStabilityRecheckObservedSelectors') or []) or '-'}; "
                f"leftRecheckRouteHits={diagnostic_exclusion.get('leftStabilityRecheckRouteSelectorHitCount')}; "
                f"leftActiveOrderRecheckSamples={diagnostic_exclusion.get('leftActiveOrderRecheckSampleCount')}; "
                "leftActiveOrderRecheckObserved="
                f"{','.join(diagnostic_exclusion.get('leftActiveOrderRecheckObservedSelectors') or []) or '-'}; "
                f"leftActiveOrderRecheckRouteHits={diagnostic_exclusion.get('leftActiveOrderRecheckRouteSelectorHitCount')}; "
                f"leftActiveOrderCount={diagnostic_exclusion.get('leftActiveOrderRecheckActiveOrderCountValues')}; "
                f"leftStabilityStatus={diagnostic_exclusion.get('leftStabilityPromotionStatus')}"
            ),
            "impact": "constructed save bytes can exercise the load path, but are excluded from selected-root execution proof",
        },
    ]
    selected_root_execution_ref_found = (
        save_gate.get("selectedPointerRealSaveCount", 0) > 0
        or dispatch_gate.get("selectedRootExecutionDispatchRefFound") is True
        or hook_prerequisite_gate.get("hookPromotingCount", 0) > 0
        or hook_prerequisite_gate.get("hookHandlerCallGraphProofFound") is True
        or opcode_gate.get("selectedRootExecutionRefFound") is True
        or opcode_gate.get("promotingSelectedPointerPathCount", 0) > 0
        or runtime.get("anyRuntimePollReachedRouteSelector") is True
        or runtime.get("keySequenceReachedRouteSelector") is True
        or runtime.get("memoryEqualsCurrentRoot") is True
    )
    selected_root_rejection = selected_root_execution_rejection_summary(
        selected_root_execution_ref_found,
        save_gate,
        static_ref_gate,
        hook_prerequisite_gate,
        dispatch_gate,
        opcode_gate,
        current_writers,
        runtime,
        diagnostic_exclusion,
    )
    gate_statuses = {
        row.get("gate"): row.get("status")
        for row in gate_rows
        if row.get("gate")
    }
    gate_status_order = [
        "save-loader selected root",
        "save-selector dispatch table anchor",
        "static current-root references",
        "selected-pointer hook prerequisites",
        "global opcode 07/08/09 selected-pointer paths",
        "current-root writer paths",
        "runtime selected-pointer probes",
        "constructed selector 2:0 diagnostic exclusion",
    ]
    non_promoting_statuses = [
        gate_statuses.get(name)
        for name in gate_status_order
        if gate_statuses.get(name)
    ]
    remaining_proofs = [
        "captured gameplay savedat with save bytes 0x0002=0x02 and 0x0003=0x00",
        "runtime watchpoint/poll proof that 0x0059de30 becomes 0x00540714 on the route path",
        "static or VM control-flow proof that a non-current root selects/stores the current 2:0 root/range",
        "runtime/control-flow proof that the current stream is interpreted through the 0x00440720 save-selector slice",
        "strict map1_01a source hotspot remains required even after selector 2:0 evidence",
    ]
    selected_root_gate_ids_by_name = {
        "save-loader selected root": "save-loader-selected-root",
        "save-selector dispatch table anchor": "save-selector-dispatch-table-anchor",
        "static current-root references": "static-current-root-references",
        "selected-pointer hook prerequisites": "selected-pointer-hook-prerequisites",
        "global opcode 07/08/09 selected-pointer paths": "global-opcode-07-08-09-selected-pointer-paths",
        "current-root writer paths": "current-root-writer-paths",
        "runtime selected-pointer probes": "runtime-selected-pointer-probes",
        "constructed selector 2:0 diagnostic exclusion": "constructed-selector-2:0-diagnostic-exclusion",
    }
    failed_selected_root_gate_ids = [
        selected_root_gate_ids_by_name[name]
        for name in gate_status_order
        if gate_statuses.get(name) and name in selected_root_gate_ids_by_name
    ]
    evidence_refs = [
        {
            "path": "out/save_selector_real_savedata_evidence_gap.json",
            "fields": [
                "validCandidateCount",
                "requiredSelectorBytePairRealSaveCount",
                "syntheticDiagnosticExcluded",
            ],
        },
        {
            "path": "out/save_selector_selected_pointer_usage.json",
            "fields": [
                "selectedPointerGlobalHex",
                "currentSelectorRootHex",
                "currentCodeRefCount",
                "runtimeTraceHookPointCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_dispatch_table_context.json",
            "fields": [
                "saveSelectorHandlerTableHex",
                "saveSelectorSliceOffsetHex",
                "selectedRootExecutionDispatchRefFound",
            ],
        },
        {
            "path": "out/save_selector_global_selected_pointer_paths.json",
            "fields": [
                "nonCurrentOpcode07CurrentRootSelectCount",
                "nonCurrentOpcode09CurrentRootStoreCount",
                "nonCurrentOpcode08NearestCurrentRootProducerCount",
                "selectedRootExecutionRefFound",
            ],
        },
        {
            "path": "out/save_selector_current_writer_paths.json",
            "fields": [
                "writerCount",
                "currentInternalOnly",
                "promotionStatus",
            ],
        },
        {
            "path": "out/runtime_selected_pointer_poll.json",
            "fields": [
                "sampleCount",
                "observedSelectors",
                "reachedRouteSelector",
            ],
        },
        {
            "path": "out/runtime_patched_public_selector_2_0_input_path_case_alias_poll.json",
            "fields": [
                "sampleCount",
                "observedSelectors",
                "reachedRouteSelector",
                "constructedDiagnosticExcluded",
            ],
        },
        {
            "path": "out/runtime_predecessor_route_attempt_context.json",
            "fields": [
                "sourceFileCount",
                "totalSequenceCount",
                "totalSampleCount",
                "routeSelectorHitCount",
                "currentRootHitCount",
                "dominantDiversionSelector",
                "diversionRoutePromotionEvidenceFound",
            ],
        },
    ]
    return {
        "source": SOURCE,
        "target": TARGET,
        "currentSelector": CURRENT_SELECTOR,
        "currentRootHex": CURRENT_ROOT_HEX,
        "selectedPointerGlobalHex": SELECTED_POINTER_GLOBAL_HEX,
        "proofFound": selected_root_execution_ref_found,
        "selectedRootExecutionRefFound": selected_root_execution_ref_found,
        "selectedRootExecutionRejectionClassification": selected_root_rejection.get("classification"),
        "selectedRootExecutionRejection": selected_root_rejection,
        "failedSelectedRootGateIds": failed_selected_root_gate_ids,
        "missingEvidence": remaining_proofs,
        "promotionStatus": "blocked" if not selected_root_execution_ref_found else "review-required",
        "saveLoaderGate": save_gate,
        "staticReferenceGate": static_ref_gate,
        "hookPrerequisiteGate": hook_prerequisite_gate,
        "dispatchTableGate": dispatch_gate,
        "opcodeSelectedPointerGate": opcode_gate,
        "currentWriterPathGate": current_writers,
        "runtimeProbeGate": runtime,
        "diagnosticExclusionGate": diagnostic_exclusion,
        "saveLoaderGateStatus": gate_statuses.get("save-loader selected root"),
        "dispatchTableGateStatus": gate_statuses.get("save-selector dispatch table anchor"),
        "staticReferenceGateStatus": gate_statuses.get("static current-root references"),
        "hookPrerequisiteGateStatus": gate_statuses.get("selected-pointer hook prerequisites"),
        "opcodeSelectedPointerGateStatus": gate_statuses.get(
            "global opcode 07/08/09 selected-pointer paths"
        ),
        "currentWriterPathGateStatus": gate_statuses.get("current-root writer paths"),
        "runtimeProbeGateStatus": gate_statuses.get("runtime selected-pointer probes"),
        "diagnosticExclusionGateStatus": gate_statuses.get(
            "constructed selector 2:0 diagnostic exclusion"
        ),
        "selectedRootSubgateStatusOrder": gate_status_order,
        "selectedRootSubgateStatuses": gate_statuses,
        "selectedRootSubgateCount": len(gate_status_order),
        "selectedRootNonPromotingSubgateCount": len(non_promoting_statuses),
        "selectedRootAllSubgatesNonPromoting": (
            not selected_root_execution_ref_found
            and len(non_promoting_statuses) == len(gate_status_order)
        ),
        "gateRows": gate_rows,
        "remainingProofs": remaining_proofs,
        "remainingProofCount": len(remaining_proofs),
        "nextRequiredEvidence": remaining_proofs,
        "evidenceRefs": evidence_refs,
        "evidenceRefCount": len(evidence_refs),
        "conclusion": (
            "No selected-root execution reference currently promotes map1_01a -> map2_02d. The save-loader path "
            "has no real selector 2:0 sample, the 0x00440720 dispatch table remains static-slice evidence rather "
            "than an execution reference, direct static references are table-only, global opcode 07/08/09 scans "
            "find no non-current producer of the current root/range, the six selected-pointer text refs are "
            "trace hook targets whose save/slot/current-range prerequisites are all still unproven, and their "
            "local windows contain no current-root/source/target/map-loader/script-runner/selector-table route-specific refs. "
            "A bounded handler-rooted selected-pointer direct-call graph reaches only expected generic "
            "selected-pointer/selector-table context and no current-root/route-record/route-selector/branch-state hits; "
            "its encoded target scalar scan adds no promoting route-execution candidate. "
            "Current writer paths are internal to 2:0, and "
            "runtime probes (base/prelude/long/late/route-watch) have not observed 0x0059de30 reaching 0x00540714."
            " The supplemental public-save SaveData load-menu polls also observed no selector 2:0/current-root "
            "transition; the input-path case-alias multislot poll reached a staged public selector 1:0 but not 2:0."
            " A follow-up predecessor direction sweep reached the public 1:0 selector under the same "
            "input-path/case-alias save-load setup and still did not observe selector 2:0/current root."
            " A left-edge overrun activation sweep from the same public predecessor save also observed "
            "1:0/19:1/50:0 states but not selector 2:0/current root, even with Return/z/space tails."
            " The consolidated predecessor route-attempt context now covers high-frequency, nearest-exit, "
            "reciprocal-exit, trail-start, trail-left-overrun, coordinate, active-order, and branch-state "
            "public predecessor polls; across those 13 poll files it still has zero selector 2:0/current-root "
            "hits and only non-promoting diversion selectors."
            " A standalone synthetic selector 2:0 save-shaped poll under the same input-path/case-alias load path "
            "still observed only selector 8:0 and did not reach the staged selector or current root."
            " A patched public-base selector 2:0 diagnostic did make the original load path select 0x00540714; "
            "its active-order watch is stable at 0x01/[0x00] and its sampled follow-up moves to selector 10:0, "
            "which contains map2_02d but not map1_01a. Because those bytes are constructed and the follow-up "
            "bridge remains non-execution-like, the diagnostic is excluded from selected-root execution proof."
            " This selected-root blocker is classified as "
            f"{selected_root_rejection.get('classification')}."
            " A broader attached strace file-I/O probe covered the same load-menu candidate family with live "
            "PID/key-buffer writes and found no savedat file access in those bounded windows."
            " Temporary original archive case aliases reduce resource lookup trace noise, but the case-alias "
            "multislot poll still observed only 8:0 and the case-alias file-I/O probe still found no savedat access."
        ),
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Save Selector Selected-Root Execution Gap",
        "",
        f"- route: `{summary['source']} -> {summary['target']}`",
        f"- current selector: `{summary['currentSelector']}`",
        f"- current root: `{summary['currentRootHex']}`",
        f"- selected-pointer global: `{summary['selectedPointerGlobalHex']}`",
        f"- selected-root execution ref found: {summary['selectedRootExecutionRefFound']}",
        f"- proof found: {summary['proofFound']}",
        f"- rejection classification: `{summary['selectedRootExecutionRejectionClassification']}`",
        f"- failed selected-root gates: `{', '.join(summary.get('failedSelectedRootGateIds') or []) or '-'}`",
        f"- selected-root subgates non-promoting: {summary['selectedRootNonPromotingSubgateCount']} / {summary['selectedRootSubgateCount']}",
        f"- runtime/diagnostic gate status: `{summary['runtimeProbeGateStatus']}` / `{summary['diagnosticExclusionGateStatus']}`",
        f"- remaining proofs: {summary['remainingProofCount']}",
        f"- evidence refs: {summary['evidenceRefCount']}",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        summary["conclusion"],
        "",
        "## Gates",
        "",
        "| gate | status | evidence | impact |",
        "| --- | --- | --- | --- |",
    ]
    for row in summary["gateRows"]:
        lines.append(
            f"| {row['gate']} | {row['status']} | {row['evidence']} | {row['impact']} |"
        )
    lines.extend(["", "## Missing Evidence", ""])
    lines.extend(f"- {item}" for item in summary["missingEvidence"])
    lines.extend(["", "## Next Required Evidence", ""])
    lines.extend(f"- {item}" for item in summary["nextRequiredEvidence"])
    lines.extend(["", "## Evidence Refs", ""])
    for ref in summary["evidenceRefs"]:
        fields = ", ".join(ref.get("fields") or [])
        lines.append(f"- `{ref['path']}`: {fields}")
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    gate_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['gate'])}</td>"
        f"<td>{html.escape(row['status'])}</td>"
        f"<td>{html.escape(row['evidence'])}</td>"
        f"<td>{html.escape(row['impact'])}</td>"
        "</tr>"
        for row in summary["gateRows"]
    )
    next_items = "".join(
        f"<li>{html.escape(item)}</li>"
        for item in summary["nextRequiredEvidence"]
    )
    missing_items = "".join(
        f"<li>{html.escape(item)}</li>"
        for item in summary["missingEvidence"]
    )
    evidence_ref_items = "".join(
        "<li>"
        f"<code>{html.escape(ref['path'])}</code>: "
        f"{html.escape(', '.join(ref.get('fields') or []))}"
        "</li>"
        for ref in summary["evidenceRefs"]
    )
    return "\n".join([
        "<!doctype html><meta charset=\"utf-8\"><title>Save Selector Selected-Root Execution Gap</title>",
        "<style>body{font-family:system-ui,sans-serif;background:#111;color:#eee;max-width:1180px;margin:24px auto}table{border-collapse:collapse;width:100%}td,th{border:1px solid #444;padding:6px 8px;vertical-align:top}code{color:#9bd4ff}</style>",
        "<h1>Save Selector Selected-Root Execution Gap</h1>",
        f"<p>Route <code>{html.escape(summary['source'])} -&gt; {html.escape(summary['target'])}</code>; current selector <code>{html.escape(summary['currentSelector'])}</code>; current root <code>{html.escape(summary['currentRootHex'])}</code>; selected-root execution ref found: {summary['selectedRootExecutionRefFound']}; proof found: {summary['proofFound']}; rejection classification: <code>{html.escape(str(summary['selectedRootExecutionRejectionClassification']))}</code>; failed selected-root gates <code>{html.escape(','.join(summary.get('failedSelectedRootGateIds') or []) or '-')}</code>; selected-root subgates non-promoting: {summary['selectedRootNonPromotingSubgateCount']} / {summary['selectedRootSubgateCount']}; runtime/diagnostic gate status: <code>{html.escape(str(summary['runtimeProbeGateStatus']))}</code> / <code>{html.escape(str(summary['diagnosticExclusionGateStatus']))}</code>; missing evidence: {len(summary.get('missingEvidence') or [])}; remaining proofs: {summary['remainingProofCount']}; evidence refs: {summary['evidenceRefCount']}; promotion status: <code>{html.escape(summary['promotionStatus'])}</code>.</p>",
        f"<p>{html.escape(summary['conclusion'])}</p>",
        "<h2>Gates</h2>",
        "<table><thead><tr><th>gate</th><th>status</th><th>evidence</th><th>impact</th></tr></thead><tbody>",
        gate_rows,
        "</tbody></table>",
        "<h2>Missing Evidence</h2>",
        f"<ul>{missing_items}</ul>",
        "<h2>Next Required Evidence</h2>",
        f"<ul>{next_items}</ul>",
        "<h2>Evidence Refs</h2>",
        f"<ul>{evidence_ref_items}</ul>",
    ])


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


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--exe", type=Path, default=ROOT / "Hwanse2.exe")
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.out_dir / "save_selector_selected_pointer_usage.json", {}),
        load_json(args.out_dir / "save_selector_global_selected_pointer_paths.json", {}),
        load_json(args.out_dir / "save_selector_selected_pointer_opcode_paths.json", {}),
        load_json(args.out_dir / "save_selector_current_writer_paths.json", []),
        load_json(args.out_dir / "save_selector_dispatch_table_context.json", {}),
        load_json(args.out_dir / "save_selector_real_savedata_evidence_gap.json", {}),
        load_json(args.out_dir / "runtime_memory_snapshot_context.json", {}),
        load_json(args.out_dir / "runtime_input_path_probe.json", {}),
        load_json(args.out_dir / "runtime_key_sequence_probe.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_prelude_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_long_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_late_poll.json", {}),
        load_json(args.out_dir / "runtime_route_watch_values_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_savedata_load_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_multislot_savedata_load_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_multislot_savedata_load_case_alias_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_multislot_savedata_load_input_path_case_alias_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_predecessor_direction_sweep_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_predecessor_left_overrun_activation_sweep_poll.json", {}),
        load_json(args.out_dir / "runtime_predecessor_route_attempt_context.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_synthetic_selector_2_0_input_path_case_alias_poll.json", {}),
        load_json(args.out_dir / "runtime_selected_pointer_patched_public_selector_2_0_input_path_case_alias_poll.json", {}),
        load_json(args.out_dir / "runtime_save_file_io_strace_attach_load_candidates_probe.json", {}),
        load_json(args.out_dir / "runtime_save_file_io_strace_attach_load_candidates_case_alias_probe.json", {}),
        load_json(args.out_dir / "map1_01a_edge_trigger_gap.json", {}),
        load_json(args.out_dir / "runtime_patched_selector_followup_context.json", {}),
        args.exe.read_bytes() if args.exe.exists() else None,
    )
    write_outputs(summary, args.out_dir)
    print(f"wrote selected-root execution gap -> {args.out_dir / 'save_selector_selected_root_execution_gap.html'}")


if __name__ == "__main__":
    main()
