#!/usr/bin/env python3
"""Consolidate current-selector leaf selection and wrapper execution gaps."""
from __future__ import annotations

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


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

EVIDENCE_REFS = [
    {
        "path": "out/save_selector_leaf_table_context.json",
        "fields": [
            "selector",
            "rootHex",
            "rootTablePointerHex",
            "frontierLeafRefIsDirectRootTableEntry",
            "runtimeSelectionProven",
            "promotionStatus",
        ],
    },
    {
        "path": "out/save_selector_leaf_table_global_context.json",
        "fields": [
            "selectorTableCount",
            "fieldEntryRowCount",
            "currentSelectorRoutePairIndices",
            "currentFrontierLeafOnlyNegative",
        ],
    },
    {
        "path": "out/save_selector_wrapper_descriptor_context.json",
        "fields": [
            "wrapperDescriptorHex",
            "wrapperEntryHex",
            "wrapperChildPointerHex",
            "wrapperRefBeforeCurrentRoot",
            "currentRootReferencesWrapper",
            "wrapperEntryPromotingRefCount",
        ],
    },
    {
        "path": "out/save_selector_route_pair_descriptor_context.json",
        "fields": [
            "currentRoutePairDescriptorCount",
            "currentRoutePairDescriptorIndices",
            "currentRoutePairCorrectedTraceReachesReaderCount",
            "readerBearingCurrentEntryCount",
            "readerBearingNegativeEntryCount",
        ],
    },
    {
        "path": "out/save_selector_opcode07_indexed_pointers.json",
        "fields": [
            "opcode07IndexMode",
            "rowCount",
            "selectedWrapperEntrySlotCount",
            "selectedLeafTableWindowSlotCount",
            "selectedCurrentRootEntrySlotCount",
            "selectedNegativeRootEntrySlotCount",
            "directFrontierTargetCount",
        ],
    },
    {
        "path": "out/save_selector_opcode08_activation_windows.json",
        "fields": [
            "sourceOrPredecessorOpcode08ActivatorCount",
            "sourceOrPredecessorCurrentRootProducerCount",
            "sourceOrPredecessorCurrentRangeProducerCount",
            "currentInternalCurrentRangeProducerCount",
        ],
    },
    {
        "path": "out/save_selector_opcode09_pointer_collisions.json",
        "fields": [
            "sourceOrPredecessorOpcode09RowCount",
            "sourceOrPredecessorSupportedOpcode09RowCount",
            "sourceOrPredecessorUnsupportedModeOpcode09RowCount",
            "sourceOrPredecessorCurrentRangeStoreCount",
        ],
    },
    {
        "path": "out/save_selector_selected_root_execution_gap.json",
        "fields": [
            "selectedRootExecutionRefFound",
            "runtimeSelectionProven",
            "diagnosticExclusionGate",
            "evidenceRefs",
            "evidenceRefCount",
        ],
    },
    {
        "path": "out/save_selector_current_root_frontier_paths.json",
        "fields": [
            "strictHotspotFound",
            "frontierClusterClass",
            "frontierClusterEventCount",
            "frontierClusterSelectorRefCount",
        ],
    },
    {
        "path": "out/save_selector_merge_execution_gap.json",
        "fields": [
            "selectorMergeExecutionProofFound",
            "selectorMergeGapOpen",
            "promotionStatus",
        ],
    },
    {
        "path": "out/save_selector_route_pair_entry_execution_gap.json",
        "fields": [
            "rootTableDirectRefContext",
            "routePairEntryExecutionProven",
            "correctedTraceNormalSelectionGapFound",
            "remainingProofs",
        ],
    },
]

WRAPPER_MISSING_EVIDENCE_BY_GATE = {
    "selected-root-execution": (
        "selected-root execution reaching current selector 2:0 on the normal route path"
    ),
    "current-leaf-selection": (
        "higher-level table/index path selecting current entries 6/8 or negative entry -12"
    ),
    "wrapper-execution": (
        "normal-route wrapper 0x00542a04 execution into frontier leaf 0x00542ae8"
    ),
    "current-selector-leaf-execution": (
        "complete current selector leaf execution proof tying selected root, leaf selection, "
        "and wrapper/reader trace"
    ),
    "strict-hotspot": "strict map1_01a source coordinate or hotspot linked to map2_02d",
}


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


def build_summary(
    leaf_table_context: dict,
    leaf_table_global_context: dict,
    wrapper_descriptor_context: dict,
    route_pair_descriptor_context: dict,
    opcode07_indexed_pointers: dict,
    opcode08_activation_windows: dict,
    opcode09_pointer_collisions: dict,
    selected_root_execution_gap: dict,
    current_root_frontier_paths: dict,
    merge_execution_gap: dict,
    route_pair_entry_execution_gap: dict | None = None,
) -> dict:
    route_pair_entry_execution_gap = route_pair_entry_execution_gap or {}
    selector = leaf_table_context.get("selector") or route_pair_descriptor_context.get("selector") or "2:0"
    root_hex = leaf_table_context.get("rootHex") or route_pair_descriptor_context.get("rootHex")
    root_table_pointer = leaf_table_context.get("rootTablePointerHex") or route_pair_descriptor_context.get(
        "rootTablePointerHex"
    )
    frontier_leaf = leaf_table_context.get("frontierLeafHex") or wrapper_descriptor_context.get("frontierLeafHex")
    frontier_reader = leaf_table_context.get("frontierReaderHex") or wrapper_descriptor_context.get(
        "frontierReaderHex"
    )
    wrapper_descriptor = wrapper_descriptor_context.get("wrapperDescriptorHex")
    wrapper_entry = wrapper_descriptor_context.get("wrapperEntryHex")
    wrapper_child = wrapper_descriptor_context.get("wrapperChildPointerHex")
    inside_root_rows = [
        row
        for row in leaf_table_context.get("tableRows") or []
        if row.get("insideRootTableWindow") is True
    ]
    current_route_pair_descriptor_count = route_pair_descriptor_context.get("currentRoutePairDescriptorCount") or 0
    corrected_reader_count = (
        route_pair_descriptor_context.get("currentRoutePairCorrectedTraceReachesReaderCount")
        or route_pair_descriptor_context.get("currentRoutePairTraceReachesReaderCount")
        or 0
    )
    route_pair_reader_trace_grounded = (
        current_route_pair_descriptor_count > 0
        and corrected_reader_count == current_route_pair_descriptor_count
    )
    opcode07_selection_absent = (
        opcode07_indexed_pointers.get("selectedWrapperEntrySlotCount") == 0
        and opcode07_indexed_pointers.get("selectedLeafTableWindowSlotCount") == 0
        and opcode07_indexed_pointers.get("selectedCurrentRootEntrySlotCount") == 0
        and opcode07_indexed_pointers.get("selectedNegativeRootEntrySlotCount") == 0
        and opcode07_indexed_pointers.get("directFrontierTargetCount") == 0
    )
    wrapper_before_current_root = wrapper_descriptor_context.get("wrapperRefBeforeCurrentRoot") is True
    wrapper_not_in_current_root = wrapper_descriptor_context.get("currentRootReferencesWrapper") is False
    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
    )
    wrapper_non_promoting_refs = (
        wrapper_descriptor_context.get("wrapperEntryPromotingRefCount") == 0
        and wrapper_descriptor_context.get("wrapperEntryRefCount") == 1
        and wrapper_before_current_root
    )
    frontier_leaf_direct_current_root_ref = (
        wrapper_descriptor_context.get("frontierLeafDirectCurrentRootRef") is True
        or leaf_table_context.get("frontierLeafRefIsDirectRootTableEntry") is True
    )
    reader_negative_only = (
        route_pair_descriptor_context.get("readerBearingCurrentEntryCount") == 0
        and route_pair_descriptor_context.get("readerBearingNegativeEntryCount") == 1
    )
    runtime_selection_proven = (
        leaf_table_context.get("runtimeSelectionProven") is True
        or route_pair_descriptor_context.get("runtimeSelectionProven") is True
        or selected_root_execution_gap.get("selectedRootExecutionRefFound") is True
    )
    wrapper_execution_proof_found = (
        wrapper_descriptor_context.get("wrapperEntryPromotingRefCount", 0) > 0
        or wrapper_descriptor_context.get("currentRootReferencesWrapper") is True
        or (not opcode07_selection_absent and frontier_leaf_direct_current_root_ref)
    )
    current_leaf_selection_proof_found = (
        runtime_selection_proven
        or not opcode07_selection_absent
        or frontier_leaf_direct_current_root_ref
    )
    selected_root_execution_ref_found = selected_root_execution_gap.get("selectedRootExecutionRefFound") is True
    current_selector_leaf_execution_proof_found = (
        selected_root_execution_ref_found
        and current_leaf_selection_proof_found
        and (wrapper_execution_proof_found or route_pair_reader_trace_grounded)
    )
    strict_hotspot_found = (
        leaf_table_context.get("strictHotspotFound") is True
        or route_pair_descriptor_context.get("strictHotspotFound") is True
        or current_root_frontier_paths.get("strictHotspotFound") is True
    )
    selector_merge_execution_proof_found = merge_execution_gap.get("selectorMergeExecutionProofFound") is True
    diagnostic_exclusion_gate = selected_root_execution_gap.get("diagnosticExclusionGate") or {}
    constructed_diagnostic_excluded = (
        diagnostic_exclusion_gate.get("excludedFromSelectedRootExecutionProof") is True
    )
    constructed_diagnostic_status = (
        "diagnostic-only-not-reproduced"
        if constructed_diagnostic_excluded
        and (diagnostic_exclusion_gate.get("leftStabilityRouteSelectorHitCount") or 0) > 0
        and diagnostic_exclusion_gate.get("leftStabilityRouteHitReproducibility") == "not-reproduced"
        and (diagnostic_exclusion_gate.get("leftStabilityRecheckRouteSelectorHitCount") or 0) == 0
        and (diagnostic_exclusion_gate.get("leftActiveOrderRecheckRouteSelectorHitCount") or 0) == 0
        else "diagnostic-only"
        if constructed_diagnostic_excluded
        else "not-available"
    )
    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
    )
    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
    )
    source_or_predecessor_current_producer_count = (
        opcode08_source_current_root_count
        + opcode08_source_current_range_count
        + opcode09_source_current_range_count
    )
    root_table_direct_ref_context = route_pair_entry_execution_gap.get("rootTableDirectRefContext") or {}
    root_table_direct_ref_status = root_table_direct_ref_context.get("status") or "unknown"
    corrected_trace_normal_selection_gap_found = (
        route_pair_reader_trace_grounded
        and reader_negative_only
        and global_current_frontier_leaf_only_negative
        and opcode07_selection_absent
        and source_or_predecessor_current_producer_count == 0
        and not runtime_selection_proven
        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"
    )
    promotion_status = (
        "ready-for-review"
        if current_selector_leaf_execution_proof_found
        and strict_hotspot_found
        and selector_merge_execution_proof_found
        else "blocked"
    )
    failed_wrapper_gate_ids = []
    if not selected_root_execution_ref_found:
        failed_wrapper_gate_ids.append("selected-root-execution")
    if not current_leaf_selection_proof_found:
        failed_wrapper_gate_ids.append("current-leaf-selection")
    if not wrapper_execution_proof_found:
        failed_wrapper_gate_ids.append("wrapper-execution")
    if not current_selector_leaf_execution_proof_found:
        failed_wrapper_gate_ids.append("current-selector-leaf-execution")
    if not strict_hotspot_found:
        failed_wrapper_gate_ids.append("strict-hotspot")
    missing_evidence = [
        WRAPPER_MISSING_EVIDENCE_BY_GATE.get(gate_id, gate_id)
        for gate_id in failed_wrapper_gate_ids
    ]
    proof_found = not failed_wrapper_gate_ids
    evidence = [
        {
            "kind": "current-root-table-window",
            "status": "route-pair-descriptors-present"
            if current_route_pair_descriptor_count
            else "route-pair-descriptors-missing",
            "detail": (
                f"root={root_hex}; table={root_table_pointer}; "
                f"insideRootRows={len(inside_root_rows)}; "
                f"routePairIndices={csv(route_pair_descriptor_context.get('currentRoutePairDescriptorIndices'))}"
            ),
        },
        {
            "kind": "negative-wrapper-entry",
            "status": "outside-current-root-run" if wrapper_before_current_root else "inside-current-root-run",
            "detail": (
                f"wrapperEntry={wrapper_entry}; wrapper={wrapper_descriptor}; "
                f"child={wrapper_child}; childIsFrontier={wrapper_descriptor_context.get('wrapperChildIsFrontierLeaf')}; "
                f"frontierLeaf={frontier_leaf}; reader={frontier_reader}"
            ),
        },
        {
            "kind": "wrapper-reference-context",
            "status": "non-promoting" if wrapper_non_promoting_refs and wrapper_not_in_current_root else "open",
            "detail": (
                f"wrapperEntryRefs={wrapper_descriptor_context.get('wrapperEntryRefCount')}; "
                f"currentRootRangeRefs={wrapper_descriptor_context.get('wrapperEntryCurrentRootRangeRefCount')}; "
                f"currentRootEntryRunRefs={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 '-'}; "
                f"promotingRefs={wrapper_descriptor_context.get('wrapperEntryPromotingRefCount')}; "
                f"currentRootReferencesWrapper={wrapper_descriptor_context.get('currentRootReferencesWrapper')}"
            ),
        },
        {
            "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": root_table_direct_ref_status,
            "detail": (
                f"tableWindow={root_table_direct_ref_context.get('tableWindowHex')}; "
                f"tableRefs={root_table_direct_ref_context.get('tableWindowRefCount')}/"
                f"{root_table_direct_ref_context.get('tableWindowTextRefCount')}; "
                f"sections={root_table_direct_ref_context.get('tableWindowSectionCounts')}; "
                f"routeEntryTextRefs={root_table_direct_ref_context.get('routeEntryAddressTextRefCount')}; "
                f"routeLeafTextRefs={root_table_direct_ref_context.get('routeLeafValueTextRefCount')}; "
                f"frontierLeafTextRefs={root_table_direct_ref_context.get('frontierLeafValueTextRefCount')}; "
                f"frontierReaderTextRefs={root_table_direct_ref_context.get('frontierReaderValueTextRefCount')}; "
                f"frontierReaderRefs={root_table_direct_ref_context.get('frontierReaderValueRefCount')}"
            ),
        },
        {
            "kind": "route-pair-reader-trace",
            "status": "corrected-trace-only" if route_pair_reader_trace_grounded else "not-grounded",
            "detail": (
                f"routePairDescriptors={current_route_pair_descriptor_count}; "
                f"correctedReaderHits={corrected_reader_count}; "
                f"geometryExitHits={route_pair_descriptor_context.get('currentRoutePairGeometryExitHitCount')}; "
                f"readerNegativeOnly={reader_negative_only}"
            ),
        },
        {
            "kind": "opcode07-leaf-selection",
            "status": "absent" if opcode07_selection_absent else "present",
            "detail": (
                f"rowCount={opcode07_indexed_pointers.get('rowCount')}; "
                f"indexMode={opcode07_indexed_pointers.get('opcode07IndexMode')}; "
                f"selectedWrapper={opcode07_indexed_pointers.get('selectedWrapperEntrySlotCount')}; "
                f"selectedLeafWindow={opcode07_indexed_pointers.get('selectedLeafTableWindowSlotCount')}; "
                f"selectedNegative={opcode07_indexed_pointers.get('selectedNegativeRootEntrySlotCount')}; "
                f"directFrontier={opcode07_indexed_pointers.get('directFrontierTargetCount')}"
            ),
        },
        {
            "kind": "opcode08-source-predecessor-activation",
            "status": "current-producer-absent"
            if not (opcode08_source_current_root_count or opcode08_source_current_range_count)
            else "current-producer-present",
            "detail": (
                f"activators={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')}"
            ),
        },
        {
            "kind": "opcode09-source-predecessor-store",
            "status": "current-store-absent"
            if opcode09_source_current_range_count == 0
            else "current-store-present",
            "detail": (
                f"rows={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"currentRangeStores={opcode09_source_current_range_count}; "
                f"sourcePredCurrentProducers={source_or_predecessor_current_producer_count}"
            ),
        },
        {
            "kind": "corrected-trace-normal-selection-gap",
            "status": corrected_trace_normal_selection_gap_status,
            "detail": (
                f"routePairReaderTraceGrounded={route_pair_reader_trace_grounded}; "
                f"readerNegativeOnly={reader_negative_only}; "
                f"frontierLeafNegativeOnly={global_current_frontier_leaf_only_negative}; "
                f"opcode07SelectionAbsent={opcode07_selection_absent}; "
                f"sourcePredCurrentProducers={source_or_predecessor_current_producer_count}; "
                f"runtimeSelection={runtime_selection_proven}; "
                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 "proven",
            "detail": (
                f"selectedRootExecutionRefFound={selected_root_execution_ref_found}; "
                f"runtimeSelectionProven={runtime_selection_proven}; "
                f"selectedPointerGlobal={selected_root_execution_gap.get('selectedPointerGlobalHex')}; "
                f"currentRoot={selected_root_execution_gap.get('currentRootHex')}"
            ),
        },
        {
            "kind": "constructed-diagnostic-recheck",
            "status": constructed_diagnostic_status,
            "detail": (
                f"runtimePoll={diagnostic_exclusion_gate.get('runtimePollSampleCount')} "
                f"observed={csv(diagnostic_exclusion_gate.get('runtimePollObservedSelectors'))} "
                f"route={diagnostic_exclusion_gate.get('observedCurrentThenFollowupInDiagnosticPoll')}; "
                f"leftStability={diagnostic_exclusion_gate.get('leftStabilitySampleCount')} "
                f"routeHits={diagnostic_exclusion_gate.get('leftStabilityRouteSelectorHitCount')} "
                f"repro={diagnostic_exclusion_gate.get('leftStabilityRouteHitReproducibility')}; "
                f"leftRecheck={diagnostic_exclusion_gate.get('leftStabilityRecheckSampleCount')} "
                f"routeHits={diagnostic_exclusion_gate.get('leftStabilityRecheckRouteSelectorHitCount')}; "
                f"leftActiveOrder={diagnostic_exclusion_gate.get('leftActiveOrderRecheckSampleCount')} "
                f"routeHits={diagnostic_exclusion_gate.get('leftActiveOrderRecheckRouteSelectorHitCount')} "
                f"activeOrderCount={diagnostic_exclusion_gate.get('leftActiveOrderRecheckActiveOrderCountValues')}; "
                f"excluded={constructed_diagnostic_excluded}"
            ),
        },
        {
            "kind": "strict-hotspot",
            "status": "missing" if not strict_hotspot_found else "found",
            "detail": (
                f"strictHotspotFound={strict_hotspot_found}; "
                f"frontierClusterClass={current_root_frontier_paths.get('frontierClusterClass')}; "
                f"frontierClusterEventCount={current_root_frontier_paths.get('frontierClusterEventCount')}; "
                f"frontierClusterSelectorRefCount={current_root_frontier_paths.get('frontierClusterSelectorRefCount')}"
            ),
        },
    ]
    conclusion = (
        "Current selector 2:0 contains route-pair descriptors and corrected traces from entries 6 and 8 reach "
        "the frontier reader, but this is still table/control-flow shape rather than execution proof. The "
        "reader-bearing wrapper lives at negative entry -12 before the current root table pointer, opcode 0x07 "
        "does not select the wrapper, leaf table window, negative entry, frontier leaf, or reader, source/"
        "predecessor opcode 0x08/0x09 rows do not produce the current selector root/range, and no runtime "
        "selected-root proof or strict source hotspot is present. The global leaf-table scan also keeps the "
        "frontier reader-bearing leaf negative-only, so entries 6 and 8 remain corrected-trace candidates rather "
        "than normal-selection proof; this contradiction is tracked as a separate corrected-trace normal-selection "
        "gap. The constructed selector 2:0 diagnostic is also excluded from wrapper "
        "proof because its left-route hit is not reproduced and the active-order recheck stays at a zero count."
    )
    return {
        "source": current_root_frontier_paths.get("source") or "map1_01a",
        "target": current_root_frontier_paths.get("target") or "map2_02d",
        "selector": selector,
        "rootHex": root_hex,
        "rootTablePointerHex": root_table_pointer,
        "tableWindowHex": leaf_table_context.get("tableWindowHex"),
        "currentRootEntryRunHex": wrapper_descriptor_context.get("currentRootEntryRunHex"),
        "insideCurrentRootEntryCount": len(inside_root_rows),
        "frontierLeafHex": frontier_leaf,
        "frontierReaderHex": frontier_reader,
        "wrapperDescriptorHex": wrapper_descriptor,
        "wrapperEntryHex": wrapper_entry,
        "wrapperChildPointerHex": wrapper_child,
        "wrapperChildIsFrontierLeaf": wrapper_descriptor_context.get("wrapperChildIsFrontierLeaf"),
        "wrapperRefBeforeCurrentRoot": wrapper_before_current_root,
        "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"),
        "frontierLeafDirectCurrentRootRef": frontier_leaf_direct_current_root_ref,
        "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,
        "rootTableDirectRefContext": root_table_direct_ref_context,
        "rootTableDirectRefStatus": root_table_direct_ref_status,
        "rootTableWindowDirectRefCount": root_table_direct_ref_context.get("tableWindowRefCount"),
        "rootTableWindowDirectTextRefCount": root_table_direct_ref_context.get("tableWindowTextRefCount"),
        "rootTableWindowDirectRefSectionCounts": root_table_direct_ref_context.get(
            "tableWindowSectionCounts"
        )
        or {},
        "rootTableRouteEntryAddressTextRefCount": root_table_direct_ref_context.get(
            "routeEntryAddressTextRefCount"
        ),
        "rootTableRouteLeafValueTextRefCount": root_table_direct_ref_context.get(
            "routeLeafValueTextRefCount"
        ),
        "rootTableFrontierLeafValueTextRefCount": root_table_direct_ref_context.get(
            "frontierLeafValueTextRefCount"
        ),
        "rootTableFrontierReaderValueTextRefCount": root_table_direct_ref_context.get(
            "frontierReaderValueTextRefCount"
        ),
        "rootTableFrontierReaderValueRefCount": root_table_direct_ref_context.get(
            "frontierReaderValueRefCount"
        ),
        "currentRoutePairDescriptorCount": current_route_pair_descriptor_count,
        "currentRoutePairDescriptorIndices": route_pair_descriptor_context.get(
            "currentRoutePairDescriptorIndices"
        )
        or [],
        "currentRoutePairCorrectedTraceReachesReaderCount": corrected_reader_count,
        "routePairReaderTraceGrounded": route_pair_reader_trace_grounded,
        "currentRoutePairGeometryExitHitCount": route_pair_descriptor_context.get(
            "currentRoutePairGeometryExitHitCount"
        ),
        "readerBearingCurrentEntryCount": route_pair_descriptor_context.get("readerBearingCurrentEntryCount"),
        "readerBearingNegativeEntryCount": route_pair_descriptor_context.get("readerBearingNegativeEntryCount"),
        "readerBearingNegativeIndices": route_pair_descriptor_context.get("readerBearingNegativeIndices") or [],
        "readerBearingNegativeOnly": reader_negative_only,
        "opcode07IndexMode": opcode07_indexed_pointers.get("opcode07IndexMode"),
        "opcode07RowCount": opcode07_indexed_pointers.get("rowCount"),
        "selectedWrapperEntrySlotCount": opcode07_indexed_pointers.get("selectedWrapperEntrySlotCount"),
        "selectedLeafTableWindowSlotCount": opcode07_indexed_pointers.get("selectedLeafTableWindowSlotCount"),
        "selectedCurrentRootEntrySlotCount": opcode07_indexed_pointers.get("selectedCurrentRootEntrySlotCount"),
        "selectedNegativeRootEntrySlotCount": opcode07_indexed_pointers.get("selectedNegativeRootEntrySlotCount"),
        "directFrontierTargetCount": opcode07_indexed_pointers.get("directFrontierTargetCount"),
        "opcode07LeafSelectionAbsent": opcode07_selection_absent,
        "opcode08SourceOrPredecessorActivatorCount": opcode08_activation_windows.get(
            "sourceOrPredecessorOpcode08ActivatorCount"
        ),
        "opcode08SourceOrPredecessorCurrentRootProducerCount": opcode08_source_current_root_count,
        "opcode08SourceOrPredecessorCurrentRangeProducerCount": opcode08_source_current_range_count,
        "opcode08SourceOrPredecessorOwnRangeProducerCount": opcode08_activation_windows.get(
            "sourceOrPredecessorOwnRangeProducerCount"
        ),
        "opcode08SourceOrPredecessorScriptScalarProducerCount": opcode08_activation_windows.get(
            "sourceOrPredecessorScriptScalarProducerCount"
        ),
        "opcode08CurrentInternalCurrentRangeProducerCount": opcode08_activation_windows.get(
            "currentInternalCurrentRangeProducerCount"
        ),
        "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 [],
        "opcode09SourceOrPredecessorPointerCollisionRowCount": opcode09_pointer_collisions.get(
            "sourceOrPredecessorPointerCollisionRowCount"
        ),
        "sourceOrPredecessorCurrentProducerCount": source_or_predecessor_current_producer_count,
        "correctedTraceNormalSelectionGapFound": corrected_trace_normal_selection_gap_found,
        "correctedTraceNormalSelectionGapStatus": corrected_trace_normal_selection_gap_status,
        "constructedDiagnosticWrapperProofStatus": constructed_diagnostic_status,
        "constructedDiagnosticExcludedFromWrapperProof": constructed_diagnostic_excluded,
        "constructedDiagnosticRuntimeSampleCount": diagnostic_exclusion_gate.get("runtimePollSampleCount"),
        "constructedDiagnosticObservedSelectors": diagnostic_exclusion_gate.get("runtimePollObservedSelectors") or [],
        "constructedDiagnosticReachedRouteSelector": diagnostic_exclusion_gate.get(
            "observedCurrentThenFollowupInDiagnosticPoll"
        )
        is True,
        "constructedDiagnosticFollowupSelector": diagnostic_exclusion_gate.get("followupSelector"),
        "constructedDiagnosticLeftStabilitySampleCount": diagnostic_exclusion_gate.get(
            "leftStabilitySampleCount"
        ),
        "constructedDiagnosticLeftStabilityRouteSelectorHitCount": diagnostic_exclusion_gate.get(
            "leftStabilityRouteSelectorHitCount"
        ),
        "constructedDiagnosticLeftStabilityReproducibility": diagnostic_exclusion_gate.get(
            "leftStabilityRouteHitReproducibility"
        ),
        "constructedDiagnosticLeftStabilityRecheckSampleCount": diagnostic_exclusion_gate.get(
            "leftStabilityRecheckSampleCount"
        ),
        "constructedDiagnosticLeftStabilityRecheckRouteSelectorHitCount": diagnostic_exclusion_gate.get(
            "leftStabilityRecheckRouteSelectorHitCount"
        ),
        "constructedDiagnosticLeftActiveOrderRecheckSampleCount": diagnostic_exclusion_gate.get(
            "leftActiveOrderRecheckSampleCount"
        ),
        "constructedDiagnosticLeftActiveOrderRecheckRouteSelectorHitCount": diagnostic_exclusion_gate.get(
            "leftActiveOrderRecheckRouteSelectorHitCount"
        ),
        "constructedDiagnosticLeftActiveOrderRecheckActiveOrderCountValues": diagnostic_exclusion_gate.get(
            "leftActiveOrderRecheckActiveOrderCountValues"
        ),
        "selectedRootExecutionRefFound": selected_root_execution_ref_found,
        "proofFound": proof_found,
        "failedWrapperGateIds": failed_wrapper_gate_ids,
        "missingEvidence": missing_evidence,
        "runtimeSelectionProven": runtime_selection_proven,
        "currentLeafSelectionProofFound": current_leaf_selection_proof_found,
        "wrapperExecutionProofFound": wrapper_execution_proof_found,
        "currentSelectorLeafExecutionProofFound": current_selector_leaf_execution_proof_found,
        "selectorMergeExecutionProofFound": selector_merge_execution_proof_found,
        "strictHotspotFound": strict_hotspot_found,
        "promotionStatus": promotion_status,
        "evidence": evidence,
        "evidenceRefs": EVIDENCE_REFS,
        "evidenceRefCount": len(EVIDENCE_REFS),
        "remainingProofs": [
            "prove selected-root execution reaches current selector 2:0 on the normal route path",
            "decode the higher-level table/index path that selects entries 6/8 or negative entry -12",
            "prove wrapper 0x00542a04 executes into frontier leaf 0x00542ae8 in normal route execution",
            "find a strict map1_01a source coordinate or hotspot linked to map2_02d",
        ],
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Save Selector Wrapper Execution Gap",
        "",
        summary["conclusion"],
        "",
        f"- route: `{summary['source']} -> {summary['target']}`",
        f"- selector: `{summary['selector']}` root `{summary['rootHex']}`",
        f"- root table pointer: `{summary['rootTablePointerHex']}`",
        f"- current root entry run: `{summary['currentRootEntryRunHex']}`",
        f"- wrapper entry: `{summary['wrapperEntryHex']}`",
        f"- wrapper descriptor: `{summary['wrapperDescriptorHex']}`",
        f"- wrapper child/frontier leaf: `{summary['wrapperChildPointerHex']}` / `{summary['frontierLeafHex']}`",
        f"- frontier reader: `{summary['frontierReaderHex']}`",
        f"- wrapper ref before current root: {summary['wrapperRefBeforeCurrentRoot']}",
        f"- current root references wrapper: {summary['currentRootReferencesWrapper']}",
        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 entry promoting refs: {summary['wrapperEntryPromotingRefCount']}",
        f"- global leaf table field entries negative/non-negative: {summary['globalNegativeFieldEntryRowCount']} / {summary['globalNonNegativeFieldEntryRowCount']}",
        f"- global current selector route-pair indices: {csv(summary['globalCurrentSelectorRoutePairIndices'])}",
        f"- global current frontier leaf only negative: {summary['globalCurrentFrontierLeafOnlyNegative']}",
        f"- root table direct refs/text refs: {summary['rootTableWindowDirectRefCount']} / {summary['rootTableWindowDirectTextRefCount']}",
        f"- root table route-entry/route-leaf/frontier-leaf/frontier-reader text refs: "
        f"{summary['rootTableRouteEntryAddressTextRefCount']} / "
        f"{summary['rootTableRouteLeafValueTextRefCount']} / "
        f"{summary['rootTableFrontierLeafValueTextRefCount']} / "
        f"{summary['rootTableFrontierReaderValueTextRefCount']}",
        f"- root table direct ref status: `{summary['rootTableDirectRefStatus']}`",
        f"- frontier leaf direct current-root ref: {summary['frontierLeafDirectCurrentRootRef']}",
        f"- route-pair descriptor indices: {csv(summary['currentRoutePairDescriptorIndices'])}",
        f"- corrected route-pair reader hits: {summary['currentRoutePairCorrectedTraceReachesReaderCount']}",
        f"- reader-bearing negative indices: {csv(summary['readerBearingNegativeIndices'])}",
        f"- opcode07 leaf selection absent: {summary['opcode07LeafSelectionAbsent']}",
        f"- opcode08 source/predecessor current root/range producers: {summary['opcode08SourceOrPredecessorCurrentRootProducerCount']} / {summary['opcode08SourceOrPredecessorCurrentRangeProducerCount']}",
        f"- opcode09 source/predecessor current-range stores: {summary['opcode09SourceOrPredecessorCurrentRangeStoreCount']}",
        f"- source/predecessor current producer count: {summary['sourceOrPredecessorCurrentProducerCount']}",
        f"- corrected trace normal-selection gap: `{summary['correctedTraceNormalSelectionGapStatus']}`",
        f"- corrected trace normal-selection gap found: {summary['correctedTraceNormalSelectionGapFound']}",
        f"- constructed diagnostic wrapper proof status: `{summary['constructedDiagnosticWrapperProofStatus']}`",
        f"- constructed diagnostic runtime route hit: {summary['constructedDiagnosticReachedRouteSelector']} ({summary['constructedDiagnosticRuntimeSampleCount']} samples; observed {csv(summary['constructedDiagnosticObservedSelectors'])})",
        f"- constructed diagnostic left stability/recheck route hits: {summary['constructedDiagnosticLeftStabilityRouteSelectorHitCount']} / {summary['constructedDiagnosticLeftStabilityRecheckRouteSelectorHitCount']}",
        f"- constructed diagnostic left active-order recheck: {summary['constructedDiagnosticLeftActiveOrderRecheckRouteSelectorHitCount']} route hits; count {summary['constructedDiagnosticLeftActiveOrderRecheckActiveOrderCountValues']}",
        f"- constructed diagnostic excluded from wrapper proof: {summary['constructedDiagnosticExcludedFromWrapperProof']}",
        f"- selected-root execution ref found: {summary['selectedRootExecutionRefFound']}",
        f"- proof found: {summary['proofFound']}",
        f"- failed wrapper gates: `{csv(summary.get('failedWrapperGateIds'))}`",
        f"- missing evidence count: {len(summary.get('missingEvidence') or [])}",
        f"- current leaf selection proof found: {summary['currentLeafSelectionProofFound']}",
        f"- wrapper execution proof found: {summary['wrapperExecutionProofFound']}",
        f"- current selector leaf execution proof found: {summary['currentSelectorLeafExecutionProofFound']}",
        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 []],
        "",
        "## Evidence",
        "",
        "| kind | status | detail |",
        "| --- | --- | --- |",
    ]
    for row in summary["evidence"]:
        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(["", "## Remaining Proofs", ""])
    lines.extend(f"- {item}" for item in summary["remainingProofs"])
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    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["evidence"]
    )
    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 Wrapper 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 Wrapper Execution Gap</h1>",
            f"  <p>{html.escape(summary['conclusion'])}</p>",
            (
                "  <p><b>Route:</b> "
                f"<code>{html.escape(summary['source'])} -> {html.escape(summary['target'])}</code>; "
                f"selector <code>{html.escape(str(summary['selector']))}</code>; "
                f"root <code>{html.escape(str(summary['rootHex']))}</code>; "
                f"table <code>{html.escape(str(summary['rootTablePointerHex']))}</code>.</p>"
            ),
            (
                "  <p><b>Wrapper:</b> "
                f"entry <code>{html.escape(str(summary['wrapperEntryHex']))}</code>; "
                f"descriptor <code>{html.escape(str(summary['wrapperDescriptorHex']))}</code>; "
                f"child <code>{html.escape(str(summary['wrapperChildPointerHex']))}</code>; "
                f"frontier reader <code>{html.escape(str(summary['frontierReaderHex']))}</code>.</p>"
            ),
            (
                "  <p><b>Global leaf table:</b> "
                f"field entries {summary['globalFieldEntryRowCount']} "
                f"({summary['globalNegativeFieldEntryRowCount']} negative / "
                f"{summary['globalNonNegativeFieldEntryRowCount']} non-negative); "
                "global current selector route-pair indices "
                f"<code>{html.escape(csv(summary['globalCurrentSelectorRoutePairIndices']))}</code>; "
                "global current frontier leaf only negative: "
                f"{summary['globalCurrentFrontierLeafOnlyNegative']}.</p>"
            ),
            (
                "  <p><b>Root table direct refs:</b> "
                f"{summary['rootTableWindowDirectRefCount']} refs / "
                f"{summary['rootTableWindowDirectTextRefCount']} text refs; "
                "route-entry/route-leaf/frontier-leaf/frontier-reader text refs "
                f"{summary['rootTableRouteEntryAddressTextRefCount']}/"
                f"{summary['rootTableRouteLeafValueTextRefCount']}/"
                f"{summary['rootTableFrontierLeafValueTextRefCount']}/"
                f"{summary['rootTableFrontierReaderValueTextRefCount']}; "
                "status "
                f"<code>{html.escape(str(summary['rootTableDirectRefStatus']))}</code>.</p>"
            ),
            (
                "  <p><b>Source/predecessor producers:</b> "
                "opcode08 current root/range "
                f"{summary['opcode08SourceOrPredecessorCurrentRootProducerCount']}/"
                f"{summary['opcode08SourceOrPredecessorCurrentRangeProducerCount']}; "
                "opcode09 current-range stores "
                f"{summary['opcode09SourceOrPredecessorCurrentRangeStoreCount']}; "
                "source/predecessor current producer count "
                f"{summary['sourceOrPredecessorCurrentProducerCount']}.</p>"
            ),
            (
                "  <p><b>corrected trace normal-selection gap:</b> "
                f"<code>{html.escape(str(summary['correctedTraceNormalSelectionGapStatus']))}</code>; "
                f"route-pair reader trace grounded {summary['routePairReaderTraceGrounded']}, "
                f"reader negative-only {summary['readerBearingNegativeOnly']}, "
                f"runtime selection {summary['runtimeSelectionProven']}, "
                f"wrapper proof {summary['wrapperExecutionProofFound']}.</p>"
            ),
            (
                "  <p><b>Constructed diagnostic recheck:</b> "
                "constructed diagnostic wrapper proof status "
                f"<code>{html.escape(str(summary['constructedDiagnosticWrapperProofStatus']))}</code>; "
                f"runtime route hit {summary['constructedDiagnosticReachedRouteSelector']} "
                f"({summary['constructedDiagnosticRuntimeSampleCount']} samples, observed "
                f"<code>{html.escape(csv(summary['constructedDiagnosticObservedSelectors']))}</code>); "
                "constructed diagnostic left stability/recheck route hits "
                f"{summary['constructedDiagnosticLeftStabilityRouteSelectorHitCount']}/"
                f"{summary['constructedDiagnosticLeftStabilityRecheckRouteSelectorHitCount']}; "
                "constructed diagnostic left active-order recheck route hits "
                f"{summary['constructedDiagnosticLeftActiveOrderRecheckRouteSelectorHitCount']} "
                f"with count <code>{html.escape(str(summary['constructedDiagnosticLeftActiveOrderRecheckActiveOrderCountValues']))}</code>; "
                f"excluded from wrapper proof {summary['constructedDiagnosticExcludedFromWrapperProof']}.</p>"
            ),
            (
                "  <p>current leaf selection proof found: "
                f"{summary['currentLeafSelectionProofFound']}; "
                "wrapper execution proof found: "
                f"{summary['wrapperExecutionProofFound']}; "
                "current selector leaf execution proof found: "
                f"{summary['currentSelectorLeafExecutionProofFound']}; "
                "proof found: "
                f"{summary['proofFound']}; "
                "failed wrapper gates: "
                f"<code>{html.escape(csv(summary.get('failedWrapperGateIds')))}</code>; "
                "missing evidence count: "
                f"{len(summary.get('missingEvidence') or [])}; "
                "promotion status: "
                f"<code>{html.escape(summary['promotionStatus'])}</code>.</p>"
            ),
            f"  <p><b>Evidence refs:</b> {summary['evidenceRefCount']}.</p>",
            "  <h2>Missing Evidence</h2>",
            f"  <ul>{missing_items}</ul>",
            "  <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>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_wrapper_execution_gap.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    (out_dir / "save_selector_wrapper_execution_gap.html").write_text(html_page(summary), encoding="utf-8")


def load_json(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--leaf-table-context", type=Path, default=OUT / "save_selector_leaf_table_context.json")
    parser.add_argument(
        "--leaf-table-global-context",
        type=Path,
        default=OUT / "save_selector_leaf_table_global_context.json",
    )
    parser.add_argument(
        "--wrapper-descriptor-context",
        type=Path,
        default=OUT / "save_selector_wrapper_descriptor_context.json",
    )
    parser.add_argument(
        "--route-pair-descriptor-context",
        type=Path,
        default=OUT / "save_selector_route_pair_descriptor_context.json",
    )
    parser.add_argument(
        "--opcode07-indexed-pointers",
        type=Path,
        default=OUT / "save_selector_opcode07_indexed_pointers.json",
    )
    parser.add_argument(
        "--opcode08-activation-windows",
        type=Path,
        default=OUT / "save_selector_opcode08_activation_windows.json",
    )
    parser.add_argument(
        "--opcode09-pointer-collisions",
        type=Path,
        default=OUT / "save_selector_opcode09_pointer_collisions.json",
    )
    parser.add_argument(
        "--selected-root-execution-gap",
        type=Path,
        default=OUT / "save_selector_selected_root_execution_gap.json",
    )
    parser.add_argument(
        "--current-root-frontier-paths",
        type=Path,
        default=OUT / "save_selector_current_root_frontier_paths.json",
    )
    parser.add_argument(
        "--merge-execution-gap",
        type=Path,
        default=OUT / "save_selector_merge_execution_gap.json",
    )
    parser.add_argument(
        "--route-pair-entry-execution-gap",
        type=Path,
        default=OUT / "save_selector_route_pair_entry_execution_gap.json",
    )
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.leaf_table_context),
        load_json(args.leaf_table_global_context),
        load_json(args.wrapper_descriptor_context),
        load_json(args.route_pair_descriptor_context),
        load_json(args.opcode07_indexed_pointers),
        load_json(args.opcode08_activation_windows),
        load_json(args.opcode09_pointer_collisions),
        load_json(args.selected_root_execution_gap),
        load_json(args.current_root_frontier_paths),
        load_json(args.merge_execution_gap),
        load_json(args.route_pair_entry_execution_gap),
    )
    write_outputs(summary, args.out_dir)
    print(f"wrote selector wrapper execution gap -> {args.out_dir / 'save_selector_wrapper_execution_gap.html'}")


if __name__ == "__main__":
    main()
