#!/usr/bin/env python3
"""Consolidate route-pair leaf-entry execution evidence for selector 2:0."""
from __future__ import annotations

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

from probe_exe_scene_tables import read_sections


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

EVIDENCE_REFS = [
    {
        "path": "out/save_selector_leaf_index_space.json",
        "fields": [
            "routeRelevantRows",
            "routePairCurrentDescriptorIndices",
            "routePairCorrectedTraceDescriptorIndices",
            "readerBearingNegativeIndices",
            "frontierReaderSelectableByNonNegativeIndex",
            "frontierReaderReachableByCorrectedNonNegativeIndex",
        ],
    },
    {
        "path": "out/save_selector_leaf_table_global_context.json",
        "fields": [
            "selectorTableCount",
            "fieldEntryRowCount",
            "currentSelectorRoutePairIndices",
            "currentFrontierLeafOnlyNegative",
        ],
    },
    {
        "path": "out/save_selector_opcode08_activation_windows.json",
        "fields": [
            "sourceOrPredecessorOpcode08ActivatorCount",
            "sourceOrPredecessorCurrentRootProducerCount",
            "sourceOrPredecessorCurrentRangeProducerCount",
            "currentInternalCurrentRangeProducerCount",
            "contextWindows",
        ],
    },
    {
        "path": "out/save_selector_opcode07_indexed_pointers.json",
        "fields": [
            "opcode07IndexMode",
            "rowCount",
            "selectedLeafTableWindowSlotCount",
            "selectedNegativeRootEntrySlotCount",
            "selectedCurrentRootEntrySlotCount",
            "selectedWrapperEntrySlotCount",
            "directFrontierTargetCount",
        ],
    },
    {
        "path": "out/save_selector_opcode09_pointer_collisions.json",
        "fields": [
            "sourceOrPredecessorOpcode09RowCount",
            "sourceOrPredecessorSupportedOpcode09RowCount",
            "sourceOrPredecessorUnsupportedModeOpcode09RowCount",
            "sourceOrPredecessorCurrentRangeStoreCount",
            "rows",
        ],
    },
    {
        "path": "out/save_selector_wrapper_descriptor_context.json",
        "fields": [
            "wrapperEntryHex",
            "wrapperDescriptorHex",
            "wrapperChildPointerHex",
            "wrapperRefBeforeCurrentRoot",
            "wrapperEntryRefs",
            "wrapperEntryPromotingRefCount",
        ],
    },
    {
        "path": "out/save_selector_selected_root_execution_gap.json",
        "fields": [
            "selectedRootExecutionRefFound",
            "currentRootHex",
            "selectedPointerGlobalHex",
            "runtimeProbeGate",
            "diagnosticExclusionGate",
            "evidenceRefs",
            "evidenceRefCount",
        ],
    },
    {
        "path": "out/save_selector_current_root_frontier_paths.json",
        "fields": [
            "strictHotspotFound",
            "frontierClusterClass",
            "frontierClusterEventCount",
            "frontierClusterSelectorRefCount",
        ],
    },
    {
        "path": "out/save_selector_route_pair_index_source_gap.json",
        "fields": [
            "routeEntryIndices",
            "entryPointerRefCount",
            "entryPointerTextRefCount",
            "entryPointerPromotingRefCount",
            "encodedEntryAnchorRawScalarCandidateCount",
            "encodedEntryAnchorPromotingCandidateCount",
            "higherLevelIndexSourceProven",
        ],
    },
    {
        "path": "out/save_selector_leaf_table_context.json",
        "fields": [
            "selector",
            "rootHex",
            "rootTablePointerHex",
            "tableWindowHex",
            "frontierLeafHex",
            "frontierReaderHex",
        ],
    },
]

ROUTE_PAIR_ENTRY_MISSING_EVIDENCE_BY_GATE = {
    "selected-root-execution": (
        "selected-root execution reaches selector 2:0 on the normal route path"
    ),
    "route-pair-index-source": (
        "higher-level selector/table index source selects route-pair entries 6 or 8"
    ),
    "source-predecessor-current-producer": (
        "source/predecessor opcode 0x08 or 0x09 producer for the current root/range"
    ),
    "wrapper-entry-execution": (
        "wrapper entry -12 executes into 0x00542ae8 on the normal route path"
    ),
    "strict-hotspot": "strict map1_01a source coordinate or hotspot linked to map2_02d",
}


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


def csv(values: list[Any] | None) -> str:
    return ",".join(str(value) for value in values or []) or "-"


def parse_hex(value: str | None) -> int | None:
    if not value:
        return None
    return int(value, 16)


def hex32(value: int | None) -> str | None:
    if not isinstance(value, int):
        return None
    return f"0x{value:08x}"


def section_for_offset(sections: list[dict], offset: int) -> dict | None:
    for section in sections:
        start = section["raw"]
        end = start + section["raw_size"]
        if start <= offset < end:
            return section
    return None


def refs_to_value(exe: bytes, sections: list[dict], value: int | None) -> list[dict]:
    if not isinstance(value, int):
        return []
    needle = struct.pack("<I", value)
    refs: list[dict] = []
    search = 0
    while True:
        hit = exe.find(needle, search)
        if hit < 0:
            break
        search = hit + 1
        section = section_for_offset(sections, hit)
        if section is None:
            continue
        refs.append({
            "section": section["name"],
            "refVaHex": hex32(section["va"] + hit - section["raw"]),
            "valueHex": hex32(value),
        })
    return refs


def aligned_refs_to_range(
    exe: bytes,
    sections: list[dict],
    start_va: int | None,
    end_va: int | None,
) -> list[dict]:
    if not isinstance(start_va, int) or not isinstance(end_va, int):
        return []
    refs: list[dict] = []
    for section in sections:
        raw_start = section["raw"]
        raw = exe[raw_start : raw_start + section["raw_size"]]
        for index in range(0, len(raw) - 3, 4):
            value = struct.unpack_from("<I", raw, index)[0]
            if start_va <= value <= end_va:
                refs.append({
                    "section": section["name"],
                    "refVaHex": hex32(section["va"] + index),
                    "valueHex": hex32(value),
                })
    return refs


def section_counts(refs: list[dict]) -> dict[str, int]:
    counts: dict[str, int] = {}
    for ref in refs:
        section = ref.get("section") or "-"
        counts[section] = counts.get(section, 0) + 1
    return dict(sorted(counts.items()))


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


def root_table_direct_ref_context(
    leaf_table_context: dict | None,
    route_pair_rows: list[dict],
    negative_reader_rows: list[dict],
    frontier_reader_hex: str | None,
) -> dict:
    leaf_table_context = leaf_table_context or {}
    exe_path = ROOT / "Hwanse2.exe"
    if not exe_path.exists():
        return {
            "status": "missing-exe",
            "tableWindowHex": leaf_table_context.get("tableWindowHex"),
        }
    exe = exe_path.read_bytes()
    sections = read_sections(exe)
    table_start, table_end = parse_table_window(leaf_table_context.get("tableWindowHex"))
    table_refs = aligned_refs_to_range(exe, sections, table_start, table_end)
    route_entry_addresses = [
        parse_hex(row.get("entryVaHex"))
        for row in route_pair_rows
        if row.get("entryVaHex")
    ]
    negative_entry_addresses = [
        parse_hex(row.get("entryVaHex"))
        for row in negative_reader_rows
        if row.get("entryVaHex")
    ]
    route_leaf_addresses = [
        parse_hex(row.get("descriptorHex"))
        for row in route_pair_rows
        if row.get("descriptorHex")
    ]
    frontier_leaf_hex = leaf_table_context.get("frontierLeafHex")
    frontier_leaf = parse_hex(frontier_leaf_hex)
    frontier_reader = parse_hex(frontier_reader_hex)
    root_table_pointer = parse_hex(leaf_table_context.get("rootTablePointerHex"))
    key_addresses = [
        ("rootTablePointer", root_table_pointer),
        *[(f"routeEntry{index}", value) for index, value in enumerate(route_entry_addresses)],
        *[(f"negativeReaderEntry{index}", value) for index, value in enumerate(negative_entry_addresses)],
    ]
    key_leaf_values = [
        *[(f"routeLeaf{index}", value) for index, value in enumerate(route_leaf_addresses)],
        ("frontierLeaf", frontier_leaf),
        ("frontierReader", frontier_reader),
    ]
    key_address_rows = []
    for name, value in key_addresses:
        refs = refs_to_value(exe, sections, value)
        key_address_rows.append({
            "name": name,
            "valueHex": hex32(value),
            "refCount": len(refs),
            "textRefCount": sum(1 for ref in refs if ref.get("section") == ".text"),
            "sectionCounts": section_counts(refs),
            "refs": refs,
        })
    key_leaf_rows = []
    for name, value in key_leaf_values:
        refs = refs_to_value(exe, sections, value)
        key_leaf_rows.append({
            "name": name,
            "valueHex": hex32(value),
            "refCount": len(refs),
            "textRefCount": sum(1 for ref in refs if ref.get("section") == ".text"),
            "sectionCounts": section_counts(refs),
            "refs": refs,
        })
    route_entry_text_refs = sum(row["textRefCount"] for row in key_address_rows if row["name"].startswith("routeEntry"))
    route_leaf_text_refs = sum(row["textRefCount"] for row in key_leaf_rows if row["name"].startswith("routeLeaf"))
    frontier_leaf_text_refs = sum(row["textRefCount"] for row in key_leaf_rows if row["name"] == "frontierLeaf")
    frontier_reader_text_refs = sum(row["textRefCount"] for row in key_leaf_rows if row["name"] == "frontierReader")
    return {
        "status": "data-only-no-text-ref"
        if table_refs and not any(ref.get("section") == ".text" for ref in table_refs)
        else "open",
        "tableWindowHex": leaf_table_context.get("tableWindowHex"),
        "tableWindowRefCount": len(table_refs),
        "tableWindowTextRefCount": sum(1 for ref in table_refs if ref.get("section") == ".text"),
        "tableWindowSectionCounts": section_counts(table_refs),
        "routeEntryAddressTextRefCount": route_entry_text_refs,
        "negativeReaderEntryAddressTextRefCount": sum(
            row["textRefCount"] for row in key_address_rows if row["name"].startswith("negativeReaderEntry")
        ),
        "routeLeafValueTextRefCount": route_leaf_text_refs,
        "frontierLeafValueTextRefCount": frontier_leaf_text_refs,
        "frontierReaderValueTextRefCount": frontier_reader_text_refs,
        "routeLeafValueRefCount": sum(row["refCount"] for row in key_leaf_rows if row["name"].startswith("routeLeaf")),
        "frontierLeafValueRefCount": sum(row["refCount"] for row in key_leaf_rows if row["name"] == "frontierLeaf"),
        "frontierReaderValueRefCount": sum(row["refCount"] for row in key_leaf_rows if row["name"] == "frontierReader"),
        "keyAddressRows": key_address_rows,
        "keyLeafRows": key_leaf_rows,
        "tableWindowRefs": table_refs,
    }


def compact_leaf_row(row: dict) -> dict:
    return {
        "rootRelativeIndex": row.get("rootRelativeIndex"),
        "entryVaHex": row.get("entryVaHex"),
        "insideCurrentRootEntryRun": row.get("insideCurrentRootEntryRun"),
        "descriptorHex": row.get("descriptorHex"),
        "childPointerHex": row.get("childPointerHex"),
        "descriptorFieldMaps": row.get("descriptorFieldMaps") or [],
        "descriptorNestedFieldMaps": row.get("descriptorNestedFieldMaps") or [],
        "childFieldMaps": row.get("childFieldMaps") or [],
        "descriptorHasRoutePair": row.get("descriptorHasRoutePair"),
        "childHasRoutePair": row.get("childHasRoutePair"),
        "descriptorTraceContainsFrontierReader": row.get("descriptorTraceContainsFrontierReader"),
        "childTraceContainsFrontierReader": row.get("childTraceContainsFrontierReader"),
        "correctedDescriptorTraceContainsFrontierReader": row.get(
            "correctedDescriptorTraceContainsFrontierReader"
        ),
        "correctedDescriptorFrontierReaderStep": row.get("correctedDescriptorFrontierReaderStep"),
        "effectiveDescriptorTraceContainsFrontierReader": row.get(
            "effectiveDescriptorTraceContainsFrontierReader"
        ),
    }


def selected_root_runtime_summary(selected_root_execution_gap: dict) -> dict:
    runtime_gate = selected_root_execution_gap.get("runtimeProbeGate") or {}
    diagnostic_gate = selected_root_execution_gap.get("diagnosticExclusionGate") or {}
    return {
        "pollSampleCount": runtime_gate.get("pollSampleCount"),
        "pollObservedSelectors": runtime_gate.get("pollObservedSelectors") or [],
        "routeWatchPollSampleCount": runtime_gate.get("routeWatchPollSampleCount"),
        "routeWatchPollObservedSelectors": runtime_gate.get("routeWatchPollObservedSelectors") or [],
        "routeWatchPollValues": runtime_gate.get("routeWatchPollValues"),
        "predecessorDirectionSweepPollSampleCount": runtime_gate.get(
            "predecessorDirectionSweepPollSampleCount"
        ),
        "predecessorDirectionSweepPollObservedSelectors": runtime_gate.get(
            "predecessorDirectionSweepPollObservedSelectors"
        )
        or [],
        "predecessorDirectionSweepPollReachedRouteSelector": runtime_gate.get(
            "predecessorDirectionSweepPollReachedRouteSelector"
        ),
        "predecessorLeftOverrunActivationSweepPollSampleCount": runtime_gate.get(
            "predecessorLeftOverrunActivationSweepPollSampleCount"
        ),
        "predecessorLeftOverrunActivationSweepPollObservedSelectors": runtime_gate.get(
            "predecessorLeftOverrunActivationSweepPollObservedSelectors"
        )
        or [],
        "predecessorLeftOverrunActivationSweepPollReachedRouteSelector": runtime_gate.get(
            "predecessorLeftOverrunActivationSweepPollReachedRouteSelector"
        ),
        "patchedPublicSelector20PollSampleCount": runtime_gate.get(
            "patchedPublicSelector20InputPathCaseAliasPollSampleCount"
        ),
        "patchedPublicSelector20PollObservedSelectors": runtime_gate.get(
            "patchedPublicSelector20InputPathCaseAliasPollObservedSelectors"
        )
        or [],
        "constructedDiagnosticPollReachedRouteSelector": runtime_gate.get(
            "constructedDiagnosticPollReachedRouteSelector"
        ),
        "diagnosticExcludedFromSelectedRootExecutionProof": diagnostic_gate.get(
            "excludedFromSelectedRootExecutionProof"
        ),
        "diagnosticFollowupSelector": diagnostic_gate.get("followupSelector"),
        "diagnosticBridgeExecutionLike": diagnostic_gate.get("aliasToCurrentExecutionLikeBridgeFound"),
    }


def compact_opcode08_context(context: dict) -> dict:
    return {
        "selector": context.get("selector"),
        "role": context.get("role"),
        "rangeHex": context.get("rangeHex"),
        "activationCount": context.get("activationCount"),
        "nearestCurrentRootProducerCount": context.get("nearestCurrentRootProducerCount"),
        "nearestCurrentRangeProducerCount": context.get("nearestCurrentRangeProducerCount"),
        "nearestOwnRangeProducerCount": context.get("nearestOwnRangeProducerCount"),
        "nearestScriptScalarProducerCount": context.get("nearestScriptScalarProducerCount"),
        "nearestUnreadableProducerCount": context.get("nearestUnreadableProducerCount"),
        "nearestNoLocalProducerCount": context.get("nearestNoLocalProducerCount"),
    }


def opcode08_context_summary(row: dict) -> str:
    return (
        f"{row.get('selector')}:op8={row.get('activationCount')},"
        f"currentRootRange={row.get('nearestCurrentRootProducerCount')}/"
        f"{row.get('nearestCurrentRangeProducerCount')},"
        f"own={row.get('nearestOwnRangeProducerCount')},"
        f"script={row.get('nearestScriptScalarProducerCount')},"
        f"unreadable={row.get('nearestUnreadableProducerCount')}"
    )


def compact_opcode09_collision_row(row: dict) -> dict:
    return {
        "selector": row.get("selector"),
        "vaHex": row.get("vaHex"),
        "valueHex": row.get("valueHex"),
        "valueSection": row.get("valueSection"),
        "modeHex": row.get("modeHex"),
        "storedPointerSource": row.get("storedPointerSource"),
        "modeSupportedByHandler": row.get("modeSupportedByHandler"),
        "unsupportedModeReturnsWithoutStore": row.get("unsupportedModeReturnsWithoutStore"),
        "pointerCollision": row.get("pointerCollision"),
        "classification": row.get("classification"),
    }


def opcode09_collision_summary(row: dict) -> str:
    return (
        f"{row.get('selector')}@{row.get('vaHex')}="
        f"{row.get('valueHex')}/{row.get('modeHex')}/"
        f"{row.get('valueSection') or '-'}"
    )


def build_summary(
    leaf_index_space: dict,
    leaf_table_global_context: dict,
    opcode08_activation_windows: dict,
    opcode07_indexed_pointers: dict,
    opcode09_pointer_collisions: dict,
    wrapper_descriptor_context: dict,
    selected_root_execution_gap: dict,
    current_root_frontier_paths: dict | None = None,
    route_pair_index_source_gap: dict | None = None,
    leaf_table_context: dict | None = None,
) -> dict:
    current_root_frontier_paths = current_root_frontier_paths or {}
    route_pair_index_source_gap = route_pair_index_source_gap or {}
    route_rows_by_index = {
        row.get("rootRelativeIndex"): compact_leaf_row(row)
        for row in leaf_index_space.get("routeRelevantRows") or []
    }
    route_pair_indices = leaf_index_space.get("routePairCurrentDescriptorIndices") or []
    corrected_route_pair_indices = leaf_index_space.get("routePairCorrectedTraceDescriptorIndices") or []
    negative_reader_indices = leaf_index_space.get("readerBearingNegativeIndices") or []
    route_pair_rows = [route_rows_by_index[index] for index in route_pair_indices if index in route_rows_by_index]
    negative_reader_rows = [
        route_rows_by_index[index] for index in negative_reader_indices if index in route_rows_by_index
    ]
    global_current_route_pair_indices = leaf_table_global_context.get("currentSelectorRoutePairIndices") or []
    global_current_frontier_leaf_only_negative = (
        leaf_table_global_context.get("currentFrontierLeafOnlyNegative") is True
    )
    opcode07_direct_selection_absent = (
        opcode07_indexed_pointers.get("selectedLeafTableWindowSlotCount") == 0
        and opcode07_indexed_pointers.get("selectedNegativeRootEntrySlotCount") == 0
        and opcode07_indexed_pointers.get("selectedCurrentRootEntrySlotCount") == 0
        and opcode07_indexed_pointers.get("selectedWrapperEntrySlotCount") == 0
        and opcode07_indexed_pointers.get("directFrontierTargetCount") == 0
    )
    opcode08_source_current_root_count = (
        opcode08_activation_windows.get("sourceOrPredecessorCurrentRootProducerCount") or 0
    )
    opcode08_source_current_range_count = (
        opcode08_activation_windows.get("sourceOrPredecessorCurrentRangeProducerCount") or 0
    )
    opcode09_source_current_range_count = (
        opcode09_pointer_collisions.get("sourceOrPredecessorCurrentRangeStoreCount") or 0
    )
    opcode08_selector_bucket_rows = [
        compact_opcode08_context(context)
        for context in opcode08_activation_windows.get("contextWindows") or []
    ]
    opcode08_source_predecessor_bucket_rows = [
        row
        for row in opcode08_selector_bucket_rows
        if row.get("selector") in {"0:0", "1:0"}
    ]
    opcode08_current_selector_bucket_rows = [
        row for row in opcode08_selector_bucket_rows if row.get("selector") == "2:0"
    ]
    opcode08_source_predecessor_bucket_summary = ";".join(
        opcode08_context_summary(row) for row in opcode08_source_predecessor_bucket_rows
    )
    opcode08_current_selector_contrast_summary = ";".join(
        opcode08_context_summary(row) for row in opcode08_current_selector_bucket_rows
    )
    opcode09_source_predecessor_pointer_collision_rows = [
        compact_opcode09_collision_row(row)
        for row in opcode09_pointer_collisions.get("rows") or []
        if row.get("selector") in {"0:0", "1:0"} and row.get("pointerCollision") is True
    ]
    opcode09_source_predecessor_pointer_collision_summary = ";".join(
        opcode09_collision_summary(row)
        for row in opcode09_source_predecessor_pointer_collision_rows
    )
    source_or_predecessor_current_producer_count = (
        opcode08_source_current_root_count
        + opcode08_source_current_range_count
        + opcode09_source_current_range_count
    )
    wrapper_execution_proof_found = (
        wrapper_descriptor_context.get("wrapperEntryPromotingRefCount", 0) > 0
        or wrapper_descriptor_context.get("currentRootReferencesWrapper") is True
    )
    wrapper_entry_refs = wrapper_descriptor_context.get("wrapperEntryRefs") or []
    wrapper_entry_current_root_entry_run_ref_count = (
        wrapper_descriptor_context.get("wrapperEntryCurrentRootEntryRunRefCount") or 0
    )
    wrapper_entry_opcode5a_fallthrough_ref_count = sum(
        1
        for row in wrapper_entry_refs
        if row.get("referenceRole") == "opcode-0x5a-mode0-fallthrough-word"
        and row.get("promotesWrapperSelection") is False
    )
    wrapper_entry_fallthrough_non_code_ref_count = sum(
        1
        for row in wrapper_entry_refs
        if row.get("referenceRole") == "opcode-0x5a-mode0-fallthrough-word"
        and row.get("fallthroughWordHandlerIsCode") is False
        and row.get("fallthroughWordCanJumpToDwordAtPlus4") is False
    )
    wrapper_entry_fallthrough_handler_summaries = [
        (
            f"{row.get('fallthroughWordValueHex')}/{row.get('fallthroughWordOpcodeHex')}"
            f"->{row.get('fallthroughWordHandlerHex') or '-'}"
            f"/{row.get('fallthroughWordHandlerSection') or '-'}"
        )
        for row in wrapper_entry_refs
        if row.get("referenceRole") == "opcode-0x5a-mode0-fallthrough-word"
    ]
    wrapper_entry_only_ref_is_opcode5a_fallthrough = (
        wrapper_descriptor_context.get("wrapperEntryRefCount") == 1
        and wrapper_entry_opcode5a_fallthrough_ref_count == 1
    )
    selected_root_execution_ref_found = selected_root_execution_gap.get("selectedRootExecutionRefFound") is True
    route_pair_corrected_reader_grounded = (
        bool(route_pair_indices)
        and corrected_route_pair_indices == route_pair_indices
        and all(row.get("correctedDescriptorTraceContainsFrontierReader") is True for row in route_pair_rows)
    )
    route_pair_entry_execution_proven = (
        selected_root_execution_ref_found
        and route_pair_corrected_reader_grounded
        and source_or_predecessor_current_producer_count > 0
    )
    corrected_trace_normal_selection_gap_found = (
        route_pair_corrected_reader_grounded
        and leaf_index_space.get("frontierReaderReachableByCorrectedNonNegativeIndex") is True
        and leaf_index_space.get("frontierReaderSelectableByNonNegativeIndex") is False
        and global_current_frontier_leaf_only_negative
        and opcode07_direct_selection_absent
        and source_or_predecessor_current_producer_count == 0
        and not wrapper_execution_proof_found
        and not selected_root_execution_ref_found
    )
    corrected_trace_normal_selection_gap_status = (
        "corrected-trace-not-normal-selection-proof"
        if corrected_trace_normal_selection_gap_found
        else "open"
    )
    direct_entry_pointer_source_proven = (
        route_pair_index_source_gap.get("higherLevelIndexSourceProven") is True
        or route_pair_index_source_gap.get("entryPointerPromotingRefCount", 0) > 0
        or route_pair_index_source_gap.get("encodedEntryAnchorPromotingCandidateCount", 0) > 0
    )
    strict_hotspot_found = (
        leaf_index_space.get("strictHotspotFound") is True
        or current_root_frontier_paths.get("strictHotspotFound") is True
    )
    failed_route_pair_entry_gate_ids = []
    if not selected_root_execution_ref_found:
        failed_route_pair_entry_gate_ids.append("selected-root-execution")
    if not direct_entry_pointer_source_proven:
        failed_route_pair_entry_gate_ids.append("route-pair-index-source")
    if source_or_predecessor_current_producer_count == 0:
        failed_route_pair_entry_gate_ids.append("source-predecessor-current-producer")
    if not wrapper_execution_proof_found:
        failed_route_pair_entry_gate_ids.append("wrapper-entry-execution")
    if not strict_hotspot_found:
        failed_route_pair_entry_gate_ids.append("strict-hotspot")
    missing_evidence = [
        ROUTE_PAIR_ENTRY_MISSING_EVIDENCE_BY_GATE.get(gate_id, gate_id)
        for gate_id in failed_route_pair_entry_gate_ids
    ]
    table_direct_ref_context = root_table_direct_ref_context(
        leaf_table_context,
        route_pair_rows,
        negative_reader_rows,
        leaf_index_space.get("frontierReaderHex"),
    )
    entry_selection_gap_open = not route_pair_entry_execution_proven
    promotion_status = (
        "ready-for-review"
        if route_pair_entry_execution_proven and strict_hotspot_found
        else "blocked"
    )
    evidence_rows = [
        {
            "kind": "route-pair-current-entries",
            "status": "corrected-reader-trace-only"
            if route_pair_corrected_reader_grounded
            else "missing-corrected-reader-trace",
            "detail": (
                f"indices={csv(route_pair_indices)}; corrected={csv(corrected_route_pair_indices)}; "
                f"readerReachableByCorrectedNonNegativeIndex="
                f"{leaf_index_space.get('frontierReaderReachableByCorrectedNonNegativeIndex')}"
            ),
        },
        {
            "kind": "negative-wrapper-reader",
            "status": "outside-current-root-run",
            "detail": (
                f"indices={csv(negative_reader_indices)}; wrapperEntry="
                f"{wrapper_descriptor_context.get('wrapperEntryHex')}; wrapper="
                f"{wrapper_descriptor_context.get('wrapperDescriptorHex')}; child="
                f"{wrapper_descriptor_context.get('wrapperChildPointerHex')}; "
                f"entryRunRefs={wrapper_entry_current_root_entry_run_ref_count}; "
                f"opcode5aFallthroughRefs={wrapper_entry_opcode5a_fallthrough_ref_count}; "
                f"fallthroughNonCodeRefs={wrapper_entry_fallthrough_non_code_ref_count}; "
                f"fallthroughHandlers={','.join(wrapper_entry_fallthrough_handler_summaries) or '-'}"
            ),
        },
        {
            "kind": "route-entry-pointer-source-refs",
            "status": "non-promoting-fallthrough-only"
            if route_pair_index_source_gap
            and not direct_entry_pointer_source_proven
            and route_pair_index_source_gap.get("entryPointerOpcode5aFallthroughRefCount") == (
                route_pair_index_source_gap.get("entryPointerRefCount")
            )
            else "open",
            "detail": (
                f"routeEntryIdx={csv(route_pair_index_source_gap.get('routeEntryIndices') or [])}; "
                f"entryRefs={route_pair_index_source_gap.get('entryPointerRefCount')}; "
                f"textRefs={route_pair_index_source_gap.get('entryPointerTextRefCount')}; "
                f"promotingRefs={route_pair_index_source_gap.get('entryPointerPromotingRefCount')}; "
                f"opcode5aFallthroughRefs="
                f"{route_pair_index_source_gap.get('entryPointerOpcode5aFallthroughRefCount')}; "
                f"fallthroughNonCodeRefs="
                f"{route_pair_index_source_gap.get('entryPointerFallthroughNonCodeRefCount')}; "
                f"nonNegPromoting="
                f"{route_pair_index_source_gap.get('nonNegativeEntryPointerPromotingRefCount')}; "
                f"negativeReaderPromoting="
                f"{route_pair_index_source_gap.get('negativeReaderEntryPointerPromotingRefCount')}; "
                f"encodedRaw={route_pair_index_source_gap.get('encodedEntryAnchorRawScalarCandidateCount')}; "
                f"encodedBranch={route_pair_index_source_gap.get('encodedEntryAnchorBranchAttachedEncodedFieldCount')}; "
                f"encodedModeled={route_pair_index_source_gap.get('encodedEntryAnchorModeledControlFlowCandidateCount')}; "
                f"encodedPromoting={route_pair_index_source_gap.get('encodedEntryAnchorPromotingCandidateCount')}; "
                f"encodedClass={route_pair_index_source_gap.get('encodedEntryAnchorClassification')}; "
                f"handlers={','.join(route_pair_index_source_gap.get('entryPointerFallthroughHandlerSummaries') or []) or '-'}; "
                f"descriptorTableOnly={route_pair_index_source_gap.get('descriptorRefsOnlyTableCells')}; "
                f"childDescriptorWordOnly={route_pair_index_source_gap.get('childRefsOnlyDescriptorChildWords')}"
            ),
        },
        {
            "kind": "global-leaf-table-context",
            "status": "frontier-leaf-negative-only"
            if global_current_frontier_leaf_only_negative
            else "frontier-leaf-nonnegative-open",
            "detail": (
                f"selectorTables={leaf_table_global_context.get('selectorTableCount')}; "
                f"fieldEntries={leaf_table_global_context.get('fieldEntryRowCount')}; "
                f"negative/nonNegative="
                f"{leaf_table_global_context.get('negativeFieldEntryRowCount')}/"
                f"{leaf_table_global_context.get('nonNegativeFieldEntryRowCount')}; "
                f"currentRoutePairIdx={csv(global_current_route_pair_indices)}; "
                f"frontierLeafOnlyNegative={global_current_frontier_leaf_only_negative}"
            ),
        },
        {
            "kind": "root-table-direct-ref-context",
            "status": table_direct_ref_context.get("status") or "unknown",
            "detail": (
                f"tableWindow={table_direct_ref_context.get('tableWindowHex')}; "
                f"tableRefs={table_direct_ref_context.get('tableWindowRefCount')}/"
                f"{table_direct_ref_context.get('tableWindowTextRefCount')}; "
                f"sections={table_direct_ref_context.get('tableWindowSectionCounts')}; "
                f"routeEntryTextRefs={table_direct_ref_context.get('routeEntryAddressTextRefCount')}; "
                f"routeLeafTextRefs={table_direct_ref_context.get('routeLeafValueTextRefCount')}; "
                f"frontierLeafTextRefs={table_direct_ref_context.get('frontierLeafValueTextRefCount')}; "
                f"frontierReaderTextRefs={table_direct_ref_context.get('frontierReaderValueTextRefCount')}; "
                f"frontierReaderRefs={table_direct_ref_context.get('frontierReaderValueRefCount')}"
            ),
        },
        {
            "kind": "opcode07-direct-entry-selection",
            "status": "absent" if opcode07_direct_selection_absent else "present",
            "detail": (
                f"rowCount={opcode07_indexed_pointers.get('rowCount')}; "
                f"indexMode={opcode07_indexed_pointers.get('opcode07IndexMode')}; "
                f"leafWindow={opcode07_indexed_pointers.get('selectedLeafTableWindowSlotCount')}; "
                f"negative={opcode07_indexed_pointers.get('selectedNegativeRootEntrySlotCount')}; "
                f"current={opcode07_indexed_pointers.get('selectedCurrentRootEntrySlotCount')}; "
                f"wrapper={opcode07_indexed_pointers.get('selectedWrapperEntrySlotCount')}; "
                f"directFrontier={opcode07_indexed_pointers.get('directFrontierTargetCount')}"
            ),
        },
        {
            "kind": "opcode08-activation-window",
            "status": "source-predecessor-current-producer-absent"
            if not (opcode08_source_current_root_count or opcode08_source_current_range_count)
            else "source-predecessor-current-producer-present",
            "detail": (
                f"sourcePredecessorActivators="
                f"{opcode08_activation_windows.get('sourceOrPredecessorOpcode08ActivatorCount')}; "
                f"currentRoot={opcode08_source_current_root_count}; "
                f"currentRange={opcode08_source_current_range_count}; "
                f"ownRange={opcode08_activation_windows.get('sourceOrPredecessorOwnRangeProducerCount')}; "
                f"scriptScalar={opcode08_activation_windows.get('sourceOrPredecessorScriptScalarProducerCount')}; "
                f"currentInternalRange="
                f"{opcode08_activation_windows.get('currentInternalCurrentRangeProducerCount')}; "
                f"sourcePredBuckets={opcode08_source_predecessor_bucket_summary or '-'}; "
                f"currentContrast={opcode08_current_selector_contrast_summary or '-'}; "
                f"promotes={opcode08_activation_windows.get('opcode08ActivationPromotesRoute')}"
            ),
        },
        {
            "kind": "opcode09-selected-pointer-store",
            "status": "source-predecessor-current-store-absent"
            if opcode09_source_current_range_count == 0
            else "source-predecessor-current-store-present",
            "detail": (
                f"sourcePredecessorRows="
                f"{opcode09_pointer_collisions.get('sourceOrPredecessorOpcode09RowCount')}; "
                f"supported={opcode09_pointer_collisions.get('sourceOrPredecessorSupportedOpcode09RowCount')}; "
                f"unsupported={opcode09_pointer_collisions.get('sourceOrPredecessorUnsupportedModeOpcode09RowCount')}; "
                f"unsupportedModes="
                f"{','.join(opcode09_pointer_collisions.get('sourceOrPredecessorUnsupportedModesHex') or []) or '-'}; "
                f"pointerCollisions={opcode09_pointer_collisions.get('sourceOrPredecessorPointerCollisionRowCount')}; "
                f"currentRangeStores={opcode09_source_current_range_count}; "
                f"activationLinkedCollisions="
                f"{opcode09_pointer_collisions.get('activationLinkedPointerCollisionCount')}; "
                f"collisionRows={opcode09_source_predecessor_pointer_collision_summary or '-'}; "
                f"promotes={opcode09_pointer_collisions.get('opcode09PointerCollisionPromotesRoute')}"
            ),
        },
        {
            "kind": "corrected-trace-normal-selection-gap",
            "status": corrected_trace_normal_selection_gap_status,
            "detail": (
                f"correctedReaderGrounded={route_pair_corrected_reader_grounded}; "
                "nonNegativeSelectable="
                f"{leaf_index_space.get('frontierReaderSelectableByNonNegativeIndex')}; "
                "nonNegativeCorrectedReachable="
                f"{leaf_index_space.get('frontierReaderReachableByCorrectedNonNegativeIndex')}; "
                f"frontierLeafNegativeOnly={global_current_frontier_leaf_only_negative}; "
                f"opcode07DirectAbsent={opcode07_direct_selection_absent}; "
                f"sourcePredCurrentProducers={source_or_predecessor_current_producer_count}; "
                f"wrapperExec={wrapper_execution_proof_found}; "
                f"selectedRootRef={selected_root_execution_ref_found}"
            ),
        },
        {
            "kind": "selected-root-execution",
            "status": "missing" if not selected_root_execution_ref_found else "found",
            "detail": (
                f"selectedRootExecutionRefFound={selected_root_execution_ref_found}; "
                f"currentRoot={selected_root_execution_gap.get('currentRootHex')}; "
                f"selectedPointerGlobal={selected_root_execution_gap.get('selectedPointerGlobalHex')}; "
                f"promotion={selected_root_execution_gap.get('promotionStatus')}"
            ),
        },
        {
            "kind": "strict-hotspot",
            "status": "missing" if not strict_hotspot_found else "found",
            "detail": (
                f"leafIndexStrict={leaf_index_space.get('strictHotspotFound')}; "
                f"frontierStrict={current_root_frontier_paths.get('strictHotspotFound')}; "
                f"frontierClusterClass={current_root_frontier_paths.get('frontierClusterClass')}"
            ),
        },
    ]
    conclusion = (
        "Selector 2:0 has current-root route-pair entries 6 and 8, and opcode 0x2c-corrected traces from "
        "both entries reach reader 0x00542b0c. This still does not prove normal route execution chooses those "
        "entries: opcode 0x07 has no direct entry selection, source/predecessor opcode 0x08 and 0x09 windows "
        "do not produce the current root/range, explicit entry-pointer refs to -12/6/8 are non-code opcode 0x5a "
        "fallthrough words, the negative wrapper entry -12 is outside the current root run, the reader is "
        "corrected-reachable but not selectable by a non-negative index, and selected-root runtime proof remains "
        "absent."
    )
    return {
        "source": leaf_index_space.get("source") or SOURCE,
        "target": leaf_index_space.get("target") or TARGET,
        "selector": leaf_index_space.get("selector") or "2:0",
        "rootHex": leaf_index_space.get("rootHex"),
        "rootTablePointerHex": leaf_index_space.get("rootTablePointerHex"),
        "frontierLeafHex": leaf_index_space.get("frontierLeafHex"),
        "frontierReaderHex": leaf_index_space.get("frontierReaderHex"),
        "routePairEntryIndices": route_pair_indices,
        "routePairCorrectedTraceEntryIndices": corrected_route_pair_indices,
        "negativeReaderEntryIndices": negative_reader_indices,
        "routePairCurrentEntryCount": leaf_index_space.get("routePairDescriptorCurrentEntryCount"),
        "routePairCorrectedTraceReachesReaderCount": leaf_index_space.get(
            "correctedRoutePairTraceReachesReaderCount"
        ),
        "routePairCorrectedReaderGrounded": route_pair_corrected_reader_grounded,
        "globalSelectorTableCount": leaf_table_global_context.get("selectorTableCount"),
        "globalFieldEntryRowCount": leaf_table_global_context.get("fieldEntryRowCount"),
        "globalNegativeFieldEntryRowCount": leaf_table_global_context.get("negativeFieldEntryRowCount"),
        "globalNonNegativeFieldEntryRowCount": leaf_table_global_context.get(
            "nonNegativeFieldEntryRowCount"
        ),
        "globalCurrentSelectorRoutePairIndices": global_current_route_pair_indices,
        "globalCurrentSelectorNegativeRoutePairRowCount": leaf_table_global_context.get(
            "currentSelectorNegativeRoutePairRowCount"
        ),
        "globalCurrentSelectorNonNegativeRoutePairRowCount": leaf_table_global_context.get(
            "currentSelectorNonNegativeRoutePairRowCount"
        ),
        "globalCurrentFrontierLeafOnlyNegative": global_current_frontier_leaf_only_negative,
        "frontierReaderSelectableByNonNegativeIndex": leaf_index_space.get(
            "frontierReaderSelectableByNonNegativeIndex"
        ),
        "frontierReaderReachableByCorrectedNonNegativeIndex": leaf_index_space.get(
            "frontierReaderReachableByCorrectedNonNegativeIndex"
        ),
        "correctedTraceNormalSelectionGapFound": corrected_trace_normal_selection_gap_found,
        "correctedTraceNormalSelectionGapStatus": corrected_trace_normal_selection_gap_status,
        "opcode07DirectEntrySelectionAbsent": opcode07_direct_selection_absent,
        "opcode07SelectedLeafTableWindowSlotCount": opcode07_indexed_pointers.get(
            "selectedLeafTableWindowSlotCount"
        ),
        "opcode07SelectedNegativeRootEntrySlotCount": opcode07_indexed_pointers.get(
            "selectedNegativeRootEntrySlotCount"
        ),
        "opcode07SelectedCurrentRootEntrySlotCount": opcode07_indexed_pointers.get(
            "selectedCurrentRootEntrySlotCount"
        ),
        "opcode07SelectedWrapperEntrySlotCount": opcode07_indexed_pointers.get(
            "selectedWrapperEntrySlotCount"
        ),
        "opcode07DirectFrontierTargetCount": opcode07_indexed_pointers.get("directFrontierTargetCount"),
        "opcode08SourceOrPredecessorActivatorCount": opcode08_activation_windows.get(
            "sourceOrPredecessorOpcode08ActivatorCount"
        ),
        "opcode08SourceOrPredecessorCurrentRootProducerCount": opcode08_source_current_root_count,
        "opcode08SourceOrPredecessorCurrentRangeProducerCount": opcode08_source_current_range_count,
        "opcode08CurrentInternalCurrentRangeProducerCount": opcode08_activation_windows.get(
            "currentInternalCurrentRangeProducerCount"
        ),
        "opcode08SelectorBucketRows": opcode08_selector_bucket_rows,
        "opcode08SourcePredecessorBucketSummary": opcode08_source_predecessor_bucket_summary,
        "opcode08CurrentSelectorContrastSummary": opcode08_current_selector_contrast_summary,
        "opcode08ActivationPromotesRoute": opcode08_activation_windows.get("opcode08ActivationPromotesRoute"),
        "opcode09SourceOrPredecessorCurrentRangeStoreCount": opcode09_source_current_range_count,
        "opcode09SourceOrPredecessorSupportedOpcode09RowCount": opcode09_pointer_collisions.get(
            "sourceOrPredecessorSupportedOpcode09RowCount"
        ),
        "opcode09SourceOrPredecessorUnsupportedModeOpcode09RowCount": opcode09_pointer_collisions.get(
            "sourceOrPredecessorUnsupportedModeOpcode09RowCount"
        ),
        "opcode09SourceOrPredecessorUnsupportedModesHex": opcode09_pointer_collisions.get(
            "sourceOrPredecessorUnsupportedModesHex"
        )
        or [],
        "opcode09SourceOrPredecessorUnsupportedModePointerCollisionCount": opcode09_pointer_collisions.get(
            "sourceOrPredecessorUnsupportedModePointerCollisionCount"
        ),
        "opcode09SourceOrPredecessorPointerCollisionRowCount": opcode09_pointer_collisions.get(
            "sourceOrPredecessorPointerCollisionRowCount"
        ),
        "opcode09ActivationLinkedPointerCollisionCount": opcode09_pointer_collisions.get(
            "activationLinkedPointerCollisionCount"
        ),
        "opcode09SourcePredecessorPointerCollisionRows": opcode09_source_predecessor_pointer_collision_rows,
        "opcode09SourcePredecessorPointerCollisionSummary": (
            opcode09_source_predecessor_pointer_collision_summary
        ),
        "opcode09PointerCollisionPromotesRoute": opcode09_pointer_collisions.get(
            "opcode09PointerCollisionPromotesRoute"
        ),
        "sourceOrPredecessorCurrentProducerCount": source_or_predecessor_current_producer_count,
        "routePairIndexSourceRouteEntryIndices": route_pair_index_source_gap.get("routeEntryIndices") or [],
        "routePairIndexSourceEntryPointerRefCount": route_pair_index_source_gap.get(
            "entryPointerRefCount"
        ),
        "routePairIndexSourceEntryPointerTextRefCount": route_pair_index_source_gap.get(
            "entryPointerTextRefCount"
        ),
        "routePairIndexSourceEntryPointerPromotingRefCount": route_pair_index_source_gap.get(
            "entryPointerPromotingRefCount"
        ),
        "routePairIndexSourceEncodedEntryAnchorRawScalarCandidateCount": route_pair_index_source_gap.get(
            "encodedEntryAnchorRawScalarCandidateCount"
        ),
        "routePairIndexSourceEncodedEntryAnchorBranchAttachedEncodedFieldCount": route_pair_index_source_gap.get(
            "encodedEntryAnchorBranchAttachedEncodedFieldCount"
        ),
        "routePairIndexSourceEncodedEntryAnchorModeledControlFlowCandidateCount": route_pair_index_source_gap.get(
            "encodedEntryAnchorModeledControlFlowCandidateCount"
        ),
        "routePairIndexSourceEncodedEntryAnchorPromotingCandidateCount": route_pair_index_source_gap.get(
            "encodedEntryAnchorPromotingCandidateCount"
        ),
        "routePairIndexSourceEncodedEntryAnchorClassification": route_pair_index_source_gap.get(
            "encodedEntryAnchorClassification"
        ),
        "routePairIndexSourceEntryPointerOpcode5aFallthroughRefCount": route_pair_index_source_gap.get(
            "entryPointerOpcode5aFallthroughRefCount"
        ),
        "routePairIndexSourceEntryPointerFallthroughNonCodeRefCount": route_pair_index_source_gap.get(
            "entryPointerFallthroughNonCodeRefCount"
        ),
        "routePairIndexSourceNonNegativeEntryPointerPromotingRefCount": route_pair_index_source_gap.get(
            "nonNegativeEntryPointerPromotingRefCount"
        ),
        "routePairIndexSourceNegativeReaderEntryPointerPromotingRefCount": route_pair_index_source_gap.get(
            "negativeReaderEntryPointerPromotingRefCount"
        ),
        "routePairIndexSourceEntryPointerFallthroughHandlerSummaries": (
            route_pair_index_source_gap.get("entryPointerFallthroughHandlerSummaries") or []
        ),
        "routePairIndexSourceDescriptorRefsOnlyTableCells": route_pair_index_source_gap.get(
            "descriptorRefsOnlyTableCells"
        ),
        "routePairIndexSourceChildRefsOnlyDescriptorChildWords": route_pair_index_source_gap.get(
            "childRefsOnlyDescriptorChildWords"
        ),
        "routePairIndexSourceHigherLevelIndexSourceProven": route_pair_index_source_gap.get(
            "higherLevelIndexSourceProven"
        ),
        "routePairIndexSourceProofFound": route_pair_index_source_gap.get("proofFound"),
        "routePairIndexSourceFailedGateIds": (
            route_pair_index_source_gap.get("failedRoutePairIndexSourceGateIds") or []
        ),
        "routePairIndexSourceMissingEvidence": (
            route_pair_index_source_gap.get("missingEvidence") or []
        ),
        "rootTableDirectRefContext": table_direct_ref_context,
        "rootTableWindowDirectRefCount": table_direct_ref_context.get("tableWindowRefCount"),
        "rootTableWindowDirectTextRefCount": table_direct_ref_context.get("tableWindowTextRefCount"),
        "rootTableWindowDirectRefSectionCounts": table_direct_ref_context.get(
            "tableWindowSectionCounts"
        ),
        "rootTableRouteEntryAddressTextRefCount": table_direct_ref_context.get(
            "routeEntryAddressTextRefCount"
        ),
        "rootTableRouteLeafValueTextRefCount": table_direct_ref_context.get(
            "routeLeafValueTextRefCount"
        ),
        "rootTableFrontierLeafValueTextRefCount": table_direct_ref_context.get(
            "frontierLeafValueTextRefCount"
        ),
        "rootTableFrontierReaderValueTextRefCount": table_direct_ref_context.get(
            "frontierReaderValueTextRefCount"
        ),
        "rootTableFrontierReaderValueRefCount": table_direct_ref_context.get(
            "frontierReaderValueRefCount"
        ),
        "wrapperEntryHex": wrapper_descriptor_context.get("wrapperEntryHex"),
        "wrapperDescriptorHex": wrapper_descriptor_context.get("wrapperDescriptorHex"),
        "wrapperChildPointerHex": wrapper_descriptor_context.get("wrapperChildPointerHex"),
        "wrapperRefBeforeCurrentRoot": wrapper_descriptor_context.get("wrapperRefBeforeCurrentRoot"),
        "currentRootReferencesWrapper": wrapper_descriptor_context.get("currentRootReferencesWrapper"),
        "wrapperEntryRefCount": wrapper_descriptor_context.get("wrapperEntryRefCount"),
        "wrapperEntryCurrentRootRangeRefCount": wrapper_descriptor_context.get(
            "wrapperEntryCurrentRootRangeRefCount"
        ),
        "wrapperEntryCurrentRootEntryRunRefCount": wrapper_entry_current_root_entry_run_ref_count,
        "wrapperEntryOpcode5aFallthroughRefCount": wrapper_entry_opcode5a_fallthrough_ref_count,
        "wrapperEntryFallthroughNonCodeRefCount": wrapper_entry_fallthrough_non_code_ref_count,
        "wrapperEntryFallthroughHandlerSummaries": wrapper_entry_fallthrough_handler_summaries,
        "wrapperEntryOnlyRefIsOpcode5aFallthrough": wrapper_entry_only_ref_is_opcode5a_fallthrough,
        "wrapperEntryPromotingRefCount": wrapper_descriptor_context.get("wrapperEntryPromotingRefCount"),
        "wrapperExecutionProofFound": wrapper_execution_proof_found,
        "selectedRootExecutionRefFound": selected_root_execution_ref_found,
        "selectedRootRuntimeSummary": selected_root_runtime_summary(selected_root_execution_gap),
        "routePairEntryExecutionProven": route_pair_entry_execution_proven,
        "proofFound": route_pair_entry_execution_proven,
        "failedRoutePairEntryGateIds": failed_route_pair_entry_gate_ids,
        "missingEvidence": missing_evidence,
        "entrySelectionGapOpen": entry_selection_gap_open,
        "strictHotspotFound": strict_hotspot_found,
        "promotionStatus": promotion_status,
        "routePairEntryRows": route_pair_rows,
        "negativeReaderRows": negative_reader_rows,
        "evidenceRows": evidence_rows,
        "evidenceRefs": EVIDENCE_REFS,
        "evidenceRefCount": len(EVIDENCE_REFS),
        "remainingProofs": [
            "prove selected-root execution reaches selector 2:0 on the normal route path",
            "prove a higher-level selector/table index selects entry 6 or 8",
            "or prove wrapper entry -12 executes into 0x00542ae8 on the normal route path",
            "find a strict map1_01a source coordinate or hotspot linked to map2_02d",
        ],
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Save Selector Route-Pair Entry Execution Gap",
        "",
        summary["conclusion"],
        "",
        f"- route: `{summary['source']} -> {summary['target']}`",
        f"- selector/root: `{summary['selector']}` / `{summary['rootHex']}`",
        f"- root table pointer: `{summary['rootTablePointerHex']}`",
        f"- frontier leaf/reader: `{summary['frontierLeafHex']}` / `{summary['frontierReaderHex']}`",
        f"- route-pair entry indices: `{csv(summary['routePairEntryIndices'])}`",
        f"- corrected reader trace entry indices: `{csv(summary['routePairCorrectedTraceEntryIndices'])}`",
        f"- negative reader entry indices: `{csv(summary['negativeReaderEntryIndices'])}`",
        f"- global current selector route-pair indices: `{csv(summary['globalCurrentSelectorRoutePairIndices'])}`",
        f"- global current frontier leaf only negative: `{summary['globalCurrentFrontierLeafOnlyNegative']}`",
        f"- corrected trace normal-selection gap: `{summary['correctedTraceNormalSelectionGapStatus']}`",
        f"- corrected trace normal-selection gap found: `{summary['correctedTraceNormalSelectionGapFound']}`",
        f"- opcode07 direct entry selection absent: `{summary['opcode07DirectEntrySelectionAbsent']}`",
        f"- opcode08 source/predecessor current root/range producers: `{summary['opcode08SourceOrPredecessorCurrentRootProducerCount']}` / `{summary['opcode08SourceOrPredecessorCurrentRangeProducerCount']}`",
        f"- opcode08 source/predecessor bucket summary: `{summary['opcode08SourcePredecessorBucketSummary']}`",
        f"- opcode08 current selector contrast: `{summary['opcode08CurrentSelectorContrastSummary']}`",
        f"- opcode09 source/predecessor current-range stores: `{summary['opcode09SourceOrPredecessorCurrentRangeStoreCount']}`",
        f"- opcode09 source/predecessor unsupported modes: `{csv(summary['opcode09SourceOrPredecessorUnsupportedModesHex'])}`",
        f"- opcode09 source/predecessor collision rows: `{summary['opcode09SourcePredecessorPointerCollisionSummary']}`",
        f"- source/predecessor current producer count: `{summary['sourceOrPredecessorCurrentProducerCount']}`",
        f"- route-pair index source entry refs/text/promoting: `{summary['routePairIndexSourceEntryPointerRefCount']}` / `{summary['routePairIndexSourceEntryPointerTextRefCount']}` / `{summary['routePairIndexSourceEntryPointerPromotingRefCount']}`",
        f"- route-pair index source encoded raw/branch/modeled/promoting: `{summary['routePairIndexSourceEncodedEntryAnchorRawScalarCandidateCount']}` / `{summary['routePairIndexSourceEncodedEntryAnchorBranchAttachedEncodedFieldCount']}` / `{summary['routePairIndexSourceEncodedEntryAnchorModeledControlFlowCandidateCount']}` / `{summary['routePairIndexSourceEncodedEntryAnchorPromotingCandidateCount']}`",
        f"- route-pair index source encoded classification: `{summary['routePairIndexSourceEncodedEntryAnchorClassification']}`",
        f"- route-pair index source opcode5a fallthrough/non-code refs: `{summary['routePairIndexSourceEntryPointerOpcode5aFallthroughRefCount']}` / `{summary['routePairIndexSourceEntryPointerFallthroughNonCodeRefCount']}`",
        f"- route-pair index source handlers: `{csv(summary['routePairIndexSourceEntryPointerFallthroughHandlerSummaries'])}`",
        f"- route-pair index source proven: `{summary['routePairIndexSourceHigherLevelIndexSourceProven']}`",
        f"- root table window refs/text refs: `{summary['rootTableWindowDirectRefCount']}` / `{summary['rootTableWindowDirectTextRefCount']}`",
        f"- root table route entry/leaf/frontier leaf/reader text refs: `{summary['rootTableRouteEntryAddressTextRefCount']}` / `{summary['rootTableRouteLeafValueTextRefCount']}` / `{summary['rootTableFrontierLeafValueTextRefCount']}` / `{summary['rootTableFrontierReaderValueTextRefCount']}`",
        f"- root table frontier reader direct refs: `{summary['rootTableFrontierReaderValueRefCount']}`",
        f"- wrapper entry current-root entry-run refs: `{summary['wrapperEntryCurrentRootEntryRunRefCount']}`",
        f"- wrapper entry opcode5a fallthrough refs: `{summary['wrapperEntryOpcode5aFallthroughRefCount']}`",
        f"- wrapper entry fallthrough non-code refs: `{summary['wrapperEntryFallthroughNonCodeRefCount']}`",
        f"- wrapper entry fallthrough handlers: `{csv(summary['wrapperEntryFallthroughHandlerSummaries'])}`",
        f"- wrapper execution proof found: `{summary['wrapperExecutionProofFound']}`",
        f"- selected-root execution ref found: `{summary['selectedRootExecutionRefFound']}`",
        f"- route-pair entry execution proven: `{summary['routePairEntryExecutionProven']}`",
        f"- proof found: `{summary['proofFound']}`",
        f"- failed route-pair entry gates: `{csv(summary.get('failedRoutePairEntryGateIds'))}`",
        f"- missing evidence count: `{len(summary.get('missingEvidence') or [])}`",
        f"- strict hotspot found: `{summary['strictHotspotFound']}`",
        f"- evidence refs: `{summary['evidenceRefCount']}`",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        "## Missing Evidence",
        "",
        *[f"- {item}" for item in summary.get("missingEvidence") or []],
        "",
        "## Route-Pair Entries",
        "",
        "| index | entry | descriptor | child | maps | corrected reader |",
        "| ---: | --- | --- | --- | --- | --- |",
    ]
    for row in summary["routePairEntryRows"]:
        maps = ",".join(row.get("descriptorFieldMaps") or []) or "-"
        lines.append(
            f"| {row.get('rootRelativeIndex')} | `{row.get('entryVaHex')}` | "
            f"`{row.get('descriptorHex')}` | `{row.get('childPointerHex')}` | "
            f"{maps} | {row.get('correctedDescriptorTraceContainsFrontierReader')} |"
        )
    lines.extend(["", "## Evidence", "", "| kind | status | detail |", "| --- | --- | --- |"])
    for row in summary["evidenceRows"]:
        lines.append(f"| {row['kind']} | {row['status']} | {row['detail']} |")
    lines.extend(["", "## Evidence Refs", ""])
    for ref in summary.get("evidenceRefs") or []:
        fields = ", ".join(ref.get("fields") or [])
        lines.append(f"- `{ref['path']}`: {fields}")
    lines.extend([
        "",
        "## Opcode 0x08 Selector Buckets",
        "",
        "| selector | role | range | activations | current root/range | own | script | unreadable |",
        "| --- | --- | --- | ---: | --- | ---: | ---: | ---: |",
    ])
    for row in summary["opcode08SelectorBucketRows"]:
        lines.append(
            f"| `{row.get('selector')}` | {row.get('role')} | `{row.get('rangeHex')}` | "
            f"{row.get('activationCount')} | {row.get('nearestCurrentRootProducerCount')}/"
            f"{row.get('nearestCurrentRangeProducerCount')} | {row.get('nearestOwnRangeProducerCount')} | "
            f"{row.get('nearestScriptScalarProducerCount')} | {row.get('nearestUnreadableProducerCount')} |"
        )
    lines.extend([
        "",
        "## Opcode 0x09 Pointer Collisions",
        "",
        "| selector | va | value | mode | section | returns without store | classification |",
        "| --- | --- | --- | --- | --- | --- | --- |",
    ])
    for row in summary["opcode09SourcePredecessorPointerCollisionRows"]:
        lines.append(
            f"| `{row.get('selector')}` | `{row.get('vaHex')}` | `{row.get('valueHex')}` | "
            f"`{row.get('modeHex')}` | {row.get('valueSection') or '-'} | "
            f"{row.get('unsupportedModeReturnsWithoutStore')} | {row.get('classification')} |"
        )
    lines.extend(["", "## Remaining Proofs", ""])
    lines.extend(f"- {item}" for item in summary["remainingProofs"])
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    entry_rows = "\n".join(
        "<tr>"
        f"<td>{row.get('rootRelativeIndex')}</td>"
        f"<td><code>{html.escape(str(row.get('entryVaHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('descriptorHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('childPointerHex')))}</code></td>"
        f"<td>{html.escape(','.join(row.get('descriptorFieldMaps') or []) or '-')}</td>"
        f"<td>{row.get('correctedDescriptorTraceContainsFrontierReader')}</td>"
        "</tr>"
        for row in summary["routePairEntryRows"]
    )
    evidence_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['kind'])}</td>"
        f"<td>{html.escape(row['status'])}</td>"
        f"<td>{html.escape(row['detail'])}</td>"
        "</tr>"
        for row in summary["evidenceRows"]
    )
    opcode08_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(row.get('selector')))}</code></td>"
        f"<td>{html.escape(str(row.get('role')))}</td>"
        f"<td><code>{html.escape(str(row.get('rangeHex')))}</code></td>"
        f"<td>{row.get('activationCount')}</td>"
        f"<td>{row.get('nearestCurrentRootProducerCount')}/"
        f"{row.get('nearestCurrentRangeProducerCount')}</td>"
        f"<td>{row.get('nearestOwnRangeProducerCount')}</td>"
        f"<td>{row.get('nearestScriptScalarProducerCount')}</td>"
        f"<td>{row.get('nearestUnreadableProducerCount')}</td>"
        "</tr>"
        for row in summary["opcode08SelectorBucketRows"]
    )
    opcode09_collision_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(row.get('selector')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('vaHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('valueHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('modeHex')))}</code></td>"
        f"<td>{html.escape(str(row.get('valueSection') or '-'))}</td>"
        f"<td>{row.get('unsupportedModeReturnsWithoutStore')}</td>"
        f"<td>{html.escape(str(row.get('classification')))}</td>"
        "</tr>"
        for row in summary["opcode09SourcePredecessorPointerCollisionRows"]
    )
    proof_items = "\n".join(f"<li>{html.escape(item)}</li>" for item in summary["remainingProofs"])
    missing_items = "\n".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or []
    )
    evidence_ref_items = "\n".join(
        "<li>"
        f"<code>{html.escape(ref.get('path') or '')}</code>: "
        f"{html.escape(', '.join(ref.get('fields') or []))}"
        "</li>"
        for ref in summary.get("evidenceRefs") or []
    )
    return "\n".join(
        [
            "<!doctype html>",
            '<html lang="en">',
            "<head>",
            '  <meta charset="utf-8">',
            "  <title>Save Selector Route-Pair Entry Execution Gap</title>",
            "  <style>body{font-family:system-ui,sans-serif;margin:24px;line-height:1.45;max-width:1200px}table{border-collapse:collapse;width:100%;margin:16px 0}td,th{border:1px solid #ddd;padding:6px 8px;text-align:left;vertical-align:top}th{background:#f5f5f5}code{white-space:nowrap}</style>",
            "</head>",
            "<body>",
            "  <h1>Save Selector Route-Pair Entry Execution Gap</h1>",
            f"  <p>{html.escape(summary['conclusion'])}</p>",
            (
                "  <p><b>Route:</b> "
                f"<code>{html.escape(summary['source'])} -&gt; {html.escape(summary['target'])}</code>; "
                f"selector <code>{html.escape(str(summary['selector']))}</code>; "
                f"root <code>{html.escape(str(summary['rootHex']))}</code>; "
                f"promotion status <code>{html.escape(str(summary['promotionStatus']))}</code>.</p>"
            ),
            (
                "  <p>route-pair entry execution proven: "
                f"{summary['routePairEntryExecutionProven']}; "
                "selected-root execution ref found: "
                f"{summary['selectedRootExecutionRefFound']}; "
                "strict hotspot found: "
                f"{summary['strictHotspotFound']}; "
                f"proofFound={summary['proofFound']}; "
                "failedRoutePairEntryGates="
                f"<code>{html.escape(csv(summary.get('failedRoutePairEntryGateIds')))}</code>; "
                f"missingEvidenceCount={len(summary.get('missingEvidence') or [])}.</p>"
            ),
            (
                "  <p><b>Global leaf table:</b> "
                "global current selector route-pair indices "
                f"<code>{html.escape(csv(summary['globalCurrentSelectorRoutePairIndices']))}</code>; "
                "global current frontier leaf only negative: "
                f"{summary['globalCurrentFrontierLeafOnlyNegative']}; "
                "route-pair index source entry refs/text/promoting: "
                f"{summary['routePairIndexSourceEntryPointerRefCount']}/"
                f"{summary['routePairIndexSourceEntryPointerTextRefCount']}/"
                f"{summary['routePairIndexSourceEntryPointerPromotingRefCount']}; "
                "route-pair index source encoded raw/branch/modeled/promoting: "
                f"{summary['routePairIndexSourceEncodedEntryAnchorRawScalarCandidateCount']}/"
                f"{summary['routePairIndexSourceEncodedEntryAnchorBranchAttachedEncodedFieldCount']}/"
                f"{summary['routePairIndexSourceEncodedEntryAnchorModeledControlFlowCandidateCount']}/"
                f"{summary['routePairIndexSourceEncodedEntryAnchorPromotingCandidateCount']}; "
                "route-pair index source encoded classification: "
                f"{summary['routePairIndexSourceEncodedEntryAnchorClassification']}; "
                "root table window refs/text refs: "
                f"{summary['rootTableWindowDirectRefCount']}/"
                f"{summary['rootTableWindowDirectTextRefCount']}; "
                "route entry/leaf/frontier leaf/reader text refs: "
                f"{summary['rootTableRouteEntryAddressTextRefCount']}/"
                f"{summary['rootTableRouteLeafValueTextRefCount']}/"
                f"{summary['rootTableFrontierLeafValueTextRefCount']}/"
                f"{summary['rootTableFrontierReaderValueTextRefCount']}; "
                "wrapper entry opcode5a fallthrough refs: "
                f"{summary['wrapperEntryOpcode5aFallthroughRefCount']}.</p>"
            ),
            (
                "  <p><b>Opcode 0x08/0x09 current producer contrast:</b> "
                f"source/predecessor buckets <code>{html.escape(summary['opcode08SourcePredecessorBucketSummary'])}</code>; "
                f"current selector contrast <code>{html.escape(summary['opcode08CurrentSelectorContrastSummary'])}</code>; "
                f"opcode09 collision rows <code>{html.escape(summary['opcode09SourcePredecessorPointerCollisionSummary'])}</code>.</p>"
            ),
            (
                "  <p><b>corrected trace normal-selection gap:</b> "
                f"<code>{html.escape(str(summary['correctedTraceNormalSelectionGapStatus']))}</code>; "
                "corrected trace reaches the reader, but non-negative selection is "
                f"{summary['frontierReaderSelectableByNonNegativeIndex']} and the reader-bearing leaf remains "
                f"negative-only {summary['globalCurrentFrontierLeafOnlyNegative']}.</p>"
            ),
            f"  <p><b>Evidence refs:</b> {summary['evidenceRefCount']}.</p>",
            "  <h2>Missing Evidence</h2>",
            f"  <ul>{missing_items}</ul>",
            "  <h2>Route-Pair Entries</h2>",
            "  <table><thead><tr><th>index</th><th>entry</th><th>descriptor</th><th>child</th><th>maps</th><th>corrected reader</th></tr></thead><tbody>",
            entry_rows,
            "  </tbody></table>",
            "  <h2>Evidence</h2>",
            f"  <table><thead><tr><th>kind</th><th>status</th><th>detail</th></tr></thead><tbody>{evidence_rows}</tbody></table>",
            "  <h2>Evidence Refs</h2>",
            f"  <ul>{evidence_ref_items}</ul>",
            "  <h2>Opcode 0x08 Selector Buckets</h2>",
            "  <table><thead><tr><th>selector</th><th>role</th><th>range</th><th>activations</th><th>current root/range</th><th>own</th><th>script</th><th>unreadable</th></tr></thead><tbody>",
            opcode08_rows,
            "  </tbody></table>",
            "  <h2>Opcode 0x09 Pointer Collisions</h2>",
            "  <table><thead><tr><th>selector</th><th>va</th><th>value</th><th>mode</th><th>section</th><th>returns without store</th><th>classification</th></tr></thead><tbody>",
            opcode09_collision_rows,
            "  </tbody></table>",
            "  <h2>Remaining Proofs</h2>",
            f"  <ul>{proof_items}</ul>",
            "</body>",
            "</html>",
            "",
        ]
    )


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


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.out_dir / "save_selector_leaf_index_space.json", {}),
        load_json(args.out_dir / "save_selector_leaf_table_global_context.json", {}),
        load_json(args.out_dir / "save_selector_opcode08_activation_windows.json", {}),
        load_json(args.out_dir / "save_selector_opcode07_indexed_pointers.json", {}),
        load_json(args.out_dir / "save_selector_opcode09_pointer_collisions.json", {}),
        load_json(args.out_dir / "save_selector_wrapper_descriptor_context.json", {}),
        load_json(args.out_dir / "save_selector_selected_root_execution_gap.json", {}),
        load_json(args.out_dir / "save_selector_current_root_frontier_paths.json", {}),
        load_json(args.out_dir / "save_selector_route_pair_index_source_gap.json", {}),
        load_json(args.out_dir / "save_selector_leaf_table_context.json", {}),
    )
    write_outputs(summary, args.out_dir)
    print(
        "wrote route-pair entry execution gap -> "
        f"{args.out_dir / 'save_selector_route_pair_entry_execution_gap.html'}"
    )


if __name__ == "__main__":
    main()
