#!/usr/bin/env python3
"""Summarize why the current gate base is still unproven."""
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"
SOURCE = "map1_01a"
TARGET = "map2_02d"
CURRENT_WRITER = "0x005428bc"
CURRENT_OPCODE20 = "0x005428a8"
FIRST_GATE = "0x005428c4"
SECOND_GATE = "0x005428cc"
IMAGE_BASE = 0x00400000
IMAGE_SIZE = 0x001BE000
PUBLIC_PREDECESSOR_ACTIVE_ORDER_POLL = "runtime_selected_pointer_predecessor_direction_sweep_active_order_poll.json"
PUBLIC_PREDECESSOR_LEFT_OVERRUN_ACTIVE_ORDER_POLL = (
    "runtime_selected_pointer_predecessor_left_overrun_activation_active_order_poll.json"
)
GATE_BASE_MISSING_EVIDENCE_BY_GATE = {
    "opcode20-runtime-base-path": (
        "prove opcode 0x20 runtime descriptor/base path before 0x005428c4; "
        "active order alone is insufficient"
    ),
    "predecessor-state-persistence": "prove predecessor 1:0 state persistence into current 2:0",
    "strict-source-hotspot": (
        "find strict map1_01a source hotspot or equivalent non-coordinate trigger"
    ),
}


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


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


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


def current_writer_row(current_writer_paths: list[dict]) -> dict:
    return next((row for row in current_writer_paths if row.get("writerVaHex") == CURRENT_WRITER), {})


def local_base_affecting_rows(writer: dict) -> list[dict]:
    rows = []
    context_rows = (writer.get("activationContext") or {}).get("contextRows") or []
    for row in context_rows:
        opcode = row.get("opcodeHex")
        if opcode == "0x20":
            rows.append({
                "vaHex": row.get("vaHex"),
                "valueHex": row.get("valueHex"),
                "opcodeHex": opcode,
                "kind": "nested descriptor runner",
                "directBaseSetter": False,
                "meaning": row.get("meaning") or "dispatch/load runtime object or party-member script references",
            })
        elif opcode in {"0x28", "0x40", "0x41", "0x42", "0x43"}:
            rows.append({
                "vaHex": row.get("vaHex"),
                "valueHex": row.get("valueHex"),
                "opcodeHex": opcode,
                "kind": "base-selector-shaped local row",
                "directBaseSetter": False,
                "meaning": "low-byte shape only in save-selector stream; not proven as general nested handler",
            })
    return rows


def gate_window_rows(writer: dict) -> list[dict]:
    rows_by_va: dict[str, dict] = {}
    start = parse_hex(CURRENT_OPCODE20)
    end = parse_hex(FIRST_GATE)
    for row in (writer.get("activationContext") or {}).get("contextRows") or []:
        va_hex = row.get("vaHex")
        va = parse_hex(va_hex)
        if va is None or start is None or end is None or not (start <= va <= end):
            continue
        rows_by_va[va_hex] = {
            "vaHex": va_hex,
            "valueHex": row.get("valueHex"),
            "opcodeHex": row.get("opcodeHex"),
            "handlerVaHex": row.get("handlerVaHex") or "-",
            "meaning": row.get("meaning") or "",
        }
    for row in writer.get("trace") or []:
        va_hex = row.get("vaHex")
        va = parse_hex(va_hex)
        if va is None or start is None or end is None or not (start <= va <= end):
            continue
        previous = rows_by_va.get(va_hex, {})
        rows_by_va[va_hex] = {
            "vaHex": va_hex,
            "valueHex": row.get("valueHex") or previous.get("valueHex"),
            "opcodeHex": row.get("opcodeHex") or previous.get("opcodeHex"),
            "handlerVaHex": row.get("handlerVaHex") or previous.get("handlerVaHex") or "-",
            "meaning": row.get("meaning") or previous.get("meaning") or row.get("stopReason") or "",
        }
    rows = []
    for va_hex, row in sorted(rows_by_va.items(), key=lambda item: parse_hex(item[0]) or 0):
        row = dict(row)
        row["isWriter"] = va_hex == CURRENT_WRITER
        row["isFirstGate"] = va_hex == FIRST_GATE
        row["isBaseSetterCandidate"] = row.get("opcodeHex") in {"0x20", "0x28", "0x40", "0x41", "0x42", "0x43"}
        rows.append(row)
    return rows


def parse_order_index(value_hex: str | None) -> int | None:
    if not value_hex:
        return None
    try:
        return int(value_hex, 16)
    except ValueError:
        return None


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


def descriptor_row_for_descriptor(descriptor_scripts: dict, descriptor_hex: str | None) -> dict:
    if not descriptor_hex:
        return {}
    for row in descriptor_scripts.get("descriptorRows") or []:
        if row.get("descriptorVaHex") == descriptor_hex:
            return row
    return {}


def row_selectors(row: dict) -> set[str]:
    return {
        context.get("selector")
        for context in row.get("uniqueSelectorContexts") or []
        if context.get("selector")
    }


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


def watch_value_hex(watch_values: dict[str, list[dict[str, Any]]], name: str) -> str | None:
    rows = watch_values.get(name) or []
    if len(rows) != 1:
        return None
    return rows[0].get("valueHex")


def build_public_predecessor_active_order_evidence(
    active_order_poll: dict | None,
    descriptor_scripts: dict,
    source_poll: str = PUBLIC_PREDECESSOR_ACTIVE_ORDER_POLL,
) -> dict:
    active_order_poll = active_order_poll or {}
    if not active_order_poll:
        return {
            "available": False,
            "sourcePoll": source_poll,
        }
    public_selectors = set(active_order_poll.get("observedPublicSaveSelectors") or [])
    public_rows = [
        row for row in active_order_poll.get("rows") or []
        if public_selectors & row_selectors(row)
    ]
    watch_values = aggregate_poll_watch_values(public_rows)
    sample_count = sum(row.get("sampleCount", 0) for row in public_rows)
    active_order_count_hex = watch_value_hex(watch_values, "activeOrderCount")
    active_order_count = int(active_order_count_hex, 16) if active_order_count_hex else None
    order_byte_hexes = [
        watch_value_hex(watch_values, name)
        for name in ("activeOrder0", "activeOrder1", "activeOrder2")
    ]
    active_order_hexes = [
        value for value in order_byte_hexes[:active_order_count or 0] if value is not None
    ]
    loaded_base_hex = next((row.get("loadedBaseHex") for row in public_rows if row.get("loadedBaseHex")), None)
    first_descriptor_runtime_hex = watch_value_hex(watch_values, "activeSlot0Descriptor")
    first_descriptor_hex = static_from_runtime_hex(first_descriptor_runtime_hex, loaded_base_hex)
    descriptor_row = descriptor_row_for_descriptor(descriptor_scripts, first_descriptor_hex)
    last_context_a8 = descriptor_row.get("script4LastContextA8SetterRow") or {}
    gate_base_proven = bool(
        descriptor_row
        and (
            (descriptor_row.get("script4GateWriterCount") or 0) > 0
            or (descriptor_row.get("script4GateReaderCount") or 0) > 0
            or (descriptor_row.get("script4FieldRecordCount") or 0) > 0
            or (descriptor_row.get("script4CurrentFrontierDirectRefCount") or 0) > 0
            or (descriptor_row.get("script4EncodedTargetPromotingCandidateCount") or 0) > 0
            or (descriptor_row.get("script4ContextA8NonPointerSetterRowCount") or 0) > 0
        )
    )
    stable_watch_names = [
        "activeOrderCount",
        "activeOrder0",
        "activeOrder1",
        "activeOrder2",
        "activeSlot0Descriptor",
        "runtimeSlotBaseTable0",
        "runtimeObjectTable0",
        "runtimeObjectTable1",
        "runtimeObjectTable2",
    ]
    return {
        "available": True,
        "sourcePoll": source_poll,
        "stagedSaveKind": active_order_poll.get("stagedSaveKind"),
        "notRouteProof": not (
            active_order_poll.get("anyReachedCurrentRoot")
            or active_order_poll.get("anyReachedRouteSelectorContext")
        ),
        "promotionStatus": active_order_poll.get("promotionStatus"),
        "totalSampleCount": active_order_poll.get("sampleCount"),
        "totalSequenceCount": active_order_poll.get("sequenceCount"),
        "sampleCount": sample_count,
        "sequenceCount": len(public_rows),
        "publicSequenceNames": [row.get("name") for row in public_rows],
        "observedSelectors": active_order_poll.get("observedSelectors") or [],
        "observedPublicSaveSelectors": active_order_poll.get("observedPublicSaveSelectors") or [],
        "reachedCurrentRoot": active_order_poll.get("anyReachedCurrentRoot"),
        "reachedRouteSelector": active_order_poll.get("anyReachedRouteSelectorContext"),
        "loadedBaseHex": loaded_base_hex,
        "activeOrderCountHex": active_order_count_hex,
        "activeOrderCount": active_order_count,
        "orderByteHexes": [value for value in order_byte_hexes if value is not None],
        "activeOrderHexes": active_order_hexes,
        "firstDescriptorRuntimeHex": first_descriptor_runtime_hex,
        "firstDescriptorHex": first_descriptor_hex,
        "firstDescriptorMatchesScript": bool(
            first_descriptor_hex and descriptor_row.get("descriptorVaHex") == first_descriptor_hex
        ),
        "runtimeSlotBaseTable0Hex": watch_value_hex(watch_values, "runtimeSlotBaseTable0"),
        "runtimeObjectTableHexes": [
            value for value in [
                watch_value_hex(watch_values, "runtimeObjectTable0"),
                watch_value_hex(watch_values, "runtimeObjectTable1"),
                watch_value_hex(watch_values, "runtimeObjectTable2"),
            ]
            if value is not None
        ],
        "allPublicWatchedValuesStable": all(
            len(watch_values.get(name) or []) == 1 for name in stable_watch_names
        ),
        "descriptorScript0VaHex": descriptor_row.get("script0VaHex"),
        "descriptorScript4VaHex": descriptor_row.get("script4VaHex"),
        "descriptorScript0LinkedCns": descriptor_row.get("script0LinkedCns") or [],
        "descriptorScript4LinkedCns": descriptor_row.get("script4LinkedCns") or [],
        "descriptorScript4FieldRecordCount": descriptor_row.get("script4FieldRecordCount"),
        "descriptorScript4CurrentFrontierDirectRefCount": descriptor_row.get("script4CurrentFrontierDirectRefCount"),
        "descriptorScript4EncodedTargetClassification": descriptor_row.get("script4EncodedTargetClassification"),
        "descriptorScript4EncodedTargetRawScalarCandidateCount": descriptor_row.get(
            "script4EncodedTargetRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount": descriptor_row.get(
            "script4EncodedTargetRouteProofRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetRouteContextRawScalarCandidateCount": descriptor_row.get(
            "script4EncodedTargetRouteContextRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetPromotingCandidateCount": descriptor_row.get(
            "script4EncodedTargetPromotingCandidateCount"
        ),
        "descriptorScript4GateWriterCount": descriptor_row.get("script4GateWriterCount"),
        "descriptorScript4GateReaderCount": descriptor_row.get("script4GateReaderCount"),
        "descriptorScript4ContextA8NonPointerSetterRowCount": descriptor_row.get(
            "script4ContextA8NonPointerSetterRowCount"
        ),
        "descriptorScript4LastContextA8IsPointerDword": last_context_a8.get("isPointerDword"),
        "descriptorScript4LastContextA8Shape": last_context_a8.get("shapeClassification"),
        "descriptorScript4LastContextA8VaHex": last_context_a8.get("vaHex"),
        "gateBaseProven": gate_base_proven,
    }


def build_diagnostic_active_order_evidence(
    runtime_patched_selector_followup_context: dict | None,
    descriptor_scripts: dict,
) -> dict:
    active_order = (runtime_patched_selector_followup_context or {}).get("activeOrderRuntimeEvidence") or {}
    if not active_order or active_order.get("available") is not True:
        return {
            "available": False,
            "sourcePoll": active_order.get("sourcePoll")
            or "runtime_selected_pointer_patched_public_selector_2_0_active_order_poll.json",
        }
    active_order_hexes = active_order.get("activeOrderHexes") or []
    first_order_hex = active_order_hexes[0] if active_order_hexes else None
    first_descriptor_hexes = active_order.get("activeSlotFirstDwordsStaticHex") or []
    first_descriptor_hex = first_descriptor_hexes[0] if first_descriptor_hexes else None
    descriptor_row = descriptor_row_for_descriptor(descriptor_scripts, first_descriptor_hex)
    last_context_a8 = descriptor_row.get("script4LastContextA8SetterRow") or {}
    gate_base_proven = bool(
        descriptor_row
        and (
            (descriptor_row.get("script4GateWriterCount") or 0) > 0
            or (descriptor_row.get("script4GateReaderCount") or 0) > 0
            or (descriptor_row.get("script4FieldRecordCount") or 0) > 0
            or (descriptor_row.get("script4CurrentFrontierDirectRefCount") or 0) > 0
            or (descriptor_row.get("script4EncodedTargetPromotingCandidateCount") or 0) > 0
            or (descriptor_row.get("script4ContextA8NonPointerSetterRowCount") or 0) > 0
        )
    )
    return {
        "available": True,
        "sourcePoll": active_order.get("sourcePoll"),
        "stagedSaveKind": active_order.get("stagedSaveKind"),
        "notRouteProof": active_order.get("notRoutePromotionProof"),
        "promotionStatus": active_order.get("promotionStatus"),
        "sampleCount": active_order.get("sampleCount"),
        "observedSelectors": active_order.get("observedSelectors") or [],
        "activeOrderCountHex": active_order.get("activeOrderCountHex"),
        "activeOrderHexes": active_order_hexes,
        "orderByteHexes": active_order.get("orderByteHexes") or [],
        "firstDescriptorIndex": parse_order_index(first_order_hex),
        "firstDescriptorHex": first_descriptor_hex,
        "firstDescriptorMatchesScript": bool(
            first_descriptor_hex and descriptor_row.get("descriptorVaHex") == first_descriptor_hex
        ),
        "descriptorScript0VaHex": descriptor_row.get("script0VaHex"),
        "descriptorScript4VaHex": descriptor_row.get("script4VaHex"),
        "descriptorScript0LinkedCns": descriptor_row.get("script0LinkedCns") or [],
        "descriptorScript4LinkedCns": descriptor_row.get("script4LinkedCns") or [],
        "descriptorScript4FieldRecordCount": descriptor_row.get("script4FieldRecordCount"),
        "descriptorScript4CurrentFrontierDirectRefCount": descriptor_row.get("script4CurrentFrontierDirectRefCount"),
        "descriptorScript4EncodedTargetClassification": descriptor_row.get("script4EncodedTargetClassification"),
        "descriptorScript4EncodedTargetRawScalarCandidateCount": descriptor_row.get(
            "script4EncodedTargetRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount": descriptor_row.get(
            "script4EncodedTargetRouteProofRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetRouteContextRawScalarCandidateCount": descriptor_row.get(
            "script4EncodedTargetRouteContextRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetPromotingCandidateCount": descriptor_row.get(
            "script4EncodedTargetPromotingCandidateCount"
        ),
        "descriptorScript4GateWriterCount": descriptor_row.get("script4GateWriterCount"),
        "descriptorScript4GateReaderCount": descriptor_row.get("script4GateReaderCount"),
        "descriptorScript4ContextA8NonPointerSetterRowCount": descriptor_row.get(
            "script4ContextA8NonPointerSetterRowCount"
        ),
        "descriptorScript4LastContextA8IsPointerDword": last_context_a8.get("isPointerDword"),
        "descriptorScript4LastContextA8Shape": last_context_a8.get("shapeClassification"),
        "descriptorScript4LastContextA8VaHex": last_context_a8.get("vaHex"),
        "gateBaseProven": gate_base_proven,
    }


def build_diagnostic_active_order_recheck_evidence(
    runtime_patched_selector_followup_context: dict | None,
) -> dict:
    left_stability = (runtime_patched_selector_followup_context or {}).get("leftStabilityRuntimeEvidence") or {}
    recheck = left_stability.get("recheck") or {}
    active_order_recheck = left_stability.get("activeOrderRecheck") or {}
    if not left_stability:
        return {"available": False}
    not_reproduced = (
        (left_stability.get("routeSelectorHitCount") or 0) > 0
        and (recheck.get("routeSelectorHitCount") or 0) == 0
        and (active_order_recheck.get("routeSelectorHitCount") or 0) == 0
        and left_stability.get("routeHitReproducibility") == "not-reproduced"
    )
    return {
        "available": True,
        "sourcePoll": left_stability.get("sourcePoll"),
        "recheckSourcePoll": recheck.get("sourcePoll"),
        "activeOrderRecheckSourcePoll": active_order_recheck.get("sourcePoll"),
        "promotionStatus": left_stability.get("promotionStatus"),
        "sampleCount": left_stability.get("sampleCount"),
        "routeSelectorHitCount": left_stability.get("routeSelectorHitCount"),
        "observedSelectors": left_stability.get("observedSelectors") or [],
        "routeHitReproducibility": left_stability.get("routeHitReproducibility"),
        "routeHitReproducedByRecheck": left_stability.get("routeHitReproducedByRecheck"),
        "routeHitReproducedWithActiveOrderWatch": left_stability.get(
            "routeHitReproducedWithActiveOrderWatch"
        ),
        "recheckSampleCount": recheck.get("sampleCount"),
        "recheckObservedSelectors": recheck.get("observedSelectors") or [],
        "recheckRouteSelectorHitCount": recheck.get("routeSelectorHitCount"),
        "activeOrderRecheckSampleCount": active_order_recheck.get("sampleCount"),
        "activeOrderRecheckObservedSelectors": active_order_recheck.get("observedSelectors") or [],
        "activeOrderRecheckRouteSelectorHitCount": active_order_recheck.get("routeSelectorHitCount"),
        "activeOrderRecheckActiveOrderCountValues": active_order_recheck.get("activeOrderCountValues"),
        "activeOrderRecheckSlot0DescriptorValues": active_order_recheck.get(
            "activeSlot0DescriptorValues"
        ),
        "activeOrderRecheckRuntimeSlotBaseTable0Values": active_order_recheck.get(
            "runtimeSlotBaseTable0Values"
        ),
        "notReproducedWithActiveOrderRecheck": not_reproduced,
        "gateBaseStillUnproven": not_reproduced,
    }


def build_context_f2_source_evidence(context_f2_sources: dict | None) -> dict:
    context_f2_sources = context_f2_sources or {}
    if not context_f2_sources:
        return {"available": False}
    diagnostic = context_f2_sources.get("diagnosticRuntimeObjectTableEvidence") or {}
    return {
        "available": True,
        "sourceArtifact": "save_selector_opcode20_context_f2_sources.json",
        "contextFieldOffsetHex": context_f2_sources.get("contextFieldOffsetHex"),
        "runtimeObjectTableHex": context_f2_sources.get("runtimeObjectTableHex"),
        "referenceCount": context_f2_sources.get("referenceCount"),
        "readReferenceCount": context_f2_sources.get("readReferenceCount"),
        "writeReferenceCount": context_f2_sources.get("writeReferenceCount"),
        "runtimeObjectTableReaderCount": context_f2_sources.get("runtimeObjectTableReaderCount"),
        "directInitializerCount": context_f2_sources.get("directInitializerCount"),
        "copyWriterCount": context_f2_sources.get("copyWriterCount"),
        "constantWriteCount": context_f2_sources.get("constantWriteCount"),
        "objectBaseCandidateCount": context_f2_sources.get("objectBaseCandidateCount"),
        "contextF2ObjectSelectorCount": context_f2_sources.get("contextF2ObjectSelectorCount"),
        "fixedStream2ObjectSelectorCount": context_f2_sources.get("fixedStream2ObjectSelectorCount"),
        "currentFrontierSampleCovered": context_f2_sources.get("currentFrontierSampleCovered"),
        "activeOrderAlonePromotesRoute": context_f2_sources.get("activeOrderAlonePromotesRoute"),
        "fixedContextF2ValueProvenForCurrentFrontier": context_f2_sources.get(
            "fixedContextF2ValueProvenForCurrentFrontier"
        ),
        "specificRuntimeObjectPointerProven": context_f2_sources.get(
            "specificRuntimeObjectPointerProven"
        ),
        "runtimeObjectTableStateRequired": context_f2_sources.get(
            "runtimeObjectTableStateRequired"
        ),
        "remainingProofCount": len(context_f2_sources.get("remainingProofs") or []),
        "promotionStatus": context_f2_sources.get("promotionStatus"),
        "diagnosticAvailable": diagnostic.get("available"),
        "diagnosticOnly": diagnostic.get("diagnosticOnly"),
        "diagnosticRouteSampleCount": diagnostic.get("routeSampleCount"),
        "diagnosticTotalSampleCount": diagnostic.get("totalSampleCount"),
        "diagnosticActiveOrderCountHex": diagnostic.get("activeOrderCountHex"),
        "diagnosticActiveOrderHexes": diagnostic.get("activeOrderHexes") or [],
        "diagnosticRuntimeObjectTableStaticHexes": diagnostic.get(
            "runtimeObjectTableStaticHexes"
        ) or [],
        "diagnosticNormalRouteProof": diagnostic.get("normalRouteProof"),
        "diagnosticPromotionStatus": diagnostic.get("promotionStatus"),
    }


def build_summary(
    current_writer_paths: list[dict] | None = None,
    opcode20_nested: dict | None = None,
    descriptor_scripts: dict | None = None,
    sample_order_effects: dict | None = None,
    gate_pass_matrix: dict | None = None,
    runtime_patched_selector_followup_context: dict | None = None,
    runtime_predecessor_direction_sweep_active_order_poll: dict | None = None,
    runtime_predecessor_left_overrun_active_order_poll: dict | None = None,
    opcode20_context_f2_sources: dict | None = None,
    gate_offset_sources: dict | None = None,
    gate_offset_patterns: dict | None = None,
    gate_base_candidates: dict | None = None,
    gate_sample_values: dict | None = None,
    selection_buffer_bases: dict | None = None,
    opcode20_object_base_candidates: dict | None = None,
    opcode20_order_space: dict | None = None,
    opcode20_slot_sources: dict | None = None,
    opcode20_slot_descriptor_writers: dict | None = None,
    opcode20_runtime_materializers: dict | None = None,
) -> dict:
    current_writer_paths = current_writer_paths if current_writer_paths is not None else load_json(
        OUT / "save_selector_current_writer_paths.json",
        [],
    )
    opcode20_nested = opcode20_nested if opcode20_nested is not None else load_json(
        OUT / "save_selector_opcode20_nested_base_modes.json",
        {},
    )
    descriptor_scripts = descriptor_scripts if descriptor_scripts is not None else load_json(
        OUT / "save_selector_opcode20_descriptor_scripts.json",
        {},
    )
    sample_order_effects = sample_order_effects if sample_order_effects is not None else load_json(
        OUT / "save_selector_opcode20_sample_order_effects.json",
        {},
    )
    gate_pass_matrix = gate_pass_matrix if gate_pass_matrix is not None else load_json(
        OUT / "save_selector_gate_pass_matrix.json",
        {},
    )
    runtime_patched_selector_followup_context = (
        runtime_patched_selector_followup_context
        if runtime_patched_selector_followup_context is not None
        else load_json(OUT / "runtime_patched_selector_followup_context.json", {})
    )
    runtime_predecessor_direction_sweep_active_order_poll = (
        runtime_predecessor_direction_sweep_active_order_poll
        if runtime_predecessor_direction_sweep_active_order_poll is not None
        else load_json(OUT / PUBLIC_PREDECESSOR_ACTIVE_ORDER_POLL, {})
    )
    runtime_predecessor_left_overrun_active_order_poll = (
        runtime_predecessor_left_overrun_active_order_poll
        if runtime_predecessor_left_overrun_active_order_poll is not None
        else load_json(OUT / PUBLIC_PREDECESSOR_LEFT_OVERRUN_ACTIVE_ORDER_POLL, {})
    )
    opcode20_context_f2_sources = (
        opcode20_context_f2_sources
        if opcode20_context_f2_sources is not None
        else load_json(OUT / "save_selector_opcode20_context_f2_sources.json", {})
    )
    gate_offset_sources = (
        gate_offset_sources
        if gate_offset_sources is not None
        else load_json(OUT / "save_selector_gate_offset_sources.json", {})
    )
    gate_offset_patterns = (
        gate_offset_patterns
        if gate_offset_patterns is not None
        else load_json(OUT / "save_selector_gate_offset_patterns.json", {})
    )
    gate_base_candidates = (
        gate_base_candidates
        if gate_base_candidates is not None
        else load_json(OUT / "save_selector_gate_base_candidates.json", {})
    )
    gate_sample_values = (
        gate_sample_values
        if gate_sample_values is not None
        else load_json(OUT / "save_selector_gate_sample_values.json", {})
    )
    selection_buffer_bases = (
        selection_buffer_bases
        if selection_buffer_bases is not None
        else load_json(OUT / "save_selector_selection_buffer_bases.json", {})
    )
    opcode20_object_base_candidates = (
        opcode20_object_base_candidates
        if opcode20_object_base_candidates is not None
        else load_json(OUT / "save_selector_opcode20_object_base_candidates.json", {})
    )
    opcode20_order_space = (
        opcode20_order_space
        if opcode20_order_space is not None
        else load_json(OUT / "save_selector_opcode20_order_space.json", {})
    )
    opcode20_slot_sources = (
        opcode20_slot_sources
        if opcode20_slot_sources is not None
        else load_json(OUT / "save_selector_opcode20_slot_sources.json", {})
    )
    opcode20_slot_descriptor_writers = (
        opcode20_slot_descriptor_writers
        if opcode20_slot_descriptor_writers is not None
        else load_json(OUT / "save_selector_opcode20_slot_descriptor_writers.json", {})
    )
    opcode20_runtime_materializers = (
        opcode20_runtime_materializers
        if opcode20_runtime_materializers is not None
        else load_json(OUT / "save_selector_opcode20_runtime_materializers.json", {})
    )
    writer = current_writer_row(current_writer_paths)
    local_rows = local_base_affecting_rows(writer)
    local_gate_window_rows = gate_window_rows(writer)
    gate_window_base_candidates = [row for row in local_gate_window_rows if row.get("isBaseSetterCandidate")]
    gate_window_only_opcode20_base_candidate = (
        len(gate_window_base_candidates) == 1
        and gate_window_base_candidates[0].get("vaHex") == CURRENT_OPCODE20
    )
    direct_local_setters = [row for row in local_rows if row.get("directBaseSetter")]
    opcode20_rows = [row for row in local_rows if row.get("opcodeHex") == "0x20"]
    descriptor_script4_non_pointer_bases = [
        row.get("value")
        for row in descriptor_scripts.get("script4ContextA8NonPointerBaseExpressionHistogram") or []
        if row.get("value")
    ]
    descriptor_script4_gate_quiet = (
        descriptor_scripts.get("script4SpecificGateBaseProven") is False
        and descriptor_scripts.get("script4GateWriterCount") == 0
        and descriptor_scripts.get("script4GateReaderCount") == 0
    )
    descriptor_script4_route_quiet = (
        descriptor_scripts.get("script4FieldRecordCount") == 0
        and descriptor_scripts.get("script4CurrentFrontierDirectRefCount") == 0
        and descriptor_scripts.get("script4EncodedTargetPromotingCandidateCount") == 0
    )
    descriptor_all_script_gate_quiet = (
        descriptor_scripts.get("allScriptsSpecificGateBaseProven") is False
        and descriptor_scripts.get("allScriptGateWriterCount") == 0
        and descriptor_scripts.get("allScriptGateReaderCount") == 0
    )
    descriptor_all_script_route_quiet = (
        descriptor_scripts.get("allScriptFieldRecordCount") == 0
        and descriptor_scripts.get("allScriptCurrentFrontierDirectRefCount") == 0
        and descriptor_scripts.get("allScriptEncodedTargetPromotingCandidateCount") == 0
    )
    active_order_alone_sufficient = not (
        descriptor_script4_gate_quiet
        and descriptor_script4_route_quiet
        and descriptor_all_script_gate_quiet
        and descriptor_all_script_route_quiet
    )
    diagnostic_active_order = build_diagnostic_active_order_evidence(
        runtime_patched_selector_followup_context,
        descriptor_scripts,
    )
    diagnostic_active_order_recheck = build_diagnostic_active_order_recheck_evidence(
        runtime_patched_selector_followup_context
    )
    public_predecessor_active_order = build_public_predecessor_active_order_evidence(
        runtime_predecessor_direction_sweep_active_order_poll,
        descriptor_scripts,
    )
    public_predecessor_left_overrun_active_order = build_public_predecessor_active_order_evidence(
        runtime_predecessor_left_overrun_active_order_poll,
        descriptor_scripts,
        PUBLIC_PREDECESSOR_LEFT_OVERRUN_ACTIVE_ORDER_POLL,
    )
    context_f2_source_evidence = build_context_f2_source_evidence(opcode20_context_f2_sources)
    opcode20_signature_matches = (opcode20_nested.get("opcode20SignatureSummary") or {}).get(
        "signatureMatches"
    ) or []
    opcode20_signature_found_count = sum(
        1 for row in opcode20_signature_matches if row.get("found")
    )
    nested_runner = opcode20_nested.get("nestedRunner") or {}
    active_order_proof_found = (
        active_order_alone_sufficient is True
        and (
            diagnostic_active_order.get("gateBaseProven") is True
            or public_predecessor_active_order.get("gateBaseProven") is True
            or public_predecessor_left_overrun_active_order.get("gateBaseProven") is True
        )
    )
    gate_time_base_proof_found = (
        descriptor_scripts.get("script4SpecificGateBaseProven") is True
        or descriptor_scripts.get("allScriptsSpecificGateBaseProven") is True
        or context_f2_source_evidence.get("specificRuntimeObjectPointerProven") is True
        or diagnostic_active_order.get("gateBaseProven") is True
        or public_predecessor_active_order.get("gateBaseProven") is True
        or public_predecessor_left_overrun_active_order.get("gateBaseProven") is True
    )
    predecessor_persistence_proof_found = (
        gate_pass_matrix.get("predecessorPersistenceProofRequired") is False
    )
    strict_hotspot_proof_found = gate_pass_matrix.get("strictHotspotProofRequired") is False
    failed_gate_base_gate_ids = []
    if not gate_time_base_proof_found:
        failed_gate_base_gate_ids.append("opcode20-runtime-base-path")
    if not predecessor_persistence_proof_found:
        failed_gate_base_gate_ids.append("predecessor-state-persistence")
    if not strict_hotspot_proof_found:
        failed_gate_base_gate_ids.append("strict-source-hotspot")
    missing_evidence = [
        GATE_BASE_MISSING_EVIDENCE_BY_GATE.get(gate_id, gate_id)
        for gate_id in failed_gate_base_gate_ids
    ]
    proof_found = not failed_gate_base_gate_ids
    conclusion = (
        "The current gate pass calculation only becomes useful if the gate-time context+0xa8 base is known. "
        "The local stream before 0x005428c4 has no direct context+0xa8 base setter; the only base-affecting "
        "candidate in the activation window is opcode 0x20 at 0x005428a8, which runs runtime descriptor+4 nested "
        "scripts through the general handler table. The opcode 0x20 handler signature scan confirms that this row "
        "uses the descriptor+4 nested stream shape, and the nested runner swaps into the general dispatcher rather "
        "than executing the save-selector stream inline. Static descriptor scanning finds no descriptor+4 field-map "
        "records, no direct or encoded-scalar current-frontier/route refs, and no 0xe8/0xea gate readers or writers. The same gate-offset "
        "count is zero across descriptor+0, descriptor+4, and descriptor+8 scripts even though those scripts contain "
        "362 selection-buffer opcode-shaped rows, so the active descriptor order alone cannot prove this route. "
        "The patched selector 2:0 diagnostic active order selects descriptor "
        "0x004f867c, but its descriptor+4 script has no field-map/current-frontier/gate rows and its last context+0xa8 "
        "setter is a pointer-dword-low-byte-collision, so that diagnostic path is also non-promoting. A public "
        "predecessor direction sweep reaches selector 1:0 with active order 0x01/[0x00] and the same descriptor "
        "0x004f867c, but it still does not reach selector 2:0 or the route context and descriptor+4 remains without "
        "field/frontier/gate rows. The constructed diagnostic left-route hit is not reproduced by either the "
        "selector-only recheck or the active-order recheck, and that active-order recheck stays at count 0, so it "
        "does not prove the gate-time base. A public predecessor left-overrun activation sweep also reaches selector "
        "1:0 with the same non-promoting active-order evidence and still misses selector 2:0/current root. Therefore the "
        "context+0xf2 source scan is part of this gate-base proof: it sees runtime object-table reads and copies, "
        "not a fixed current-route object pointer. "
        "The supporting gate-offset, base-candidate, sample-value, selection-buffer-base, object-base, order-space, "
        "slot-source, descriptor-writer, and runtime-materializer reports also remain blocked/non-promoting: the gate "
        "offsets are inherited reader-only state, public samples do not cover selector 2:0, active order is not proven "
        "for the current frontier, and slot/materializer scans still require runtime descriptor/object state. "
        "save/runtime pass matrix narrows the hypothesis but cannot promote "
        "map1_01a -> map2_02d until the opcode 0x20 runtime descriptor/base path or an equivalent runtime trace is "
        "proven."
    )
    evidence_refs = [
        {
            "path": "out/save_selector_current_writer_paths.json",
            "fields": [
                "classification",
                "rootHex",
                "writerVaHex",
                "activationContext",
                "trace",
            ],
        },
        {
            "path": "out/save_selector_opcode20_nested_base_modes.json",
            "fields": [
                "currentModeIsNestedObjectPlus4",
                "directContextA8SetterCount",
                "nestedRunner",
                "opcode20SignatureSummary",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_descriptor_scripts.json",
            "fields": [
                "script4SpecificGateBaseProven",
                "script4GateWriterCount",
                "script4GateReaderCount",
                "allScriptsSpecificGateBaseProven",
                "allScriptSelectionOpcodeCount",
                "runtimeActiveOrderRequired",
            ],
        },
        {
            "path": "out/save_selector_opcode20_sample_order_effects.json",
            "fields": [
                "sampleCount",
                "currentFrontierSampleCovered",
                "sampleFinalNonPointerContextA8BaseHistogram",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_gate_pass_matrix.json",
            "fields": [
                "saveRuntimePassMatrix",
                "saveRuntimePredecessorAllGatePassSampleCount",
                "saveRuntimeZeroTableAllGatePassSampleCount",
                "runtimeBaseProofRequired",
                "predecessorPersistenceProofRequired",
                "strictHotspotProofRequired",
                "promotionStatus",
            ],
        },
        {
            "path": "out/runtime_patched_selector_followup_context.json",
            "fields": [
                "activeOrderRuntimeEvidence",
                "leftStabilityRuntimeEvidence",
                "promotionStatus",
            ],
        },
        {
            "path": f"out/{PUBLIC_PREDECESSOR_ACTIVE_ORDER_POLL}",
            "fields": [
                "observedPublicSaveSelectors",
                "rows",
                "anyReachedCurrentRoot",
                "anyReachedRouteSelectorContext",
                "promotionStatus",
            ],
        },
        {
            "path": f"out/{PUBLIC_PREDECESSOR_LEFT_OVERRUN_ACTIVE_ORDER_POLL}",
            "fields": [
                "observedPublicSaveSelectors",
                "rows",
                "anyReachedCurrentRoot",
                "anyReachedRouteSelectorContext",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_gate_offset_sources.json",
            "fields": [
                "gateOffsetsHex",
                "anyScriptLocalSelectionWriter",
                "anyGlobalScriptSelectionWriter",
                "controlPathGateStatus",
                "controlPathProofStatus",
                "proofFound",
                "gateOffsetSourceProofFound",
                "failedGateOffsetSourceGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_gate_offset_patterns.json",
            "fields": [
                "offsets",
                "totalReaderCount",
                "totalWriterCount",
                "proofFound",
                "gateOffsetPatternProofFound",
                "failedGateOffsetPatternGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_gate_base_candidates.json",
            "fields": [
                "candidateCount",
                "directRefCandidateCount",
                "partySlotStatByteCandidateCount",
                "runtimePointerModeStillRequired",
                "proofFound",
                "gateBaseCandidateProofFound",
                "failedGateBaseCandidateGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_gate_sample_values.json",
            "fields": [
                "sampleCount",
                "uniqueSelectorCount",
                "currentFrontierSampleCovered",
                "runtimePointerModeStillRequired",
                "proofFound",
                "gateSampleValueProofFound",
                "failedGateSampleValueGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_selection_buffer_bases.json",
            "fields": [
                "knownStaticGateOffsetDirectRefCount",
                "runtimePointerModeStillRequired",
                "proofFound",
                "selectionBufferBaseProofFound",
                "failedSelectionBufferBaseGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_object_base_candidates.json",
            "fields": [
                "candidateCount",
                "contextF2ObjectSelectorCount",
                "fieldMapRowsAfterCandidateCount",
                "currentFrontierRowsAfterCandidateCount",
                "gateSelectionRowsAfterCandidateCount",
                "runtimeObjectPointerProofRequired",
                "proofFound",
                "opcode20ObjectBaseProofFound",
                "failedOpcode20ObjectBaseGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_order_space.json",
            "fields": [
                "descriptorRowCount",
                "currentFrontierSampleCovered",
                "activeOrderAlonePromotesRoute",
                "runtimeDescriptorObjectStateRequired",
                "proofFound",
                "opcode20OrderSpaceProofFound",
                "failedOpcode20OrderSpaceGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_slot_sources.json",
            "fields": [
                "runtimeSlotCountRequired",
                "runtimeSlotDescriptorPointersRequired",
                "controlPathProofStatus",
                "proofFound",
                "opcode20SlotSourceProofFound",
                "failedOpcode20SlotSourceGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_slot_descriptor_writers.json",
            "fields": [
                "descriptorWriteCount",
                "opcode20Mode0ScriptSource",
                "runtimeActiveOrderRequired",
                "controlPathProofStatus",
                "proofFound",
                "opcode20DescriptorWriterProofFound",
                "failedOpcode20DescriptorWriterGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_runtime_materializers.json",
            "fields": [
                "materializers",
                "loadRebuildEvidence",
                "currentRouteSameLowByteRowCount",
                "descriptorScriptMutationRowCount",
                "currentFrontierActiveOrderProven",
                "opcode20SelfMutationPathEliminated",
                "controlPathProofStatus",
                "proofFound",
                "opcode20RuntimeMaterializerProofFound",
                "failedOpcode20RuntimeMaterializerGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_opcode20_context_f2_sources.json",
            "fields": [
                "referenceCount",
                "readReferenceCount",
                "writeReferenceCount",
                "runtimeObjectTableReaderCount",
                "specificRuntimeObjectPointerProven",
                "runtimeObjectTableStateRequired",
                "diagnosticRuntimeObjectTableEvidence",
                "promotionStatus",
            ],
        },
    ]
    return {
        "source": SOURCE,
        "target": TARGET,
        "currentWriterVaHex": CURRENT_WRITER,
        "firstGateVaHex": "0x005428c4",
        "secondGateVaHex": "0x005428cc",
        "writerStreamStartHex": writer.get("streamStartHex"),
        "gateWindowRows": local_gate_window_rows,
        "gateWindowBaseSetterCandidateCount": len(gate_window_base_candidates),
        "gateWindowOnlyOpcode20BaseCandidate": gate_window_only_opcode20_base_candidate,
        "localBaseAffectingRowsBeforeGate": local_rows,
        "localBaseAffectingRowCount": len(local_rows),
        "localDirectBaseSetterCount": len(direct_local_setters),
        "opcode20CandidateCount": len(opcode20_rows),
        "opcode20CandidateVaHex": CURRENT_OPCODE20 if opcode20_rows else None,
        "opcode20CurrentMode": opcode20_nested.get("currentMode"),
        "opcode20CurrentModeIsNestedObjectPlus4": opcode20_nested.get("currentModeIsNestedObjectPlus4"),
        "opcode20DirectContextA8SetterCountInNestedTable": opcode20_nested.get("directContextA8SetterCount"),
        "opcode20HandlerSignatureFoundCount": opcode20_signature_found_count,
        "opcode20HandlerSignatureTotalCount": len(opcode20_signature_matches),
        "opcode20NestedDispatcherUsesGeneralTable": nested_runner.get("dispatcherUsesGeneralTable"),
        "opcode20NestedRunnerSwapsContextStream": nested_runner.get(
            "runnerTemporarilySwapsContextStream"
        ),
        "descriptorScript4SpecificGateBaseProven": descriptor_scripts.get("script4SpecificGateBaseProven"),
        "descriptorScript4GateWriterCount": descriptor_scripts.get("script4GateWriterCount"),
        "descriptorScript4GateReaderCount": descriptor_scripts.get("script4GateReaderCount"),
        "descriptorScript4FieldRecordCount": descriptor_scripts.get("script4FieldRecordCount"),
        "descriptorScript4CurrentFrontierDirectRefCount": descriptor_scripts.get("script4CurrentFrontierDirectRefCount"),
        "descriptorScript4EncodedTargetClassification": descriptor_scripts.get("script4EncodedTargetClassification"),
        "descriptorScript4EncodedTargetRawScalarCandidateCount": descriptor_scripts.get(
            "script4EncodedTargetRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount": descriptor_scripts.get(
            "script4EncodedTargetRouteProofRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetRouteContextRawScalarCandidateCount": descriptor_scripts.get(
            "script4EncodedTargetRouteContextRawScalarCandidateCount"
        ),
        "descriptorScript4EncodedTargetPromotingCandidateCount": descriptor_scripts.get(
            "script4EncodedTargetPromotingCandidateCount"
        ),
        "descriptorScript4EncodedTargetGroupCounts": descriptor_scripts.get("script4EncodedTargetGroupCounts") or {},
        "descriptorScript4EncodedTargetLabelCounts": descriptor_scripts.get("script4EncodedTargetLabelCounts") or {},
        "descriptorScript4EncodedTargetKindCounts": descriptor_scripts.get("script4EncodedTargetKindCounts") or {},
        "descriptorScript4ContextA8NonPointerSetterRowCount": descriptor_scripts.get("script4ContextA8NonPointerSetterRowCount"),
        "descriptorScript4NonPointerBaseExpressions": descriptor_script4_non_pointer_bases,
        "descriptorAllScriptSpecificGateBaseProven": descriptor_scripts.get("allScriptsSpecificGateBaseProven"),
        "descriptorAllScriptGateWriterCount": descriptor_scripts.get("allScriptGateWriterCount"),
        "descriptorAllScriptGateReaderCount": descriptor_scripts.get("allScriptGateReaderCount"),
        "descriptorAllScriptSelectionOpcodeCount": descriptor_scripts.get("allScriptSelectionOpcodeCount"),
        "descriptorAllScriptFieldRecordCount": descriptor_scripts.get("allScriptFieldRecordCount"),
        "descriptorAllScriptCurrentFrontierDirectRefCount": descriptor_scripts.get(
            "allScriptCurrentFrontierDirectRefCount"
        ),
        "descriptorAllScriptEncodedTargetClassification": descriptor_scripts.get("allScriptEncodedTargetClassification"),
        "descriptorAllScriptEncodedTargetRawScalarCandidateCount": descriptor_scripts.get(
            "allScriptEncodedTargetRawScalarCandidateCount"
        ),
        "descriptorAllScriptEncodedTargetRouteProofRawScalarCandidateCount": descriptor_scripts.get(
            "allScriptEncodedTargetRouteProofRawScalarCandidateCount"
        ),
        "descriptorAllScriptEncodedTargetRouteContextRawScalarCandidateCount": descriptor_scripts.get(
            "allScriptEncodedTargetRouteContextRawScalarCandidateCount"
        ),
        "descriptorAllScriptEncodedTargetPromotingCandidateCount": descriptor_scripts.get(
            "allScriptEncodedTargetPromotingCandidateCount"
        ),
        "descriptorAllScriptEncodedTargetGroupCounts": descriptor_scripts.get("allScriptEncodedTargetGroupCounts") or {},
        "descriptorAllScriptEncodedTargetLabelCounts": descriptor_scripts.get("allScriptEncodedTargetLabelCounts") or {},
        "descriptorAllScriptEncodedTargetKindCounts": descriptor_scripts.get("allScriptEncodedTargetKindCounts") or {},
        "activeOrderAloneSufficientForGateProof": active_order_alone_sufficient,
        "activeOrderOnlyProofEliminated": active_order_alone_sufficient is False,
        "diagnosticActiveOrderEvidence": diagnostic_active_order,
        "diagnosticActiveOrderRecheckEvidence": diagnostic_active_order_recheck,
        "publicPredecessorActiveOrderEvidence": public_predecessor_active_order,
        "publicPredecessorLeftOverrunActiveOrderEvidence": public_predecessor_left_overrun_active_order,
        "opcode20ContextF2SourceEvidence": context_f2_source_evidence,
        "opcode20ContextF2ReferenceCount": context_f2_source_evidence.get("referenceCount"),
        "opcode20ContextF2ReadReferenceCount": context_f2_source_evidence.get("readReferenceCount"),
        "opcode20ContextF2WriteReferenceCount": context_f2_source_evidence.get("writeReferenceCount"),
        "opcode20ContextF2RuntimeObjectTableReaderCount": context_f2_source_evidence.get(
            "runtimeObjectTableReaderCount"
        ),
        "opcode20ContextF2DirectInitializerCount": context_f2_source_evidence.get(
            "directInitializerCount"
        ),
        "opcode20ContextF2CopyWriterCount": context_f2_source_evidence.get("copyWriterCount"),
        "opcode20ContextF2ConstantWriteCount": context_f2_source_evidence.get(
            "constantWriteCount"
        ),
        "opcode20ContextF2ObjectSelectorCount": context_f2_source_evidence.get(
            "contextF2ObjectSelectorCount"
        ),
        "opcode20ContextF2FixedStream2ObjectSelectorCount": context_f2_source_evidence.get(
            "fixedStream2ObjectSelectorCount"
        ),
        "opcode20ContextF2SpecificRuntimeObjectPointerProven": context_f2_source_evidence.get(
            "specificRuntimeObjectPointerProven"
        ),
        "opcode20ContextF2RuntimeObjectTableStateRequired": context_f2_source_evidence.get(
            "runtimeObjectTableStateRequired"
        ),
        "opcode20ContextF2DiagnosticRouteSampleCount": context_f2_source_evidence.get(
            "diagnosticRouteSampleCount"
        ),
        "opcode20ContextF2DiagnosticPromotionStatus": context_f2_source_evidence.get(
            "diagnosticPromotionStatus"
        ),
        "opcode20ContextF2PromotionStatus": context_f2_source_evidence.get("promotionStatus"),
        "gateOffsetSourceProofFound": gate_offset_sources.get("gateOffsetSourceProofFound"),
        "gateOffsetSourceFailedGateIds": gate_offset_sources.get("failedGateOffsetSourceGateIds") or [],
        "gateOffsetSourceEvidenceRefCount": gate_offset_sources.get("evidenceRefCount"),
        "gateOffsetPatternProofFound": gate_offset_patterns.get("gateOffsetPatternProofFound"),
        "gateOffsetPatternFailedGateIds": gate_offset_patterns.get("failedGateOffsetPatternGateIds") or [],
        "gateOffsetPatternEvidenceRefCount": gate_offset_patterns.get("evidenceRefCount"),
        "gateBaseCandidateProofFound": gate_base_candidates.get("gateBaseCandidateProofFound"),
        "gateBaseCandidateFailedGateIds": gate_base_candidates.get("failedGateBaseCandidateGateIds") or [],
        "gateBaseCandidateEvidenceRefCount": gate_base_candidates.get("evidenceRefCount"),
        "gateSampleValueProofFound": gate_sample_values.get("gateSampleValueProofFound"),
        "gateSampleValueFailedGateIds": gate_sample_values.get("failedGateSampleValueGateIds") or [],
        "gateSampleValueEvidenceRefCount": gate_sample_values.get("evidenceRefCount"),
        "selectionBufferBaseProofFound": selection_buffer_bases.get("selectionBufferBaseProofFound"),
        "selectionBufferBaseFailedGateIds": selection_buffer_bases.get("failedSelectionBufferBaseGateIds") or [],
        "selectionBufferBaseEvidenceRefCount": selection_buffer_bases.get("evidenceRefCount"),
        "opcode20ObjectBaseProofFound": opcode20_object_base_candidates.get("opcode20ObjectBaseProofFound"),
        "opcode20ObjectBaseFailedGateIds": (
            opcode20_object_base_candidates.get("failedOpcode20ObjectBaseGateIds") or []
        ),
        "opcode20ObjectBaseEvidenceRefCount": opcode20_object_base_candidates.get("evidenceRefCount"),
        "opcode20OrderSpaceProofFound": opcode20_order_space.get("opcode20OrderSpaceProofFound"),
        "opcode20OrderSpaceFailedGateIds": opcode20_order_space.get("failedOpcode20OrderSpaceGateIds") or [],
        "opcode20OrderSpaceEvidenceRefCount": opcode20_order_space.get("evidenceRefCount"),
        "opcode20SlotSourceProofFound": opcode20_slot_sources.get("opcode20SlotSourceProofFound"),
        "opcode20SlotSourceFailedGateIds": opcode20_slot_sources.get("failedOpcode20SlotSourceGateIds") or [],
        "opcode20SlotSourceEvidenceRefCount": opcode20_slot_sources.get("evidenceRefCount"),
        "opcode20DescriptorWriterProofFound": opcode20_slot_descriptor_writers.get(
            "opcode20DescriptorWriterProofFound"
        ),
        "opcode20DescriptorWriterFailedGateIds": (
            opcode20_slot_descriptor_writers.get("failedOpcode20DescriptorWriterGateIds") or []
        ),
        "opcode20DescriptorWriterEvidenceRefCount": opcode20_slot_descriptor_writers.get("evidenceRefCount"),
        "opcode20RuntimeMaterializerProofFound": opcode20_runtime_materializers.get(
            "opcode20RuntimeMaterializerProofFound"
        ),
        "opcode20RuntimeMaterializerFailedGateIds": (
            opcode20_runtime_materializers.get("failedOpcode20RuntimeMaterializerGateIds") or []
        ),
        "opcode20RuntimeMaterializerEvidenceRefCount": opcode20_runtime_materializers.get("evidenceRefCount"),
        "opcode20RuntimeMaterializerSelfMutationPathEliminated": opcode20_runtime_materializers.get(
            "opcode20SelfMutationPathEliminated"
        ),
        "opcode20RuntimeMaterializerCurrentFrontierActiveOrderProven": opcode20_runtime_materializers.get(
            "currentFrontierActiveOrderProven"
        ),
        "proofFound": proof_found,
        "gateBaseProofFound": proof_found,
        "activeOrderProofFound": active_order_proof_found,
        "gateTimeBaseProofFound": gate_time_base_proof_found,
        "predecessorPersistenceProofFound": predecessor_persistence_proof_found,
        "strictHotspotProofFound": strict_hotspot_proof_found,
        "failedGateBaseGateIds": failed_gate_base_gate_ids,
        "missingEvidence": missing_evidence,
        "sampleCurrentFrontierCovered": sample_order_effects.get("currentFrontierSampleCovered"),
        "sampleFinalNonPointerContextA8BaseHistogram": sample_order_effects.get("sampleFinalNonPointerContextA8BaseHistogram") or [],
        "gatePassIfSaveRuntimeBaseAndPredecessorState": (
            gate_pass_matrix.get("saveRuntimePredecessorAllGatePassSampleCount")
            == gate_pass_matrix.get("saveRuntimePredecessorSampleCount")
            and (gate_pass_matrix.get("saveRuntimePredecessorSampleCount") or 0) > 0
        ),
        "remainingProofs": [
            "prove opcode 0x20 runtime descriptor/base path before 0x005428c4; active order alone is insufficient",
            "prove predecessor 1:0 state persistence into current 2:0",
            "find strict map1_01a source hotspot or equivalent non-coordinate trigger",
        ],
        "evidenceRefs": evidence_refs,
        "evidenceRefCount": len(evidence_refs),
        "promotionStatus": "blocked",
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    diagnostic = summary.get("diagnosticActiveOrderEvidence") or {}
    diagnostic_recheck = summary.get("diagnosticActiveOrderRecheckEvidence") or {}
    public_predecessor = summary.get("publicPredecessorActiveOrderEvidence") or {}
    public_predecessor_left = summary.get("publicPredecessorLeftOverrunActiveOrderEvidence") or {}
    context_f2_source = summary.get("opcode20ContextF2SourceEvidence") or {}
    lines = [
        "# Save Selector Gate Base Proof Gap",
        "",
        f"- route: {summary['source']} -> {summary['target']}",
        f"- current writer: `{summary['currentWriterVaHex']}`",
        f"- gates: `{summary['firstGateVaHex']}`, `{summary['secondGateVaHex']}`",
        f"- writer stream start: `{summary['writerStreamStartHex']}`",
        f"- gate window base-setter candidates: {summary['gateWindowBaseSetterCandidateCount']}",
        f"- gate window only opcode 0x20 base candidate: {summary['gateWindowOnlyOpcode20BaseCandidate']}",
        f"- local base-affecting rows before gate: {summary['localBaseAffectingRowCount']}",
        f"- local direct base setters before gate: {summary['localDirectBaseSetterCount']}",
        f"- opcode 0x20 candidate: `{summary['opcode20CandidateVaHex']}`",
        f"- opcode 0x20 mode: {summary['opcode20CurrentMode']}",
        f"- opcode 0x20 handler signatures found: {summary['opcode20HandlerSignatureFoundCount']}/{summary['opcode20HandlerSignatureTotalCount']}",
        f"- opcode 0x20 nested dispatcher uses general table: {summary['opcode20NestedDispatcherUsesGeneralTable']}",
        f"- opcode 0x20 nested runner swaps context stream: {summary['opcode20NestedRunnerSwapsContextStream']}",
        f"- opcode 0x20 context+0xf2 refs/read/write: "
        f"{summary['opcode20ContextF2ReferenceCount']} / "
        f"{summary['opcode20ContextF2ReadReferenceCount']} / "
        f"{summary['opcode20ContextF2WriteReferenceCount']}",
        f"- opcode 0x20 context+0xf2 object selectors/fixed stream+2 selectors: "
        f"{summary['opcode20ContextF2ObjectSelectorCount']} / "
        f"{summary['opcode20ContextF2FixedStream2ObjectSelectorCount']}",
        f"- opcode 0x20 context+0xf2 runtime object pointer proven: "
        f"{summary['opcode20ContextF2SpecificRuntimeObjectPointerProven']}",
        f"- opcode 0x20 context+0xf2 runtime object-table state required: "
        f"{summary['opcode20ContextF2RuntimeObjectTableStateRequired']}",
        f"- gate offset source/pattern proof found: "
        f"{summary['gateOffsetSourceProofFound']} / {summary['gateOffsetPatternProofFound']}",
        f"- gate base candidate/sample proof found: "
        f"{summary['gateBaseCandidateProofFound']} / {summary['gateSampleValueProofFound']}",
        f"- selection-buffer base proof found: {summary['selectionBufferBaseProofFound']}",
        f"- opcode 0x20 object/order proof found: "
        f"{summary['opcode20ObjectBaseProofFound']} / {summary['opcode20OrderSpaceProofFound']}",
        f"- opcode 0x20 slot/descriptor-writer proof found: "
        f"{summary['opcode20SlotSourceProofFound']} / {summary['opcode20DescriptorWriterProofFound']}",
        f"- opcode 0x20 runtime materializer proof found: "
        f"{summary['opcode20RuntimeMaterializerProofFound']}",
        f"- opcode 0x20 self-mutation path eliminated: "
        f"{summary['opcode20RuntimeMaterializerSelfMutationPathEliminated']}",
        f"- descriptor+4 specific gate base proven: {summary['descriptorScript4SpecificGateBaseProven']}",
        f"- descriptor+4 gate writers/readers: {summary['descriptorScript4GateWriterCount']} / {summary['descriptorScript4GateReaderCount']}",
        f"- descriptor+4 field-map/current-frontier refs: {summary['descriptorScript4FieldRecordCount']} / {summary['descriptorScript4CurrentFrontierDirectRefCount']}",
        f"- descriptor+4 encoded route-target scalars: "
        f"{summary['descriptorScript4EncodedTargetRawScalarCandidateCount']} / "
        f"{summary['descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount']} / "
        f"{summary['descriptorScript4EncodedTargetPromotingCandidateCount']} "
        f"({summary['descriptorScript4EncodedTargetClassification']})",
        f"- descriptor+4 non-pointer context+0xa8 setters: {summary['descriptorScript4ContextA8NonPointerSetterRowCount']}",
        f"- all descriptor-script specific gate base proven: {summary['descriptorAllScriptSpecificGateBaseProven']}",
        f"- all descriptor-script gate writers/readers: {summary['descriptorAllScriptGateWriterCount']} / {summary['descriptorAllScriptGateReaderCount']}",
        f"- all descriptor-script selection-buffer opcode-shaped rows: {summary['descriptorAllScriptSelectionOpcodeCount']}",
        f"- all descriptor-script field-map/current-frontier refs: {summary['descriptorAllScriptFieldRecordCount']} / {summary['descriptorAllScriptCurrentFrontierDirectRefCount']}",
        f"- all descriptor-script encoded route-target scalars: "
        f"{summary['descriptorAllScriptEncodedTargetRawScalarCandidateCount']} / "
        f"{summary['descriptorAllScriptEncodedTargetRouteProofRawScalarCandidateCount']} / "
        f"{summary['descriptorAllScriptEncodedTargetPromotingCandidateCount']} "
        f"({summary['descriptorAllScriptEncodedTargetClassification']})",
        f"- active order alone sufficient for gate proof: {summary['activeOrderAloneSufficientForGateProof']}",
        f"- diagnostic active order available: {diagnostic.get('available')}",
        f"- diagnostic active order source: `{diagnostic.get('sourcePoll')}`",
        f"- diagnostic active order route proof: {not diagnostic.get('notRouteProof') if diagnostic.get('available') else False}",
        f"- diagnostic active order gate base proven: {diagnostic.get('gateBaseProven')}",
        f"- diagnostic active-order recheck status: `{diagnostic_recheck.get('promotionStatus')}`; reproduced={not diagnostic_recheck.get('notReproducedWithActiveOrderRecheck') if diagnostic_recheck.get('available') else False}",
        f"- diagnostic active-order recheck route hits: {diagnostic_recheck.get('routeSelectorHitCount')} / {diagnostic_recheck.get('recheckRouteSelectorHitCount')} / {diagnostic_recheck.get('activeOrderRecheckRouteSelectorHitCount')}",
        f"- diagnostic active-order recheck count: `{diagnostic_recheck.get('activeOrderRecheckActiveOrderCountValues')}`",
        f"- diagnostic active-order recheck gate base still unproven: {diagnostic_recheck.get('gateBaseStillUnproven')}",
        f"- public predecessor active order available: {public_predecessor.get('available')}",
        f"- public predecessor active order source: `{public_predecessor.get('sourcePoll')}`",
        f"- public predecessor active order route proof: "
        f"{not public_predecessor.get('notRouteProof') if public_predecessor.get('available') else False}",
        f"- public predecessor active order gate base proven: {public_predecessor.get('gateBaseProven')}",
        f"- public predecessor left-overrun active order available: {public_predecessor_left.get('available')}",
        f"- public predecessor left-overrun active order source: `{public_predecessor_left.get('sourcePoll')}`",
        f"- public predecessor left-overrun active order route proof: "
        f"{not public_predecessor_left.get('notRouteProof') if public_predecessor_left.get('available') else False}",
        f"- public predecessor left-overrun active order gate base proven: {public_predecessor_left.get('gateBaseProven')}",
        f"- proof found: {summary['proofFound']}",
        f"- gate base proof found: {summary['gateBaseProofFound']}",
        f"- active order proof found: {summary['activeOrderProofFound']}",
        f"- gate-time base proof found: {summary['gateTimeBaseProofFound']}",
        f"- failed gate-base gates: `{list_text(summary.get('failedGateBaseGateIds'))}`",
        f"- missing evidence count: {len(summary.get('missingEvidence') or [])}",
        f"- sample current frontier covered: {summary['sampleCurrentFrontierCovered']}",
        f"- gate pass if save/runtime base and predecessor state: {summary['gatePassIfSaveRuntimeBaseAndPredecessorState']}",
        f"- evidence refs: {summary['evidenceRefCount']}",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        summary["conclusion"],
        "",
        "## Missing Evidence",
        "",
        *[f"- {item}" for item in summary.get("missingEvidence") or []],
        "",
        "## Evidence Refs",
        "",
        "| path | fields |",
        "| --- | --- |",
    ]
    for ref in summary.get("evidenceRefs") or []:
        lines.append(
            f"| `{ref.get('path')}` | `{list_text(ref.get('fields'))}` |"
        )
    lines.extend([
        "",
        "## Local Base-Affecting Rows",
        "",
        "| va | value | opcode | kind | direct setter | meaning |",
        "| --- | --- | --- | --- | --- | --- |",
    ])
    for row in summary["localBaseAffectingRowsBeforeGate"]:
        lines.append(
            f"| `{row['vaHex']}` | `{row['valueHex']}` | `{row['opcodeHex']}` | "
            f"{row['kind']} | {row['directBaseSetter']} | {row['meaning']} |"
        )
    if not summary["localBaseAffectingRowsBeforeGate"]:
        lines.append("| - | - | - | - | - | - |")
    lines.extend([
        "",
        "## Gate Window Trace",
        "",
        "| va | value | opcode | handler | base candidate | writer | first gate | meaning |",
        "| --- | --- | --- | --- | --- | --- | --- | --- |",
    ])
    for row in summary["gateWindowRows"]:
        lines.append(
            f"| `{row['vaHex']}` | `{row['valueHex']}` | `{row['opcodeHex']}` | `{row['handlerVaHex']}` | "
            f"{row['isBaseSetterCandidate']} | {row['isWriter']} | {row['isFirstGate']} | "
            f"{row['meaning'] or '-'} |"
        )
    if not summary["gateWindowRows"]:
        lines.append("| - | - | - | - | - | - | - | - |")
    lines.extend([
        "",
        "## Descriptor+4 Static Gate Evidence",
        "",
        "| field-map records | current frontier refs | encoded raw/proof/promoting | gate writers | gate readers | non-pointer context+0xa8 setters | non-pointer bases | active order alone sufficient |",
        "| ---: | ---: | ---: | ---: | ---: | ---: | --- | --- |",
        f"| {summary['descriptorScript4FieldRecordCount']} | {summary['descriptorScript4CurrentFrontierDirectRefCount']} | "
        f"{summary['descriptorScript4EncodedTargetRawScalarCandidateCount']}/"
        f"{summary['descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount']}/"
        f"{summary['descriptorScript4EncodedTargetPromotingCandidateCount']} | "
        f"{summary['descriptorScript4GateWriterCount']} | {summary['descriptorScript4GateReaderCount']} | "
        f"{summary['descriptorScript4ContextA8NonPointerSetterRowCount']} | "
        f"`{', '.join(summary['descriptorScript4NonPointerBaseExpressions']) or '-'}` | "
        f"{summary['activeOrderAloneSufficientForGateProof']} |",
        "",
        "## Opcode 0x20 Context+0xf2 Source Evidence",
        "",
        "| artifact | refs/read/write | object readers | init/copy/constant writes | object selectors | fixed stream+2 selectors | current sample covered | pointer proven | runtime table required | diagnostic object table | status |",
        "| --- | ---: | ---: | ---: | ---: | ---: | --- | --- | --- | --- | --- |",
        f"| `{context_f2_source.get('sourceArtifact') or '-'}` | "
        f"{context_f2_source.get('referenceCount')} / "
        f"{context_f2_source.get('readReferenceCount')} / "
        f"{context_f2_source.get('writeReferenceCount')} | "
        f"{context_f2_source.get('runtimeObjectTableReaderCount')} | "
        f"{context_f2_source.get('directInitializerCount')} / "
        f"{context_f2_source.get('copyWriterCount')} / "
        f"{context_f2_source.get('constantWriteCount')} | "
        f"{context_f2_source.get('contextF2ObjectSelectorCount')} | "
        f"{context_f2_source.get('fixedStream2ObjectSelectorCount')} | "
        f"{context_f2_source.get('currentFrontierSampleCovered')} | "
        f"{context_f2_source.get('specificRuntimeObjectPointerProven')} | "
        f"{context_f2_source.get('runtimeObjectTableStateRequired')} | "
        f"{context_f2_source.get('diagnosticRouteSampleCount')}/"
        f"{context_f2_source.get('diagnosticTotalSampleCount')} "
        f"`{context_f2_source.get('diagnosticActiveOrderCountHex') or '-'}/"
        f"{','.join(context_f2_source.get('diagnosticActiveOrderHexes') or []) or '-'}` "
        f"{context_f2_source.get('diagnosticPromotionStatus')} | "
        f"{context_f2_source.get('promotionStatus')} |",
        "",
        "## Descriptor All-Slot Static Gate Evidence",
        "",
        "| field-map records | current frontier refs | encoded raw/proof/promoting | selection opcodes | gate writers | gate readers | specific gate base proven |",
        "| ---: | ---: | ---: | ---: | ---: | ---: | --- |",
        f"| {summary['descriptorAllScriptFieldRecordCount']} | "
        f"{summary['descriptorAllScriptCurrentFrontierDirectRefCount']} | "
        f"{summary['descriptorAllScriptEncodedTargetRawScalarCandidateCount']}/"
        f"{summary['descriptorAllScriptEncodedTargetRouteProofRawScalarCandidateCount']}/"
        f"{summary['descriptorAllScriptEncodedTargetPromotingCandidateCount']} | "
        f"{summary['descriptorAllScriptSelectionOpcodeCount']} | "
        f"{summary['descriptorAllScriptGateWriterCount']} | "
        f"{summary['descriptorAllScriptGateReaderCount']} | "
        f"{summary['descriptorAllScriptSpecificGateBaseProven']} |",
        "",
        "## Diagnostic Active-Order Gate Evidence",
        "",
        "| source poll | staged save | not route proof | active order | first descriptor | matches descriptor script | field/frontier refs | encoded raw/proof/promoting | gate writers/readers | non-pointer context+0xa8 setters | last context+0xa8 shape | gate base proven |",
        "| --- | --- | --- | --- | --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
        f"| `{diagnostic.get('sourcePoll') or '-'}` | {diagnostic.get('stagedSaveKind') or '-'} | "
        f"{diagnostic.get('notRouteProof')} | "
        f"`{diagnostic.get('activeOrderCountHex') or '-'}/"
        f"{','.join(diagnostic.get('activeOrderHexes') or []) or '-'}` | "
        f"`{diagnostic.get('firstDescriptorHex') or '-'}` | "
        f"{diagnostic.get('firstDescriptorMatchesScript')} | "
        f"{diagnostic.get('descriptorScript4FieldRecordCount')} / "
        f"{diagnostic.get('descriptorScript4CurrentFrontierDirectRefCount')} | "
        f"{diagnostic.get('descriptorScript4EncodedTargetRawScalarCandidateCount')} / "
        f"{diagnostic.get('descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount')} / "
        f"{diagnostic.get('descriptorScript4EncodedTargetPromotingCandidateCount')} | "
        f"{diagnostic.get('descriptorScript4GateWriterCount')} / "
        f"{diagnostic.get('descriptorScript4GateReaderCount')} | "
        f"{diagnostic.get('descriptorScript4ContextA8NonPointerSetterRowCount')} | "
        f"{diagnostic.get('descriptorScript4LastContextA8Shape') or '-'} | "
        f"{diagnostic.get('gateBaseProven')} |",
        "",
        "## Diagnostic Active-Order Recheck",
        "",
        "| stability poll | route hits | selector recheck | active-order recheck | active-order count | slot0 descriptor | reproduced | gate base still unproven |",
        "| --- | ---: | --- | --- | --- | --- | --- | --- |",
        f"| `{diagnostic_recheck.get('sourcePoll') or '-'}` | "
        f"{diagnostic_recheck.get('routeSelectorHitCount')} | "
        f"`{diagnostic_recheck.get('recheckSourcePoll') or '-'}` "
        f"{diagnostic_recheck.get('recheckRouteSelectorHitCount')} hits / "
        f"{','.join(diagnostic_recheck.get('recheckObservedSelectors') or []) or '-'} | "
        f"`{diagnostic_recheck.get('activeOrderRecheckSourcePoll') or '-'}` "
        f"{diagnostic_recheck.get('activeOrderRecheckRouteSelectorHitCount')} hits / "
        f"{','.join(diagnostic_recheck.get('activeOrderRecheckObservedSelectors') or []) or '-'} | "
        f"`{diagnostic_recheck.get('activeOrderRecheckActiveOrderCountValues') or '-'}` | "
        f"`{diagnostic_recheck.get('activeOrderRecheckSlot0DescriptorValues') or '-'}` | "
        f"{not diagnostic_recheck.get('notReproducedWithActiveOrderRecheck') if diagnostic_recheck.get('available') else False} | "
        f"{diagnostic_recheck.get('gateBaseStillUnproven')} |",
        "",
        "## Public Predecessor Active-Order Gate Evidence",
        "",
        "| source poll | staged save | not route proof | samples | active order | first descriptor runtime/static | runtime slot base table0 | runtime object table | stable | field/frontier refs | encoded raw/proof/promoting | gate writers/readers | non-pointer context+0xa8 setters | last context+0xa8 shape | gate base proven |",
        "| --- | --- | --- | ---: | --- | --- | --- | --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
        f"| `{public_predecessor.get('sourcePoll') or '-'}` | "
        f"{public_predecessor.get('stagedSaveKind') or '-'} | "
        f"{public_predecessor.get('notRouteProof')} | "
        f"{public_predecessor.get('sampleCount')}/"
        f"{public_predecessor.get('totalSampleCount')} | "
        f"`{public_predecessor.get('activeOrderCountHex') or '-'}/"
        f"{','.join(public_predecessor.get('activeOrderHexes') or []) or '-'}` | "
        f"`{public_predecessor.get('firstDescriptorRuntimeHex') or '-'}/"
        f"{public_predecessor.get('firstDescriptorHex') or '-'}` | "
        f"`{public_predecessor.get('runtimeSlotBaseTable0Hex') or '-'}` | "
        f"`{','.join(public_predecessor.get('runtimeObjectTableHexes') or []) or '-'}` | "
        f"{public_predecessor.get('allPublicWatchedValuesStable')} | "
        f"{public_predecessor.get('descriptorScript4FieldRecordCount')} / "
        f"{public_predecessor.get('descriptorScript4CurrentFrontierDirectRefCount')} | "
        f"{public_predecessor.get('descriptorScript4EncodedTargetRawScalarCandidateCount')} / "
        f"{public_predecessor.get('descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount')} / "
        f"{public_predecessor.get('descriptorScript4EncodedTargetPromotingCandidateCount')} | "
        f"{public_predecessor.get('descriptorScript4GateWriterCount')} / "
        f"{public_predecessor.get('descriptorScript4GateReaderCount')} | "
        f"{public_predecessor.get('descriptorScript4ContextA8NonPointerSetterRowCount')} | "
        f"{public_predecessor.get('descriptorScript4LastContextA8Shape') or '-'} | "
        f"{public_predecessor.get('gateBaseProven')} |",
        "",
        "## Public Predecessor Left-Overrun Active-Order Gate Evidence",
        "",
        "| source poll | staged save | not route proof | samples | active order | first descriptor runtime/static | runtime slot base table0 | runtime object table | stable | field/frontier refs | encoded raw/proof/promoting | gate writers/readers | non-pointer context+0xa8 setters | last context+0xa8 shape | gate base proven |",
        "| --- | --- | --- | ---: | --- | --- | --- | --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
        f"| `{public_predecessor_left.get('sourcePoll') or '-'}` | "
        f"{public_predecessor_left.get('stagedSaveKind') or '-'} | "
        f"{public_predecessor_left.get('notRouteProof')} | "
        f"{public_predecessor_left.get('sampleCount')}/"
        f"{public_predecessor_left.get('totalSampleCount')} | "
        f"`{public_predecessor_left.get('activeOrderCountHex') or '-'}/"
        f"{','.join(public_predecessor_left.get('activeOrderHexes') or []) or '-'}` | "
        f"`{public_predecessor_left.get('firstDescriptorRuntimeHex') or '-'}/"
        f"{public_predecessor_left.get('firstDescriptorHex') or '-'}` | "
        f"`{public_predecessor_left.get('runtimeSlotBaseTable0Hex') or '-'}` | "
        f"`{','.join(public_predecessor_left.get('runtimeObjectTableHexes') or []) or '-'}` | "
        f"{public_predecessor_left.get('allPublicWatchedValuesStable')} | "
        f"{public_predecessor_left.get('descriptorScript4FieldRecordCount')} / "
        f"{public_predecessor_left.get('descriptorScript4CurrentFrontierDirectRefCount')} | "
        f"{public_predecessor_left.get('descriptorScript4EncodedTargetRawScalarCandidateCount')} / "
        f"{public_predecessor_left.get('descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount')} / "
        f"{public_predecessor_left.get('descriptorScript4EncodedTargetPromotingCandidateCount')} | "
        f"{public_predecessor_left.get('descriptorScript4GateWriterCount')} / "
        f"{public_predecessor_left.get('descriptorScript4GateReaderCount')} | "
        f"{public_predecessor_left.get('descriptorScript4ContextA8NonPointerSetterRowCount')} | "
        f"{public_predecessor_left.get('descriptorScript4LastContextA8Shape') or '-'} | "
        f"{public_predecessor_left.get('gateBaseProven')} |",
        "",
        "## Sample Non-Pointer Context+0xa8 Base Histogram",
        "",
        "| base expression | sample count |",
        "| --- | ---: |",
    ])
    for row in summary["sampleFinalNonPointerContextA8BaseHistogram"]:
        lines.append(f"| `{row['value']}` | {row['count']} |")
    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:
    diagnostic = summary.get("diagnosticActiveOrderEvidence") or {}
    diagnostic_recheck = summary.get("diagnosticActiveOrderRecheckEvidence") or {}
    public_predecessor = summary.get("publicPredecessorActiveOrderEvidence") or {}
    public_predecessor_left = summary.get("publicPredecessorLeftOverrunActiveOrderEvidence") or {}
    context_f2_source = summary.get("opcode20ContextF2SourceEvidence") or {}
    local_rows = []
    for row in summary["localBaseAffectingRowsBeforeGate"]:
        local_rows.append(
            "<tr>"
            f"<td><code>{html.escape(row['vaHex'])}</code></td>"
            f"<td><code>{html.escape(row['valueHex'])}</code></td>"
            f"<td><code>{html.escape(row['opcodeHex'])}</code></td>"
            f"<td>{html.escape(row['kind'])}</td>"
            f"<td>{row['directBaseSetter']}</td>"
            f"<td>{html.escape(row['meaning'])}</td>"
            "</tr>"
        )
    if not local_rows:
        local_rows.append("<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>")
    gate_rows = []
    for row in summary["gateWindowRows"]:
        gate_rows.append(
            "<tr>"
            f"<td><code>{html.escape(row['vaHex'] or '-')}</code></td>"
            f"<td><code>{html.escape(row['valueHex'] or '-')}</code></td>"
            f"<td><code>{html.escape(row['opcodeHex'] or '-')}</code></td>"
            f"<td><code>{html.escape(row['handlerVaHex'] or '-')}</code></td>"
            f"<td>{row['isBaseSetterCandidate']}</td>"
            f"<td>{row['isWriter']}</td>"
            f"<td>{row['isFirstGate']}</td>"
            f"<td>{html.escape(row['meaning'] or '-')}</td>"
            "</tr>"
        )
    if not gate_rows:
        gate_rows.append("<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>")
    sample_rows = [
        f"<tr><td><code>{html.escape(row['value'])}</code></td><td>{row['count']}</td></tr>"
        for row in summary["sampleFinalNonPointerContextA8BaseHistogram"]
    ]
    evidence_ref_rows = [
        "<tr>"
        f"<td><code>{html.escape(ref.get('path') or '-')}</code></td>"
        f"<td><code>{html.escape(list_text(ref.get('fields')))}</code></td>"
        "</tr>"
        for ref in summary.get("evidenceRefs") or []
    ]
    if not evidence_ref_rows:
        evidence_ref_rows.append('<tr><td colspan="2">No evidence refs recorded.</td></tr>')
    descriptor_bases = ", ".join(summary["descriptorScript4NonPointerBaseExpressions"]) or "-"
    proofs = "".join(f"<li>{html.escape(item)}</li>" for item in summary["remainingProofs"])
    missing_items = "".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or []
    )
    diagnostic_order = (
        f"{diagnostic.get('activeOrderCountHex') or '-'}/"
        f"{','.join(diagnostic.get('activeOrderHexes') or []) or '-'}"
    )
    public_predecessor_order = (
        f"{public_predecessor.get('activeOrderCountHex') or '-'}/"
        f"{','.join(public_predecessor.get('activeOrderHexes') or []) or '-'}"
    )
    public_predecessor_left_order = (
        f"{public_predecessor_left.get('activeOrderCountHex') or '-'}/"
        f"{','.join(public_predecessor_left.get('activeOrderHexes') or []) or '-'}"
    )
    return "\n".join([
        "<!doctype html>",
        '<html lang="en">',
        "<head>",
        '  <meta charset="utf-8">',
        '  <meta name="viewport" content="width=device-width, initial-scale=1">',
        "  <title>Save Selector Gate Base Proof Gap</title>",
        "  <style>",
        "    :root { color-scheme: dark; font-family: system-ui, sans-serif; background: #101010; color: #eee; }",
        "    body { margin: 0; padding: 24px; }",
        "    h1 { margin: 0 0 8px; font-size: 24px; }",
        "    h2 { margin: 24px 0 8px; font-size: 18px; }",
        "    p { max-width: 1120px; color: #bbb; line-height: 1.45; }",
        "    table { width: 100%; border-collapse: collapse; margin: 12px 0 20px; font-size: 13px; }",
        "    th, td { border-bottom: 1px solid #303030; padding: 7px 8px; text-align: left; vertical-align: top; }",
        "    th { position: sticky; top: 0; background: #181818; color: #ddd; }",
        "    code { color: #d7f0ff; }",
        "  </style>",
        "</head>",
        "<body>",
        "  <h1>Save Selector Gate Base Proof Gap</h1>",
        f"  <p>route {html.escape(summary['source'])} -&gt; {html.escape(summary['target'])}; "
        f"current writer <code>{html.escape(summary['currentWriterVaHex'])}</code>; "
        f"opcode 0x20 candidate <code>{html.escape(summary['opcode20CandidateVaHex'] or '-')}</code>; "
        f"handler signatures {summary['opcode20HandlerSignatureFoundCount']}/{summary['opcode20HandlerSignatureTotalCount']}; "
        f"nested dispatcher uses general table {summary['opcode20NestedDispatcherUsesGeneralTable']}; "
        f"nested runner swaps context stream {summary['opcode20NestedRunnerSwapsContextStream']}; "
        f"context+0xf2 refs/read/write {summary['opcode20ContextF2ReferenceCount']}/"
        f"{summary['opcode20ContextF2ReadReferenceCount']}/"
        f"{summary['opcode20ContextF2WriteReferenceCount']}; "
        f"context+0xf2 object selectors {summary['opcode20ContextF2ObjectSelectorCount']}; "
        f"context+0xf2 runtime table required {summary['opcode20ContextF2RuntimeObjectTableStateRequired']}; "
        f"local direct base setters before gate {summary['localDirectBaseSetterCount']}; "
        f"descriptor+4 specific gate base proven {summary['descriptorScript4SpecificGateBaseProven']}; "
        f"descriptor+4 encoded route-target scalars "
        f"{summary['descriptorScript4EncodedTargetRawScalarCandidateCount']}/"
        f"{summary['descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount']}/"
        f"{summary['descriptorScript4EncodedTargetPromotingCandidateCount']}; "
        f"all descriptor-script gate writers/readers {summary['descriptorAllScriptGateWriterCount']}/"
        f"{summary['descriptorAllScriptGateReaderCount']}; "
        f"all descriptor-script selection-buffer opcode-shaped rows {summary['descriptorAllScriptSelectionOpcodeCount']}; "
        f"all descriptor-script encoded route-target scalars "
        f"{summary['descriptorAllScriptEncodedTargetRawScalarCandidateCount']}/"
        f"{summary['descriptorAllScriptEncodedTargetRouteProofRawScalarCandidateCount']}/"
        f"{summary['descriptorAllScriptEncodedTargetPromotingCandidateCount']}; "
        f"all descriptor-script specific gate base proven {summary['descriptorAllScriptSpecificGateBaseProven']}; "
        f"diagnostic active order gate base proven {diagnostic.get('gateBaseProven')}; "
        f"diagnostic active-order recheck route hits "
        f"{diagnostic_recheck.get('routeSelectorHitCount')}/"
        f"{diagnostic_recheck.get('recheckRouteSelectorHitCount')}/"
        f"{diagnostic_recheck.get('activeOrderRecheckRouteSelectorHitCount')}; "
        f"diagnostic active-order recheck count {html.escape(str(diagnostic_recheck.get('activeOrderRecheckActiveOrderCountValues')))}; "
        f"diagnostic active-order recheck gate base still unproven {diagnostic_recheck.get('gateBaseStillUnproven')}; "
        f"public predecessor active order gate base proven {public_predecessor.get('gateBaseProven')}; "
        f"public predecessor left-overrun active order gate base proven {public_predecessor_left.get('gateBaseProven')}; "
        f"proof found {summary['proofFound']}; "
        f"gate base proof found {summary['gateBaseProofFound']}; "
        f"active order proof found {summary['activeOrderProofFound']}; "
        f"gate-time base proof found {summary['gateTimeBaseProofFound']}; "
        f"failed gate-base gates <code>{html.escape(list_text(summary.get('failedGateBaseGateIds')))}</code>; "
        f"missing evidence count {len(summary.get('missingEvidence') or [])}; "
        f"evidence refs {summary.get('evidenceRefCount')}; "
        f"gate pass if save/runtime base and predecessor state {summary['gatePassIfSaveRuntimeBaseAndPredecessorState']}; "
        f"promotion status <code>{html.escape(summary['promotionStatus'])}</code>.</p>",
        f"  <p>{html.escape(summary['conclusion'])}</p>",
        "  <h2>Missing Evidence</h2>",
        f"  <ul>{missing_items}</ul>",
        "  <h2>Evidence Refs</h2>",
        "  <table><thead><tr><th>path</th><th>fields</th></tr></thead><tbody>",
        *evidence_ref_rows,
        "  </tbody></table>",
        "  <h2>Local Base-Affecting Rows</h2>",
        "  <table><thead><tr><th>va</th><th>value</th><th>opcode</th><th>kind</th><th>direct setter</th><th>meaning</th></tr></thead><tbody>",
        *local_rows,
        "  </tbody></table>",
        "  <h2>Gate Window Trace</h2>",
        "  <p>The gate window trace shows that between opcode 0x20 and the first 0xe8 gate, the gate window only opcode 0x20 base candidate flag is true.</p>",
        "  <table><thead><tr><th>va</th><th>value</th><th>opcode</th><th>handler</th><th>base candidate</th><th>writer</th><th>first gate</th><th>meaning</th></tr></thead><tbody>",
        *gate_rows,
        "  </tbody></table>",
        "  <h2>Descriptor+4 Static Gate Evidence</h2>",
        "  <p>descriptor+4 field-map/current-frontier refs and gate offset rows are kept separate from active order alone sufficient for gate proof.</p>",
        "  <table><thead><tr><th>field-map records</th><th>current frontier refs</th><th>encoded raw/proof/promoting</th><th>gate writers</th><th>gate readers</th><th>non-pointer context+0xa8 setters</th><th>non-pointer bases</th><th>active order alone sufficient</th></tr></thead><tbody>",
        "    <tr>"
        f"<td>{summary['descriptorScript4FieldRecordCount']}</td>"
        f"<td>{summary['descriptorScript4CurrentFrontierDirectRefCount']}</td>"
        f"<td>{summary['descriptorScript4EncodedTargetRawScalarCandidateCount']}/"
        f"{summary['descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount']}/"
        f"{summary['descriptorScript4EncodedTargetPromotingCandidateCount']}</td>"
        f"<td>{summary['descriptorScript4GateWriterCount']}</td>"
        f"<td>{summary['descriptorScript4GateReaderCount']}</td>"
        f"<td>{summary['descriptorScript4ContextA8NonPointerSetterRowCount']}</td>"
        f"<td><code>{html.escape(descriptor_bases)}</code></td>"
        f"<td>{summary['activeOrderAloneSufficientForGateProof']}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Opcode 0x20 Context+0xf2 Source Evidence</h2>",
        "  <p>The context+0xf2 source scan is kept inside this gate-base proof so the non-pointer context+0xa8 rows cannot be read as fixed route bases.</p>",
        "  <table><thead><tr><th>artifact</th><th>refs/read/write</th><th>object readers</th><th>init/copy/constant writes</th><th>object selectors</th><th>fixed stream+2 selectors</th><th>current sample covered</th><th>pointer proven</th><th>runtime table required</th><th>diagnostic object table</th><th>status</th></tr></thead><tbody>",
        "    <tr>"
        f"<td><code>{html.escape(context_f2_source.get('sourceArtifact') or '-')}</code></td>"
        f"<td>{context_f2_source.get('referenceCount')} / "
        f"{context_f2_source.get('readReferenceCount')} / "
        f"{context_f2_source.get('writeReferenceCount')}</td>"
        f"<td>{context_f2_source.get('runtimeObjectTableReaderCount')}</td>"
        f"<td>{context_f2_source.get('directInitializerCount')} / "
        f"{context_f2_source.get('copyWriterCount')} / "
        f"{context_f2_source.get('constantWriteCount')}</td>"
        f"<td>{context_f2_source.get('contextF2ObjectSelectorCount')}</td>"
        f"<td>{context_f2_source.get('fixedStream2ObjectSelectorCount')}</td>"
        f"<td>{context_f2_source.get('currentFrontierSampleCovered')}</td>"
        f"<td>{context_f2_source.get('specificRuntimeObjectPointerProven')}</td>"
        f"<td>{context_f2_source.get('runtimeObjectTableStateRequired')}</td>"
        f"<td>{context_f2_source.get('diagnosticRouteSampleCount')}/"
        f"{context_f2_source.get('diagnosticTotalSampleCount')} "
        f"<code>{html.escape(context_f2_source.get('diagnosticActiveOrderCountHex') or '-')}/"
        f"{html.escape(','.join(context_f2_source.get('diagnosticActiveOrderHexes') or []) or '-')}</code> "
        f"{context_f2_source.get('diagnosticPromotionStatus')}</td>"
        f"<td>{context_f2_source.get('promotionStatus')}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Descriptor All-Slot Static Gate Evidence</h2>",
        "  <p>descriptor+0, descriptor+4, and descriptor+8 are scanned together to rule out a gate-offset row hiding in another descriptor script slot.</p>",
        "  <table><thead><tr><th>field-map records</th><th>current frontier refs</th><th>encoded raw/proof/promoting</th><th>selection opcodes</th><th>gate writers</th><th>gate readers</th><th>specific gate base proven</th></tr></thead><tbody>",
        "    <tr>"
        f"<td>{summary['descriptorAllScriptFieldRecordCount']}</td>"
        f"<td>{summary['descriptorAllScriptCurrentFrontierDirectRefCount']}</td>"
        f"<td>{summary['descriptorAllScriptEncodedTargetRawScalarCandidateCount']}/"
        f"{summary['descriptorAllScriptEncodedTargetRouteProofRawScalarCandidateCount']}/"
        f"{summary['descriptorAllScriptEncodedTargetPromotingCandidateCount']}</td>"
        f"<td>{summary['descriptorAllScriptSelectionOpcodeCount']}</td>"
        f"<td>{summary['descriptorAllScriptGateWriterCount']}</td>"
        f"<td>{summary['descriptorAllScriptGateReaderCount']}</td>"
        f"<td>{summary['descriptorAllScriptSpecificGateBaseProven']}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Diagnostic Active-Order Gate Evidence</h2>",
        "  <p>The diagnostic active order came from a patched public-base save load, so it is diagnostic active order evidence and not route proof.</p>",
        "  <table><thead><tr><th>source poll</th><th>staged save</th><th>not route proof</th><th>active order</th><th>first descriptor</th><th>matches script</th><th>field/frontier refs</th><th>encoded raw/proof/promoting</th><th>gate writers/readers</th><th>non-pointer context+0xa8 setters</th><th>last context+0xa8 shape</th><th>gate base proven</th></tr></thead><tbody>",
        "    <tr>"
        f"<td><code>{html.escape(diagnostic.get('sourcePoll') or '-')}</code></td>"
        f"<td>{html.escape(diagnostic.get('stagedSaveKind') or '-')}</td>"
        f"<td>{diagnostic.get('notRouteProof')}</td>"
        f"<td><code>{html.escape(diagnostic_order)}</code></td>"
        f"<td><code>{html.escape(diagnostic.get('firstDescriptorHex') or '-')}</code></td>"
        f"<td>{diagnostic.get('firstDescriptorMatchesScript')}</td>"
        f"<td>{diagnostic.get('descriptorScript4FieldRecordCount')} / "
        f"{diagnostic.get('descriptorScript4CurrentFrontierDirectRefCount')}</td>"
        f"<td>{diagnostic.get('descriptorScript4EncodedTargetRawScalarCandidateCount')} / "
        f"{diagnostic.get('descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount')} / "
        f"{diagnostic.get('descriptorScript4EncodedTargetPromotingCandidateCount')}</td>"
        f"<td>{diagnostic.get('descriptorScript4GateWriterCount')} / "
        f"{diagnostic.get('descriptorScript4GateReaderCount')}</td>"
        f"<td>{diagnostic.get('descriptorScript4ContextA8NonPointerSetterRowCount')}</td>"
        f"<td>{html.escape(diagnostic.get('descriptorScript4LastContextA8Shape') or '-')}</td>"
        f"<td>{diagnostic.get('gateBaseProven')}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Diagnostic Active-Order Recheck</h2>",
        "  <p>The selector-only and active-order rechecks are kept separate from the first constructed left-route hit.</p>",
        "  <table><thead><tr><th>stability poll</th><th>route hits</th><th>selector recheck</th><th>active-order recheck</th><th>active-order count</th><th>slot0 descriptor</th><th>reproduced</th><th>gate base still unproven</th></tr></thead><tbody>",
        "    <tr>"
        f"<td><code>{html.escape(diagnostic_recheck.get('sourcePoll') or '-')}</code></td>"
        f"<td>{diagnostic_recheck.get('routeSelectorHitCount')}</td>"
        f"<td><code>{html.escape(diagnostic_recheck.get('recheckSourcePoll') or '-')}</code> "
        f"{diagnostic_recheck.get('recheckRouteSelectorHitCount')} hits / "
        f"<code>{html.escape(','.join(diagnostic_recheck.get('recheckObservedSelectors') or []) or '-')}</code></td>"
        f"<td><code>{html.escape(diagnostic_recheck.get('activeOrderRecheckSourcePoll') or '-')}</code> "
        f"{diagnostic_recheck.get('activeOrderRecheckRouteSelectorHitCount')} hits / "
        f"<code>{html.escape(','.join(diagnostic_recheck.get('activeOrderRecheckObservedSelectors') or []) or '-')}</code></td>"
        f"<td><code>{html.escape(diagnostic_recheck.get('activeOrderRecheckActiveOrderCountValues') or '-')}</code></td>"
        f"<td><code>{html.escape(diagnostic_recheck.get('activeOrderRecheckSlot0DescriptorValues') or '-')}</code></td>"
        f"<td>{not diagnostic_recheck.get('notReproducedWithActiveOrderRecheck') if diagnostic_recheck.get('available') else False}</td>"
        f"<td>{diagnostic_recheck.get('gateBaseStillUnproven')}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Public Predecessor Active-Order Gate Evidence</h2>",
        "  <p>The public predecessor active order came from the real public savedat direction sweep. It reaches selector 1:0 but not selector 2:0 or the route context.</p>",
        "  <table><thead><tr><th>source poll</th><th>staged save</th><th>not route proof</th><th>samples</th><th>active order</th><th>first descriptor runtime/static</th><th>runtime slot base table0</th><th>runtime object table</th><th>stable</th><th>field/frontier refs</th><th>encoded raw/proof/promoting</th><th>gate writers/readers</th><th>non-pointer context+0xa8 setters</th><th>last context+0xa8 shape</th><th>gate base proven</th></tr></thead><tbody>",
        "    <tr>"
        f"<td><code>{html.escape(public_predecessor.get('sourcePoll') or '-')}</code></td>"
        f"<td>{html.escape(public_predecessor.get('stagedSaveKind') or '-')}</td>"
        f"<td>{public_predecessor.get('notRouteProof')}</td>"
        f"<td>{public_predecessor.get('sampleCount')}/{public_predecessor.get('totalSampleCount')}</td>"
        f"<td><code>{html.escape(public_predecessor_order)}</code></td>"
        f"<td><code>{html.escape(public_predecessor.get('firstDescriptorRuntimeHex') or '-')} / "
        f"{html.escape(public_predecessor.get('firstDescriptorHex') or '-')}</code></td>"
        f"<td><code>{html.escape(public_predecessor.get('runtimeSlotBaseTable0Hex') or '-')}</code></td>"
        f"<td><code>{html.escape(','.join(public_predecessor.get('runtimeObjectTableHexes') or []) or '-')}</code></td>"
        f"<td>{public_predecessor.get('allPublicWatchedValuesStable')}</td>"
        f"<td>{public_predecessor.get('descriptorScript4FieldRecordCount')} / "
        f"{public_predecessor.get('descriptorScript4CurrentFrontierDirectRefCount')}</td>"
        f"<td>{public_predecessor.get('descriptorScript4EncodedTargetRawScalarCandidateCount')} / "
        f"{public_predecessor.get('descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount')} / "
        f"{public_predecessor.get('descriptorScript4EncodedTargetPromotingCandidateCount')}</td>"
        f"<td>{public_predecessor.get('descriptorScript4GateWriterCount')} / "
        f"{public_predecessor.get('descriptorScript4GateReaderCount')}</td>"
        f"<td>{public_predecessor.get('descriptorScript4ContextA8NonPointerSetterRowCount')}</td>"
        f"<td>{html.escape(public_predecessor.get('descriptorScript4LastContextA8Shape') or '-')}</td>"
        f"<td>{public_predecessor.get('gateBaseProven')}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Public Predecessor Left-Overrun Active-Order Gate Evidence</h2>",
        "  <p>The left-overrun activation sweep is a second public predecessor calibration run. It reaches selector 1:0 but not selector 2:0 or the current root.</p>",
        "  <table><thead><tr><th>source poll</th><th>staged save</th><th>not route proof</th><th>samples</th><th>active order</th><th>first descriptor runtime/static</th><th>runtime slot base table0</th><th>runtime object table</th><th>stable</th><th>field/frontier refs</th><th>encoded raw/proof/promoting</th><th>gate writers/readers</th><th>non-pointer context+0xa8 setters</th><th>last context+0xa8 shape</th><th>gate base proven</th></tr></thead><tbody>",
        "    <tr>"
        f"<td><code>{html.escape(public_predecessor_left.get('sourcePoll') or '-')}</code></td>"
        f"<td>{html.escape(public_predecessor_left.get('stagedSaveKind') or '-')}</td>"
        f"<td>{public_predecessor_left.get('notRouteProof')}</td>"
        f"<td>{public_predecessor_left.get('sampleCount')}/{public_predecessor_left.get('totalSampleCount')}</td>"
        f"<td><code>{html.escape(public_predecessor_left_order)}</code></td>"
        f"<td><code>{html.escape(public_predecessor_left.get('firstDescriptorRuntimeHex') or '-')} / "
        f"{html.escape(public_predecessor_left.get('firstDescriptorHex') or '-')}</code></td>"
        f"<td><code>{html.escape(public_predecessor_left.get('runtimeSlotBaseTable0Hex') or '-')}</code></td>"
        f"<td><code>{html.escape(','.join(public_predecessor_left.get('runtimeObjectTableHexes') or []) or '-')}</code></td>"
        f"<td>{public_predecessor_left.get('allPublicWatchedValuesStable')}</td>"
        f"<td>{public_predecessor_left.get('descriptorScript4FieldRecordCount')} / "
        f"{public_predecessor_left.get('descriptorScript4CurrentFrontierDirectRefCount')}</td>"
        f"<td>{public_predecessor_left.get('descriptorScript4EncodedTargetRawScalarCandidateCount')} / "
        f"{public_predecessor_left.get('descriptorScript4EncodedTargetRouteProofRawScalarCandidateCount')} / "
        f"{public_predecessor_left.get('descriptorScript4EncodedTargetPromotingCandidateCount')}</td>"
        f"<td>{public_predecessor_left.get('descriptorScript4GateWriterCount')} / "
        f"{public_predecessor_left.get('descriptorScript4GateReaderCount')}</td>"
        f"<td>{public_predecessor_left.get('descriptorScript4ContextA8NonPointerSetterRowCount')}</td>"
        f"<td>{html.escape(public_predecessor_left.get('descriptorScript4LastContextA8Shape') or '-')}</td>"
        f"<td>{public_predecessor_left.get('gateBaseProven')}</td>"
        "</tr>",
        "  </tbody></table>",
        "  <h2>Sample Non-Pointer Context+0xa8 Base Histogram</h2>",
        "  <table><thead><tr><th>base expression</th><th>sample count</th></tr></thead><tbody>",
        *sample_rows,
        "  </tbody></table>",
        "  <h2>Remaining Proofs</h2>",
        f"  <ul>{proofs}</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_gate_base_proof_gap.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    (out_dir / "save_selector_gate_base_proof_gap.html").write_text(html_page(summary), encoding="utf-8")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--current-writer-paths", type=Path, default=OUT / "save_selector_current_writer_paths.json")
    parser.add_argument("--opcode20-nested", type=Path, default=OUT / "save_selector_opcode20_nested_base_modes.json")
    parser.add_argument("--descriptor-scripts", type=Path, default=OUT / "save_selector_opcode20_descriptor_scripts.json")
    parser.add_argument("--sample-order-effects", type=Path, default=OUT / "save_selector_opcode20_sample_order_effects.json")
    parser.add_argument("--gate-pass-matrix", type=Path, default=OUT / "save_selector_gate_pass_matrix.json")
    parser.add_argument(
        "--runtime-patched-selector-followup-context",
        type=Path,
        default=OUT / "runtime_patched_selector_followup_context.json",
    )
    parser.add_argument(
        "--runtime-predecessor-active-order-poll",
        type=Path,
        default=OUT / PUBLIC_PREDECESSOR_ACTIVE_ORDER_POLL,
    )
    parser.add_argument(
        "--runtime-predecessor-left-overrun-active-order-poll",
        type=Path,
        default=OUT / PUBLIC_PREDECESSOR_LEFT_OVERRUN_ACTIVE_ORDER_POLL,
    )
    parser.add_argument(
        "--opcode20-context-f2-sources",
        type=Path,
        default=OUT / "save_selector_opcode20_context_f2_sources.json",
    )
    parser.add_argument("--out-dir", type=Path, default=OUT)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.current_writer_paths, []),
        load_json(args.opcode20_nested, {}),
        load_json(args.descriptor_scripts, {}),
        load_json(args.sample_order_effects, {}),
        load_json(args.gate_pass_matrix, {}),
        load_json(args.runtime_patched_selector_followup_context, {}),
        load_json(args.runtime_predecessor_active_order_poll, {}),
        load_json(args.runtime_predecessor_left_overrun_active_order_poll, {}),
        load_json(args.opcode20_context_f2_sources, {}),
    )
    write_outputs(summary, args.out_dir)
    print(f"wrote save selector gate base proof gap -> {args.out_dir / 'save_selector_gate_base_proof_gap.html'}")


if __name__ == "__main__":
    main()
