#!/usr/bin/env python3
"""Consolidate the predecessor fill-site execution/order gap."""
from __future__ import annotations

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

from probe_exe_scene_tables import find_cns_strings, read_sections, va_to_offset
from summarize_save_selector_stream_traces import byte_at, handler_entry, trace_stream, u32_at


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"
RAW_GENERIC_MAX_BYTES = 0x400
RAW_GENERIC_CALLEE_MAX_BYTES = 0x300
RAW_GENERIC_CALL_GRAPH_MAX_DEPTH = 3
RAW_GENERIC_CALL_GRAPH_DEPTH_SENSITIVITY_DEPTHS = [1, 2, 3, 4, 5, 6]


RAW_GENERIC_STATIC_TARGETS = [
    ("wrapper-leaf", 0x00542A04, "current"),
    ("frontier-leaf", 0x00542AE8, "current"),
    ("source-record", 0x00542B44, "route-record"),
    ("target-record", 0x00542BAC, "route-record"),
    ("selected-pointer-global", 0x0059DE30, "selected-pointer"),
]

PREDECESSOR_FILL_ORDER_MISSING_EVIDENCE_BY_GATE = {
    "localFillStreamReachesCurrentReader": (
        "local predecessor fill stream reaches current reader 0x00542b0c"
    ),
    "rootEntryFixedTraversalReachesFillSites": (
        "fixed traversal from predecessor root entry reaches 0x004844d0/0x004844d8"
    ),
    "fillFragmentEntryCandidateFound": "direct or branch-backed entry into the fill fragment",
    "encodedFillEntryControlFlowCandidateFound": (
        "encoded fill-entry scalar attached to modeled control flow"
    ),
    "rootTailBranchClosureReachesFillOrReader": (
        "root-tail branch closure reaches the fill fragment or current reader"
    ),
    "descriptorSliceRuntimeDispatchProven": (
        "runtime dispatch proof for save-selector slice descriptor boundaries"
    ),
    "rawGenericRouteProofFound": "raw generic handler or call-graph route/fill/current proof",
    "runtimeObservedPredecessorFill": "runtime observation of predecessor fill branch-state values",
    "predecessorToCurrentForwardBridgeFound": "predecessor-to-current forward execution bridge",
    "routeOrderAndSelectorMergeClosed": "route-order proof with selector merge closure",
}


def bool_text(value: Any) -> str:
    return str(bool(value))


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


def hex32(value: int | None) -> str | None:
    if value is None:
        return None
    return f"0x{value & 0xFFFFFFFF:08x}"


def count_by(values: list[str]) -> dict[str, int]:
    counts: dict[str, int] = {}
    for value in values:
        counts[value] = counts.get(value, 0) + 1
    return dict(sorted(counts.items()))


def bump_count(counts: dict[str, int], key: str) -> None:
    counts[key] = counts.get(key, 0) + 1


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


def compact_field_entry_sequence_context(scan: dict | None) -> dict:
    scan = scan or {}
    return {
        "sequenceCount": scan.get("sequenceCount"),
        "fieldEntryCandidateCount": scan.get("fieldEntryCandidateCount"),
        "fieldEntryCandidateNames": scan.get("fieldEntryCandidateNames") or [],
        "snapshotCount": scan.get("snapshotCount"),
        "snapshotRouteCandidateCount": scan.get("snapshotRouteCandidateCount"),
        "snapshotRouteCandidateNames": scan.get("snapshotRouteCandidateNames") or [],
        "finalSelectorCounts": scan.get("finalSelectorCounts") or {},
        "finalCameraTileCounts": scan.get("finalCameraTileCounts") or {},
        "snapshotSelectorCounts": scan.get("snapshotSelectorCounts") or {},
        "snapshotCameraTileCounts": scan.get("snapshotCameraTileCounts") or {},
        "classificationCounts": scan.get("classificationCounts") or {},
        "activeOrderPatternCounts": scan.get("activeOrderPatternCounts") or {},
        "promotionStatus": scan.get("promotionStatus"),
        "proofFound": scan.get("proofFound"),
        "predecessorFieldEntryProofFound": scan.get("predecessorFieldEntryProofFound"),
        "fieldEntryRouteCandidateFound": scan.get("fieldEntryRouteCandidateFound"),
        "selector2FinalObserved": scan.get("selector2FinalObserved"),
        "selector2SnapshotObserved": scan.get("selector2SnapshotObserved"),
        "routeRelevantRuntimeObjectTileFound": scan.get("routeRelevantRuntimeObjectTileFound"),
        "selectedRootExecutionProofFound": scan.get("selectedRootExecutionProofFound"),
        "failedPredecessorFieldEntryGateIds": scan.get("failedPredecessorFieldEntryGateIds") or [],
        "missingEvidence": scan.get("missingEvidence") or [],
        "remainingProofs": scan.get("remainingProofs") or [],
        "evidenceRefs": scan.get("evidenceRefs") or [],
        "evidenceRefCount": scan.get("evidenceRefCount"),
        "conclusion": scan.get("conclusion"),
    }


def final_snapshot(scan: dict | None) -> dict:
    for row in (scan or {}).get("snapshots") or []:
        if row.get("phase") == "final":
            return row
    return {}


def image_hit_count(scan: dict | None, name: str) -> int | None:
    for row in (scan or {}).get("imagePairHits") or []:
        if row.get("name") == name:
            return row.get("hitCountCapped")
    return None


def compact_coordinate_source_context(scan: dict | None) -> dict:
    scan = scan or {}
    final_coordinate_snapshot = final_snapshot(scan)
    return {
        "classification": scan.get("classification"),
        "coordinateSourceRejectionClassification": scan.get(
            "coordinateSourceRejectionClassification"
        ),
        "promotionStatus": scan.get("promotionStatus"),
        "finalSelector": (final_coordinate_snapshot.get("selectedPointerContext") or {}).get(
            "selector"
        ),
        "finalCameraTile": final_coordinate_snapshot.get("cameraTile") or {},
        "pairHitSummaryRows": scan.get("pairHitSummaryRows") or [],
        "publicSaveStartPointerTableTileHitCount": scan.get(
            "publicSaveStartPointerTableTileHitCount"
        ),
        "publicSaveStartStaticBaseHitCount": scan.get("publicSaveStartStaticBaseHitCount"),
        "publicSaveStartTrailRingHitCount": scan.get("publicSaveStartTrailRingHitCount"),
        "publicSaveStartImageHitCount": scan.get(
            "publicSaveStartImageHitCount",
            image_hit_count(scan, "public-save-start"),
        ),
        "publicSaveStartKnownGlobalImageHitCount": scan.get(
            "publicSaveStartKnownGlobalImageHitCount"
        ),
        "observedTrailPointerTableTileHitCount": scan.get(
            "observedTrailPointerTableTileHitCount"
        ),
        "observedTrailStaticBaseHitCount": scan.get("observedTrailStaticBaseHitCount"),
        "observedTrailTrailRingHitCount": scan.get("observedTrailTrailRingHitCount"),
        "observedTrailImageHitCount": scan.get(
            "observedTrailImageHitCount",
            image_hit_count(scan, "observed-trail"),
        ),
        "observedTrailKnownGlobalImageHitCount": scan.get(
            "observedTrailKnownGlobalImageHitCount"
        ),
        "reciprocalPointerTableTileHitCount": scan.get("reciprocalPointerTableTileHitCount"),
        "reciprocalStaticBaseHitCount": scan.get("reciprocalStaticBaseHitCount"),
        "reciprocalTrailRingHitCount": scan.get("reciprocalTrailRingHitCount"),
        "reciprocalImageHitCount": scan.get("reciprocalImageHitCount"),
        "remainingProofs": scan.get("remainingProofs") or [],
        "conclusion": scan.get("conclusion"),
    }


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


def compact_trace_row(row: dict) -> dict:
    return {
        "step": row.get("step"),
        "vaHex": row.get("vaHex"),
        "valueHex": row.get("valueHex"),
        "opcodeHex": row.get("opcodeHex"),
        "handlerVaHex": row.get("handlerVaHex"),
        "fixedAdvances": row.get("fixedAdvances") or [],
        "branchTargetHex": row.get("branchTargetHex"),
        "fallthroughVaHex": row.get("fallthroughVaHex"),
        "stopReason": row.get("stopReason"),
    }


def stop_row(trace: list[dict]) -> dict:
    for row in reversed(trace):
        if row.get("stopReason"):
            return row
    return trace[-1] if trace else {}


def offset_to_va(sections: list[dict], offset: int) -> int | None:
    for section in sections:
        raw_start = section["raw"]
        raw_end = raw_start + section["raw_size"]
        if raw_start <= offset < raw_end:
            return section["va"] + (offset - raw_start)
    return None


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


def bounded_code_window(
    exe: bytes,
    sections: list[dict],
    start_va: int | None,
    max_bytes: int = RAW_GENERIC_MAX_BYTES,
) -> dict:
    if start_va is None:
        return {"available": False, "reason": "missing-start"}
    start_offset = va_to_offset(sections, start_va)
    section = section_for_va(sections, start_va)
    if start_offset is None or section is None:
        return {
            "available": False,
            "reason": "start-not-mapped",
            "startVaHex": hex32(start_va),
        }
    section_end_offset = int(section["raw"]) + int(section["raw_size"])
    max_end_offset = min(start_offset + max_bytes, section_end_offset, len(exe))
    end_offset = max_end_offset
    termination = "max-window"
    cursor = start_offset
    while cursor < max_end_offset:
        opcode = exe[cursor]
        if opcode == 0xC3:
            end_offset = cursor + 1
            termination = "ret"
            break
        if opcode == 0xC2 and cursor + 3 <= max_end_offset:
            end_offset = cursor + 3
            termination = "ret-imm16"
            break
        cursor += 1
    end_va = start_va + (end_offset - start_offset)
    return {
        "available": True,
        "section": section.get("name"),
        "startVaHex": hex32(start_va),
        "endVaHex": hex32(end_va),
        "byteCount": end_offset - start_offset,
        "maxBytes": max_bytes,
        "termination": termination,
        "data": exe[start_offset:end_offset],
    }


def raw_generic_target_rows(
    predecessor_root_start: int | None,
    predecessor_root_stop: int | None,
    fill_sites: list[str],
    fill_stop: int | None,
    current_root: int | None,
    current_reader: int | None,
) -> list[dict]:
    rows: list[dict] = []
    if predecessor_root_start is not None:
        rows.append({
            "label": "predecessor-root-entry",
            "va": predecessor_root_start,
            "vaHex": hex32(predecessor_root_start),
            "group": "predecessor-root",
        })
    if predecessor_root_stop is not None:
        rows.append({
            "label": "predecessor-root-stop",
            "va": predecessor_root_stop,
            "vaHex": hex32(predecessor_root_stop),
            "group": "predecessor-root",
        })
    for index, value in enumerate(fill_sites):
        target = hex_to_int(value)
        if target is None:
            continue
        rows.append({
            "label": f"predecessor-fill-site-{index}",
            "va": target,
            "vaHex": hex32(target),
            "group": "fill",
        })
    if fill_stop is not None:
        rows.append({
            "label": "predecessor-fill-stop",
            "va": fill_stop,
            "vaHex": hex32(fill_stop),
            "group": "fill",
        })
    if current_root is not None:
        rows.append({
            "label": "current-root",
            "va": current_root,
            "vaHex": hex32(current_root),
            "group": "current",
        })
    if current_reader is not None:
        rows.append({
            "label": "current-reader",
            "va": current_reader,
            "vaHex": hex32(current_reader),
            "group": "current",
        })
    for label, va, group in RAW_GENERIC_STATIC_TARGETS:
        rows.append({"label": label, "va": va, "vaHex": hex32(va), "group": group})
    for index in range(12):
        va = 0x0059E360 + index
        rows.append({
            "label": f"secondary-branch-state-{index}",
            "va": va,
            "vaHex": hex32(va),
            "group": "branch-state",
        })
    return rows


def count_rows_by_group(rows: list[dict]) -> dict[str, int]:
    counts: dict[str, int] = {}
    for row in rows:
        group = str(row.get("group") or "-")
        counts[group] = counts.get(group, 0) + 1
    return dict(sorted(counts.items()))


def dword_immediate_hits(window: dict, targets: list[dict]) -> list[dict]:
    if not window.get("available"):
        return []
    data = window.get("data") or b""
    start_va = hex_to_int(window.get("startVaHex"))
    if start_va is None:
        return []
    rows: list[dict] = []
    for target in targets:
        target_va = target.get("va")
        if not isinstance(target_va, int):
            continue
        needle = struct.pack("<I", target_va)
        search = 0
        while True:
            hit = data.find(needle, search)
            if hit < 0:
                break
            rows.append({
                "hitVaHex": hex32(start_va + hit),
                "targetLabel": target.get("label"),
                "targetVaHex": target.get("vaHex"),
                "group": target.get("group"),
            })
            search = hit + 1
    rows.sort(key=lambda row: (row.get("hitVaHex") or "", row.get("targetLabel") or ""))
    return rows


def rel32_transfer_rows(window: dict, targets: list[dict], sections: list[dict]) -> list[dict]:
    if not window.get("available"):
        return []
    data = window.get("data") or b""
    start_va = hex_to_int(window.get("startVaHex"))
    if start_va is None:
        return []
    targets_by_va = {int(row["va"]): row for row in targets if isinstance(row.get("va"), int)}
    rows: list[dict] = []
    for index in range(0, max(0, len(data) - 4)):
        opcode = data[index]
        if opcode not in (0xE8, 0xE9):
            continue
        rel = struct.unpack_from("<i", data, index + 1)[0]
        site_va = start_va + index
        target_va = (site_va + 5 + rel) & 0xFFFFFFFF
        target = targets_by_va.get(target_va)
        target_section = section_for_va(sections, target_va)
        rows.append({
            "siteVaHex": hex32(site_va),
            "kind": "call" if opcode == 0xE8 else "jmp",
            "targetVaHex": hex32(target_va),
            "targetSection": target_section.get("name") if target_section else None,
            "targetLabel": target.get("label") if target else None,
            "group": target.get("group") if target else None,
        })
    return rows


def one_hop_callee_contrast(
    exe: bytes,
    sections: list[dict],
    call_target_hexes: list[str],
    targets: list[dict],
) -> dict:
    rows = []
    for target_hex in sorted(set(call_target_hexes)):
        target_va = hex_to_int(target_hex)
        window = bounded_code_window(exe, sections, target_va, max_bytes=0x300)
        immediate_hits = dword_immediate_hits(window, targets)
        transfers = rel32_transfer_rows(window, targets, sections)
        immediate_counts = count_rows_by_group(immediate_hits)
        transfer_hits = [transfer for transfer in transfers if transfer.get("group")]
        transfer_counts = count_rows_by_group(transfer_hits)
        route_groups = {"current", "route-record"}
        rows.append({
            "calleeVaHex": target_hex,
            "windowStartVaHex": window.get("startVaHex"),
            "windowEndVaHex": window.get("endVaHex"),
            "windowByteCount": window.get("byteCount"),
            "windowTermination": window.get("termination"),
            "immediateHitCount": len(immediate_hits),
            "immediateHitCountsByGroup": immediate_counts,
            "routeImmediateHitCount": sum(
                immediate_counts.get(group, 0) for group in route_groups
            ),
            "fillImmediateHitCount": immediate_counts.get("fill", 0),
            "currentImmediateHitCount": immediate_counts.get("current", 0),
            "selectedPointerImmediateHitCount": immediate_counts.get("selected-pointer", 0),
            "branchStateImmediateHitCount": immediate_counts.get("branch-state", 0),
            "directTransferTargetHitCount": len(transfer_hits),
            "directTransferTargetHitCountsByGroup": transfer_counts,
            "routeDirectTransferHitCount": sum(
                1 for transfer in transfer_hits if transfer.get("group") in route_groups
            ),
            "fillDirectTransferHitCount": sum(
                1 for transfer in transfer_hits if transfer.get("group") == "fill"
            ),
            "immediateHits": immediate_hits[:32],
            "directTransfers": transfers[:32],
        })
    immediate_counts: dict[str, int] = {}
    transfer_counts: dict[str, int] = {}
    for row in rows:
        for group, count in (row.get("immediateHitCountsByGroup") or {}).items():
            immediate_counts[group] = immediate_counts.get(group, 0) + int(count)
        for group, count in (row.get("directTransferTargetHitCountsByGroup") or {}).items():
            transfer_counts[group] = transfer_counts.get(group, 0) + int(count)
    immediate_counts = dict(sorted(immediate_counts.items()))
    transfer_counts = dict(sorted(transfer_counts.items()))
    route_groups = {"current", "route-record"}
    route_immediate_count = sum(immediate_counts.get(group, 0) for group in route_groups)
    fill_immediate_count = immediate_counts.get("fill", 0)
    current_immediate_count = immediate_counts.get("current", 0)
    route_transfer_hit_count = sum(transfer_counts.get(group, 0) for group in route_groups)
    fill_transfer_hit_count = transfer_counts.get("fill", 0)
    route_proof_found = (
        route_immediate_count > 0
        or fill_immediate_count > 0
        or current_immediate_count > 0
        or route_transfer_hit_count > 0
        or fill_transfer_hit_count > 0
    )
    return {
        "calleeCount": len(rows),
        "calleeRows": rows,
        "immediateHitCount": sum(immediate_counts.values()),
        "immediateHitCountsByGroup": immediate_counts,
        "routeImmediateHitCount": route_immediate_count,
        "fillImmediateHitCount": fill_immediate_count,
        "currentImmediateHitCount": current_immediate_count,
        "selectedPointerImmediateHitCount": immediate_counts.get("selected-pointer", 0),
        "branchStateImmediateHitCount": immediate_counts.get("branch-state", 0),
        "directTransferTargetHitCount": sum(
            int(row.get("directTransferTargetHitCount") or 0) for row in rows
        ),
        "directTransferTargetHitCountsByGroup": transfer_counts,
        "routeDirectTransferHitCount": route_transfer_hit_count,
        "fillDirectTransferHitCount": fill_transfer_hit_count,
        "routeProofFound": route_proof_found,
    }


def raw_generic_call_graph_roots(handler_rows: list[dict]) -> list[dict]:
    rows = []
    seen: set[int] = set()
    for row in handler_rows:
        handler_hex = row.get("rawGenericHandlerVaHex")
        handler_va = hex_to_int(handler_hex)
        if handler_va is None or handler_va in seen:
            continue
        seen.add(handler_va)
        rows.append({
            "label": f"{row.get('role') or 'raw-generic'}:{handler_hex}",
            "role": row.get("role"),
            "handlerVaHex": handler_hex,
            "handlerSection": row.get("rawGenericHandlerSection"),
            "va": handler_va,
        })
    return rows


def raw_generic_call_graph_contrast(
    exe: bytes,
    sections: list[dict],
    handler_rows: list[dict],
    targets: list[dict],
    max_depth: int = RAW_GENERIC_CALL_GRAPH_MAX_DEPTH,
) -> dict:
    roots = raw_generic_call_graph_roots(handler_rows)
    queue = [
        {
            "label": root["label"],
            "role": root.get("role"),
            "va": int(root["va"]),
            "depth": 0,
            "path": [root["label"]],
        }
        for root in roots
    ]
    visited_vas: set[int] = set()
    queued_vas = {int(item["va"]) for item in queue}
    reachable_functions = []
    call_edges = []
    immediate_counts: dict[str, int] = {}
    transfer_counts: dict[str, int] = {}
    max_observed_depth = 0
    direct_call_edge_count = 0
    mapped_direct_call_edge_count = 0
    text_direct_call_edge_count = 0
    unmapped_direct_call_edge_count = 0

    while queue:
        item = queue.pop(0)
        function_va = int(item["va"])
        if function_va in visited_vas:
            continue
        visited_vas.add(function_va)
        depth = int(item["depth"])
        max_observed_depth = max(max_observed_depth, depth)
        max_bytes = RAW_GENERIC_MAX_BYTES if depth == 0 else RAW_GENERIC_CALLEE_MAX_BYTES
        window = bounded_code_window(exe, sections, function_va, max_bytes=max_bytes)
        immediate_hits = dword_immediate_hits(window, targets)
        transfers = rel32_transfer_rows(window, targets, sections)
        transfer_hits = [transfer for transfer in transfers if transfer.get("group")]
        call_rows = [transfer for transfer in transfers if transfer.get("kind") == "call"]
        mapped_call_rows = [transfer for transfer in call_rows if transfer.get("targetSection")]
        text_call_rows = [
            transfer for transfer in mapped_call_rows
            if transfer.get("targetSection") == ".text"
        ]
        row_immediate_counts = count_rows_by_group(immediate_hits)
        row_transfer_counts = count_rows_by_group(transfer_hits)
        route_groups = {"current", "route-record"}
        for group, count in row_immediate_counts.items():
            immediate_counts[group] = immediate_counts.get(group, 0) + int(count)
        for group, count in row_transfer_counts.items():
            transfer_counts[group] = transfer_counts.get(group, 0) + int(count)
        direct_call_edge_count += len(call_rows)
        mapped_direct_call_edge_count += len(mapped_call_rows)
        text_direct_call_edge_count += len(text_call_rows)
        unmapped_direct_call_edge_count += len(call_rows) - len(mapped_call_rows)
        reachable_functions.append({
            "label": item["label"],
            "role": item.get("role"),
            "depth": depth,
            "functionVaHex": hex32(function_va),
            "windowStartVaHex": window.get("startVaHex"),
            "windowEndVaHex": window.get("endVaHex"),
            "windowByteCount": window.get("byteCount"),
            "windowTermination": window.get("termination"),
            "path": item["path"],
            "immediateHitCount": len(immediate_hits),
            "immediateHitCountsByGroup": row_immediate_counts,
            "routeImmediateHitCount": sum(
                row_immediate_counts.get(group, 0) for group in route_groups
            ),
            "fillImmediateHitCount": row_immediate_counts.get("fill", 0),
            "currentImmediateHitCount": row_immediate_counts.get("current", 0),
            "selectedPointerImmediateHitCount": row_immediate_counts.get("selected-pointer", 0),
            "branchStateImmediateHitCount": row_immediate_counts.get("branch-state", 0),
            "directTransferCount": len(transfers),
            "directCallCount": len(call_rows),
            "mappedDirectCallCount": len(mapped_call_rows),
            "textDirectCallCount": len(text_call_rows),
            "directTransferTargetHitCount": len(transfer_hits),
            "directTransferTargetHitCountsByGroup": row_transfer_counts,
            "routeDirectTransferHitCount": sum(
                1 for transfer in transfer_hits if transfer.get("group") in route_groups
            ),
            "fillDirectTransferHitCount": sum(
                1 for transfer in transfer_hits if transfer.get("group") == "fill"
            ),
        })
        if depth >= max_depth:
            continue
        for transfer in call_rows:
            target_va = hex_to_int(transfer.get("targetVaHex"))
            edge = {
                "fromLabel": item["label"],
                "fromVaHex": hex32(function_va),
                "depth": depth + 1,
                "callVaHex": transfer.get("siteVaHex"),
                "targetVaHex": transfer.get("targetVaHex"),
                "targetSection": transfer.get("targetSection"),
                "targetLabel": transfer.get("targetLabel")
                or (f"sub_{target_va:08x}" if target_va is not None else None),
                "path": [
                    *item["path"],
                    f"{transfer.get('siteVaHex')}->{transfer.get('targetVaHex')}",
                ],
            }
            if len(call_edges) < 128:
                call_edges.append(edge)
            if (
                target_va is None
                or transfer.get("targetSection") != ".text"
                or target_va in visited_vas
                or target_va in queued_vas
            ):
                continue
            queued_vas.add(target_va)
            queue.append({
                "label": edge["targetLabel"] or f"sub_{target_va:08x}",
                "role": None,
                "va": target_va,
                "depth": depth + 1,
                "path": edge["path"],
            })

    immediate_counts = dict(sorted(immediate_counts.items()))
    transfer_counts = dict(sorted(transfer_counts.items()))
    route_groups = {"current", "route-record"}
    route_immediate_count = sum(immediate_counts.get(group, 0) for group in route_groups)
    fill_immediate_count = immediate_counts.get("fill", 0)
    current_immediate_count = immediate_counts.get("current", 0)
    selected_pointer_immediate_count = immediate_counts.get("selected-pointer", 0)
    branch_state_immediate_count = immediate_counts.get("branch-state", 0)
    route_transfer_hit_count = sum(transfer_counts.get(group, 0) for group in route_groups)
    fill_transfer_hit_count = transfer_counts.get("fill", 0)
    proof_found = (
        route_immediate_count > 0
        or fill_immediate_count > 0
        or current_immediate_count > 0
        or route_transfer_hit_count > 0
        or fill_transfer_hit_count > 0
    )
    route_context_hit_count = selected_pointer_immediate_count + branch_state_immediate_count
    if not roots:
        classification = "raw-generic-callgraph-unavailable"
        promotion_status = "review-required"
    elif proof_found:
        classification = "raw-generic-callgraph-route-hit-review"
        promotion_status = "review-required"
    elif route_context_hit_count:
        classification = "raw-generic-callgraph-route-context-review"
        promotion_status = "review-required"
    else:
        classification = "raw-generic-callgraph-nonroute-contrast"
        promotion_status = "blocked"
    return {
        "available": bool(roots),
        "classification": classification,
        "promotionStatus": promotion_status,
        "proofFound": proof_found,
        "routeProofFound": proof_found,
        "routeContextFound": route_context_hit_count > 0,
        "routeContextHitCount": route_context_hit_count,
        "maxDepth": max_depth,
        "observedMaxDepth": max_observed_depth,
        "rootCount": len(roots),
        "rootRows": [
            {key: value for key, value in row.items() if key != "va"}
            for row in roots
        ],
        "reachableFunctionCount": len(reachable_functions),
        "directCallEdgeCount": direct_call_edge_count,
        "mappedDirectCallEdgeCount": mapped_direct_call_edge_count,
        "textDirectCallEdgeCount": text_direct_call_edge_count,
        "unmappedDirectCallEdgeCount": unmapped_direct_call_edge_count,
        "immediateHitCount": sum(immediate_counts.values()),
        "immediateHitCountsByGroup": immediate_counts,
        "routeImmediateHitCount": route_immediate_count,
        "fillImmediateHitCount": fill_immediate_count,
        "currentImmediateHitCount": current_immediate_count,
        "selectedPointerImmediateHitCount": selected_pointer_immediate_count,
        "branchStateImmediateHitCount": branch_state_immediate_count,
        "directTransferTargetHitCount": sum(transfer_counts.values()),
        "directTransferTargetHitCountsByGroup": transfer_counts,
        "routeDirectTransferHitCount": route_transfer_hit_count,
        "fillDirectTransferHitCount": fill_transfer_hit_count,
        "sampleReachableFunctions": reachable_functions[:32],
        "sampleCallEdges": call_edges[:64],
        "conclusion": (
            "A bounded raw generic direct-call graph from the predecessor raw handlers found no route, "
            "fill, current, selected-pointer, or secondary-branch-state hits."
            if roots and not proof_found and route_context_hit_count == 0
            else "The raw generic direct-call graph requires review before it can be treated as non-route contrast."
        ),
    }


def compact_raw_generic_call_graph_depth_row(max_depth: int, evidence: dict) -> dict:
    return {
        "maxDepth": max_depth,
        "classification": evidence.get("classification"),
        "promotionStatus": evidence.get("promotionStatus"),
        "proofFound": evidence.get("proofFound"),
        "routeContextFound": evidence.get("routeContextFound"),
        "routeContextHitCount": evidence.get("routeContextHitCount"),
        "observedMaxDepth": evidence.get("observedMaxDepth"),
        "rootCount": evidence.get("rootCount"),
        "reachableFunctionCount": evidence.get("reachableFunctionCount"),
        "directCallEdgeCount": evidence.get("directCallEdgeCount"),
        "mappedDirectCallEdgeCount": evidence.get("mappedDirectCallEdgeCount"),
        "textDirectCallEdgeCount": evidence.get("textDirectCallEdgeCount"),
        "routeImmediateHitCount": evidence.get("routeImmediateHitCount"),
        "fillImmediateHitCount": evidence.get("fillImmediateHitCount"),
        "currentImmediateHitCount": evidence.get("currentImmediateHitCount"),
        "selectedPointerImmediateHitCount": evidence.get("selectedPointerImmediateHitCount"),
        "branchStateImmediateHitCount": evidence.get("branchStateImmediateHitCount"),
        "routeDirectTransferHitCount": evidence.get("routeDirectTransferHitCount"),
        "fillDirectTransferHitCount": evidence.get("fillDirectTransferHitCount"),
    }


def raw_generic_call_graph_depth_sensitivity(
    exe: bytes,
    sections: list[dict],
    handler_rows: list[dict],
    targets: list[dict],
    depths: list[int] | None = None,
) -> dict:
    checked_depths = sorted(set(depths or RAW_GENERIC_CALL_GRAPH_DEPTH_SENSITIVITY_DEPTHS))
    rows = [
        compact_raw_generic_call_graph_depth_row(
            max_depth,
            raw_generic_call_graph_contrast(
                exe,
                sections,
                handler_rows,
                targets,
                max_depth=max_depth,
            ),
        )
        for max_depth in checked_depths
    ]
    default_row = next(
        (row for row in rows if row.get("maxDepth") == RAW_GENERIC_CALL_GRAPH_MAX_DEPTH),
        rows[-1] if rows else {},
    )
    stable_keys = [
        "reachableFunctionCount",
        "directCallEdgeCount",
        "mappedDirectCallEdgeCount",
        "textDirectCallEdgeCount",
        "routeImmediateHitCount",
        "fillImmediateHitCount",
        "currentImmediateHitCount",
        "selectedPointerImmediateHitCount",
        "branchStateImmediateHitCount",
        "routeDirectTransferHitCount",
        "fillDirectTransferHitCount",
    ]
    baseline = tuple(default_row.get(key) for key in stable_keys)
    rows_at_or_beyond_default = [
        row for row in rows
        if isinstance(row.get("maxDepth"), int)
        and row["maxDepth"] >= RAW_GENERIC_CALL_GRAPH_MAX_DEPTH
    ]
    proof_absent = all(
        row.get("proofFound") is False and row.get("routeContextFound") is False
        for row in rows
    )
    counts_stable = bool(rows_at_or_beyond_default) and all(
        tuple(row.get(key) for key in stable_keys) == baseline
        for row in rows_at_or_beyond_default
    )
    max_checked = max(checked_depths) if checked_depths else None
    depth_text = ",".join(str(depth) for depth in checked_depths) or "-"
    return {
        "depthsChecked": checked_depths,
        "defaultDepth": RAW_GENERIC_CALL_GRAPH_MAX_DEPTH,
        "maxDepthChecked": max_checked,
        "proofAbsentAcrossCheckedDepths": proof_absent,
        "countsStableAtAndBeyondDefaultDepth": counts_stable,
        "defaultDepthRow": default_row,
        "rows": rows,
        "conclusion": (
            f"Depth sensitivity over max depths {depth_text} found no raw generic route/fill/current, "
            "selected-pointer, or secondary-branch-state hits. Counts are stable at and beyond the "
            "default depth, so increasing the bounded call-graph depth does not make the raw generic "
            "dispatch contrast promotable."
        ),
    }


def raw_generic_handler_contrast(
    exe: bytes,
    sections: list[dict],
    dispatch_slice_dependency: dict,
    predecessor_root_start: int | None,
    predecessor_root_stop: int | None,
    fill_sites: list[str],
    fill_stop: int | None,
    current_root: int | None,
    current_reader: int | None,
) -> dict:
    targets = raw_generic_target_rows(
        predecessor_root_start,
        predecessor_root_stop,
        fill_sites,
        fill_stop,
        current_root,
        current_reader,
    )
    handler_rows = []
    seen: set[tuple[str | None, str | None]] = set()
    for row in dispatch_slice_dependency.get("predecessorDispatchRows") or []:
        role = row.get("role")
        handler_hex = row.get("generalRawHandlerVaHex")
        key = (role, handler_hex)
        if key in seen:
            continue
        seen.add(key)
        handler_va = hex_to_int(handler_hex)
        window = bounded_code_window(exe, sections, handler_va)
        immediate_hits = dword_immediate_hits(window, targets)
        transfers = rel32_transfer_rows(window, targets, sections)
        call_rows = [transfer for transfer in transfers if transfer.get("kind") == "call"]
        mapped_call_rows = [transfer for transfer in call_rows if transfer.get("targetSection")]
        route_groups = {"current", "route-record"}
        row_immediate_counts = count_rows_by_group(immediate_hits)
        row_transfer_counts = count_rows_by_group(
            [transfer for transfer in transfers if transfer.get("group")]
        )
        handler_rows.append({
            "role": role,
            "siteVaHex": row.get("siteVaHex"),
            "relativeOpcodeHex": row.get("relativeOpcodeHex"),
            "sliceHandlerVaHex": row.get("saveHandlerVaHex"),
            "sliceHandlerSection": row.get("saveHandlerSection"),
            "rawGenericHandlerVaHex": handler_hex,
            "rawGenericHandlerSection": row.get("generalRawHandlerSection"),
            "rawGeneralDiffersFromSlice": row.get("rawGeneralDiffersFromSlice"),
            "windowStartVaHex": window.get("startVaHex"),
            "windowEndVaHex": window.get("endVaHex"),
            "windowByteCount": window.get("byteCount"),
            "windowTermination": window.get("termination"),
            "immediateHitCount": len(immediate_hits),
            "immediateHitCountsByGroup": row_immediate_counts,
            "routeImmediateHitCount": sum(
                row_immediate_counts.get(group, 0) for group in route_groups
            ),
            "fillImmediateHitCount": row_immediate_counts.get("fill", 0),
            "currentImmediateHitCount": row_immediate_counts.get("current", 0),
            "selectedPointerImmediateHitCount": row_immediate_counts.get("selected-pointer", 0),
            "branchStateImmediateHitCount": row_immediate_counts.get("branch-state", 0),
            "predecessorRootImmediateHitCount": row_immediate_counts.get("predecessor-root", 0),
            "immediateHits": immediate_hits[:32],
            "directTransferCount": len(transfers),
            "directCallCount": len(call_rows),
            "mappedDirectCallCount": len(mapped_call_rows),
            "unmappedDirectCallCount": len(call_rows) - len(mapped_call_rows),
            "mappedDirectCallTargets": sorted(
                {
                    str(transfer.get("targetVaHex"))
                    for transfer in mapped_call_rows
                    if transfer.get("targetVaHex")
                }
            ),
            "directTransferTargetHitCount": sum(1 for transfer in transfers if transfer.get("group")),
            "directTransferTargetHitCountsByGroup": row_transfer_counts,
            "routeDirectTransferHitCount": sum(
                1 for transfer in transfers if transfer.get("group") in route_groups
            ),
            "fillDirectTransferHitCount": sum(
                1 for transfer in transfers if transfer.get("group") == "fill"
            ),
            "directTransfers": transfers[:32],
        })
    immediate_counts: dict[str, int] = {}
    transfer_counts: dict[str, int] = {}
    for row in handler_rows:
        for group, count in (row.get("immediateHitCountsByGroup") or {}).items():
            immediate_counts[group] = immediate_counts.get(group, 0) + int(count)
        for group, count in (row.get("directTransferTargetHitCountsByGroup") or {}).items():
            transfer_counts[group] = transfer_counts.get(group, 0) + int(count)
    immediate_counts = dict(sorted(immediate_counts.items()))
    transfer_counts = dict(sorted(transfer_counts.items()))
    route_groups = {"current", "route-record"}
    route_immediate_count = sum(immediate_counts.get(group, 0) for group in route_groups)
    current_immediate_count = immediate_counts.get("current", 0)
    fill_immediate_count = immediate_counts.get("fill", 0)
    selected_pointer_immediate_count = immediate_counts.get("selected-pointer", 0)
    branch_state_immediate_count = immediate_counts.get("branch-state", 0)
    route_transfer_hit_count = sum(transfer_counts.get(group, 0) for group in route_groups)
    fill_transfer_hit_count = transfer_counts.get("fill", 0)
    mapped_call_targets = sorted(
        {
            str(target)
            for row in handler_rows
            for target in row.get("mappedDirectCallTargets", [])
            if target
        }
    )
    one_hop = one_hop_callee_contrast(exe, sections, mapped_call_targets, targets)
    call_graph = raw_generic_call_graph_contrast(exe, sections, handler_rows, targets)
    call_graph_depth_sensitivity = raw_generic_call_graph_depth_sensitivity(
        exe,
        sections,
        handler_rows,
        targets,
    )
    route_proof_found = (
        route_immediate_count > 0
        or current_immediate_count > 0
        or fill_immediate_count > 0
        or route_transfer_hit_count > 0
        or fill_transfer_hit_count > 0
        or one_hop.get("routeProofFound") is True
        or call_graph.get("proofFound") is True
    )
    route_context_found = call_graph.get("routeContextFound") is True
    if not handler_rows:
        classification = "raw-generic-handler-unavailable"
        promotion_status = "review-required"
    elif route_proof_found:
        classification = "raw-generic-handler-route-hit-review"
        promotion_status = "review-required"
    elif route_context_found:
        classification = "raw-generic-handler-callgraph-context-review"
        promotion_status = "review-required"
    elif (
        len(handler_rows) == 2
        and selected_pointer_immediate_count == 0
        and branch_state_immediate_count == 0
    ):
        classification = "raw-generic-handlers-nonroute-contrast"
        promotion_status = "blocked"
    else:
        classification = "raw-generic-handlers-no-direct-route-hit"
        promotion_status = "blocked"
    return {
        "available": bool(handler_rows),
        "classification": classification,
        "promotionStatus": promotion_status,
        "maxWindowBytes": RAW_GENERIC_MAX_BYTES,
        "targetRows": [
            {key: value for key, value in row.items() if key != "va"}
            for row in targets
        ],
        "handlerCount": len(handler_rows),
        "handlerRows": handler_rows,
        "immediateHitCount": sum(immediate_counts.values()),
        "immediateHitCountsByGroup": immediate_counts,
        "routeImmediateHitCount": route_immediate_count,
        "fillImmediateHitCount": fill_immediate_count,
        "currentImmediateHitCount": current_immediate_count,
        "selectedPointerImmediateHitCount": selected_pointer_immediate_count,
        "branchStateImmediateHitCount": branch_state_immediate_count,
        "predecessorRootImmediateHitCount": immediate_counts.get("predecessor-root", 0),
        "directTransferCount": sum(int(row.get("directTransferCount") or 0) for row in handler_rows),
        "directCallCount": sum(int(row.get("directCallCount") or 0) for row in handler_rows),
        "mappedDirectCallCount": sum(int(row.get("mappedDirectCallCount") or 0) for row in handler_rows),
        "unmappedDirectCallCount": sum(
            int(row.get("unmappedDirectCallCount") or 0) for row in handler_rows
        ),
        "mappedDirectCallTargets": mapped_call_targets,
        "directTransferTargetHitCount": sum(
            int(row.get("directTransferTargetHitCount") or 0) for row in handler_rows
        ),
        "directTransferTargetHitCountsByGroup": transfer_counts,
        "routeDirectTransferHitCount": route_transfer_hit_count,
        "fillDirectTransferHitCount": fill_transfer_hit_count,
        "oneHopMappedCalleeContrast": one_hop,
        "oneHopMappedCalleeCount": one_hop.get("calleeCount"),
        "oneHopRouteImmediateHitCount": one_hop.get("routeImmediateHitCount"),
        "oneHopFillImmediateHitCount": one_hop.get("fillImmediateHitCount"),
        "oneHopCurrentImmediateHitCount": one_hop.get("currentImmediateHitCount"),
        "oneHopSelectedPointerImmediateHitCount": one_hop.get(
            "selectedPointerImmediateHitCount"
        ),
        "oneHopBranchStateImmediateHitCount": one_hop.get("branchStateImmediateHitCount"),
        "oneHopRouteDirectTransferHitCount": one_hop.get("routeDirectTransferHitCount"),
        "oneHopFillDirectTransferHitCount": one_hop.get("fillDirectTransferHitCount"),
        "oneHopRouteProofFound": one_hop.get("routeProofFound"),
        "callGraphContrast": call_graph,
        "callGraphDepthSensitivity": call_graph_depth_sensitivity,
        "callGraphClassification": call_graph.get("classification"),
        "callGraphProofFound": call_graph.get("proofFound"),
        "callGraphRouteContextFound": call_graph.get("routeContextFound"),
        "callGraphRouteContextHitCount": call_graph.get("routeContextHitCount"),
        "callGraphMaxDepth": call_graph.get("maxDepth"),
        "callGraphReachableFunctionCount": call_graph.get("reachableFunctionCount"),
        "callGraphDirectCallEdgeCount": call_graph.get("directCallEdgeCount"),
        "callGraphMappedDirectCallEdgeCount": call_graph.get("mappedDirectCallEdgeCount"),
        "callGraphTextDirectCallEdgeCount": call_graph.get("textDirectCallEdgeCount"),
        "callGraphRouteImmediateHitCount": call_graph.get("routeImmediateHitCount"),
        "callGraphFillImmediateHitCount": call_graph.get("fillImmediateHitCount"),
        "callGraphCurrentImmediateHitCount": call_graph.get("currentImmediateHitCount"),
        "callGraphSelectedPointerImmediateHitCount": call_graph.get(
            "selectedPointerImmediateHitCount"
        ),
        "callGraphBranchStateImmediateHitCount": call_graph.get("branchStateImmediateHitCount"),
        "callGraphRouteDirectTransferHitCount": call_graph.get("routeDirectTransferHitCount"),
        "callGraphFillDirectTransferHitCount": call_graph.get("fillDirectTransferHitCount"),
        "callGraphDepthSensitivityMaxDepthChecked": call_graph_depth_sensitivity.get(
            "maxDepthChecked"
        ),
        "callGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
            call_graph_depth_sensitivity.get("proofAbsentAcrossCheckedDepths")
        ),
        "callGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth": (
            call_graph_depth_sensitivity.get("countsStableAtAndBeyondDefaultDepth")
        ),
        "routeProofFound": route_proof_found,
        "conclusion": (
            "Bounded raw generic handler windows for the predecessor stop low bytes contain no direct "
            "route/fill/current immediates or direct transfer targets; mapped one-hop callees and a bounded "
            "direct-call graph have the same non-route shape, so raw generic dispatch does not supply the "
            "missing predecessor fill/current bridge."
            if not route_proof_found and handler_rows
            else "Raw generic handler windows require review before they can be treated as non-route contrast."
        ),
    }


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


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


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


def readable_vas(sections: list[dict], start_va: int, end_va: int) -> list[int]:
    ranges: list[range] = []
    for section in sections:
        section_start = section["va"]
        section_end = section_start + section["raw_size"]
        start = max(start_va, section_start)
        end = min(end_va, section_end)
        if start < end:
            ranges.append(range(start, end))
    return [va for span in ranges for va in span]


def direct_dword_ref_counts(exe: bytes, sections: list[dict], targets: list[str]) -> dict[str, int]:
    counts = {}
    for target_hex in targets:
        target = hex_to_int(target_hex)
        if target is None:
            continue
        needle = struct.pack("<I", target)
        count = 0
        offset = 0
        while True:
            hit = exe.find(needle, offset)
            if hit < 0:
                break
            if offset_to_va(sections, hit) is not None:
                count += 1
            offset = hit + 1
        counts[target_hex] = count
    return counts


def fill_entry_candidate_scan(
    exe: bytes,
    sections: list[dict],
    root_start_va: int | None,
    root_end_va: int | None,
    fill_start_va: int | None,
    fill_stop_va: int | None,
) -> dict:
    if (
        root_start_va is None
        or root_end_va is None
        or fill_start_va is None
        or fill_stop_va is None
    ):
        return {"available": False}
    fill_end_va = fill_stop_va + 4
    dword_refs = []
    offset = 0
    while offset + 4 <= len(exe):
        value = struct.unpack_from("<I", exe, offset)[0]
        if fill_start_va <= value < fill_end_va:
            site_va = offset_to_va(sections, offset)
            dword_refs.append({
                "siteVaHex": f"0x{site_va:08x}" if site_va is not None else None,
                "targetVaHex": f"0x{value:08x}",
                "inPredecessorRootRange": (
                    site_va is not None and root_start_va <= site_va < root_end_va
                ),
            })
        offset += 1

    branch_target_rows = []
    va = root_start_va
    while va + 8 <= root_end_va:
        opcode = byte_at(exe, sections, va)
        handler = handler_entry(exe, sections, opcode) if opcode is not None else {}
        target = u32_at(exe, sections, va + 4)
        if (
            handler.get("canJumpToDwordAtPlus4")
            and target is not None
            and fill_start_va <= target < fill_end_va
        ):
            branch_target_rows.append({
                "siteVaHex": f"0x{va:08x}",
                "opcodeHex": f"0x{opcode:02x}" if opcode is not None else None,
                "handlerVaHex": handler.get("handlerVaHex"),
                "targetVaHex": f"0x{target:08x}",
            })
        va += 4

    root_dword_refs = [row for row in dword_refs if row["inPredecessorRootRange"]]
    return {
        "available": True,
        "fillFragmentRangeHex": f"0x{fill_start_va:08x}..0x{fill_end_va:08x}",
        "allDwordRefCount": len(dword_refs),
        "predecessorRootRangeDwordRefCount": len(root_dword_refs),
        "rootBranchTargetCandidateCount": len(branch_target_rows),
        "dwordRefs": dword_refs[:20],
        "rootBranchTargetCandidates": branch_target_rows[:20],
        "entryCandidateFound": bool(dword_refs or branch_target_rows),
    }


def encoded_fill_entry_candidate_scan(
    exe: bytes,
    sections: list[dict],
    root_start_va: int | None,
    root_stop_va: int | None,
    fill_start_va: int | None,
    fill_stop_va: int | None,
) -> dict:
    if root_start_va is None or fill_start_va is None or fill_stop_va is None:
        return {"available": False}
    if root_start_va >= fill_start_va:
        return {"available": False, "reason": "root start is not before fill fragment"}
    fill_end_va = fill_stop_va + 4
    target_vas = list(range(fill_start_va, fill_end_va, 4))
    target_low16s = {target & 0xffff: target for target in target_vas}
    target_root_rel16s = {
        target - root_start_va: target
        for target in target_vas
        if 0 <= target - root_start_va <= 0xffff
    }
    target_root_rel32s = {
        target - root_start_va: target
        for target in target_vas
        if 0 <= target - root_start_va <= 0xffffffff
    }
    range_start = root_start_va
    range_end = fill_start_va
    root_tail_start = root_stop_va if root_stop_va is not None and root_stop_va < fill_start_va else None
    handler_cache: dict[int, dict] = {}
    counts = {
        "abs16Low": 0,
        "rootRelativeU16": 0,
        "rootRelativeU32": 0,
        "signedRel16SitePlus2": 0,
        "signedRel32SitePlus4": 0,
    }
    root_tail_counts = {key: 0 for key in counts}
    raw_rows: list[dict] = []
    branch_attached_rows: list[dict] = []
    modeled_fixed_rows: list[dict] = []

    def cached_handler(opcode: int | None) -> dict:
        if opcode is None:
            return {}
        if opcode not in handler_cache:
            handler_cache[opcode] = handler_entry(exe, sections, opcode)
        return handler_cache[opcode]

    def record(
        kind: str,
        site_va: int,
        value: int,
        target: int,
        width: int,
    ) -> None:
        row_va = site_va & ~3
        opcode = byte_at(exe, sections, row_va)
        handler = cached_handler(opcode)
        row = {
            "kind": kind,
            "siteVaHex": f"0x{site_va:08x}",
            "rowVaHex": f"0x{row_va:08x}",
            "valueHex": f"0x{value & ((1 << (width * 8)) - 1):0{width * 2}x}",
            "targetVaHex": f"0x{target:08x}",
            "opcodeHex": f"0x{opcode:02x}" if opcode is not None else None,
            "handlerVaHex": handler.get("handlerVaHex"),
            "handlerSection": handler.get("handlerSection"),
            "handlerCanJumpToDwordAtPlus4": handler.get("canJumpToDwordAtPlus4") is True,
            "handlerFixedAdvances": handler.get("fixedAdvances") or [],
            "startsAtBranchTargetField": handler.get("canJumpToDwordAtPlus4") is True
            and site_va == row_va + 4,
        }
        if len(raw_rows) < 24:
            raw_rows.append(row)
        if row["startsAtBranchTargetField"] and len(branch_attached_rows) < 24:
            branch_attached_rows.append(row)

    for site_va in readable_vas(sections, range_start, range_end):
        in_root_tail = root_tail_start is not None and root_tail_start <= site_va < fill_start_va
        value16 = u16_at(exe, sections, site_va)
        if value16 is not None and value16 in target_low16s:
            counts["abs16Low"] += 1
            if in_root_tail:
                root_tail_counts["abs16Low"] += 1
            record("abs16-low", site_va, value16, target_low16s[value16], 2)
        if value16 is not None and value16 in target_root_rel16s:
            counts["rootRelativeU16"] += 1
            if in_root_tail:
                root_tail_counts["rootRelativeU16"] += 1
            record("root-relative-u16", site_va, value16, target_root_rel16s[value16], 2)
        value32 = u32_at(exe, sections, site_va)
        if value32 is not None and value32 in target_root_rel32s:
            counts["rootRelativeU32"] += 1
            if in_root_tail:
                root_tail_counts["rootRelativeU32"] += 1
            record("root-relative-u32", site_va, value32, target_root_rel32s[value32], 4)
        rel16 = s16_at(exe, sections, site_va)
        if rel16 is not None:
            target = site_va + 2 + rel16
            if fill_start_va <= target < fill_end_va and target % 4 == 0:
                counts["signedRel16SitePlus2"] += 1
                if in_root_tail:
                    root_tail_counts["signedRel16SitePlus2"] += 1
                record("signed-rel16-site-plus2", site_va, rel16, target, 2)
        rel32 = s32_at(exe, sections, site_va)
        if rel32 is not None:
            target = site_va + 4 + rel32
            if fill_start_va <= target < fill_end_va and target % 4 == 0:
                counts["signedRel32SitePlus4"] += 1
                if in_root_tail:
                    root_tail_counts["signedRel32SitePlus4"] += 1
                record("signed-rel32-site-plus4", site_va, rel32, target, 4)

    for row_va in range(range_start, range_end, 4):
        opcode = byte_at(exe, sections, row_va)
        handler = cached_handler(opcode)
        for advance in handler.get("fixedAdvances") or []:
            target = row_va + advance
            if fill_start_va <= target < fill_end_va:
                modeled_fixed_rows.append({
                    "siteVaHex": f"0x{row_va:08x}",
                    "advance": advance,
                    "targetVaHex": f"0x{target:08x}",
                    "handlerVaHex": handler.get("handlerVaHex"),
                    "handlerSection": handler.get("handlerSection"),
                })

    raw_scalar_count = sum(counts.values())
    root_tail_raw_scalar_count = sum(root_tail_counts.values())
    branch_attached_count = len(branch_attached_rows)
    modeled_control_flow_count = len(modeled_fixed_rows)
    promoting_count = modeled_control_flow_count
    if promoting_count:
        classification = "encoded-entry-control-flow-candidate"
    elif raw_scalar_count:
        classification = "raw-encoded-scalars-nonpromoting"
    else:
        classification = "no-encoded-entry-candidates"
    return {
        "available": True,
        "scanRangeHex": f"0x{range_start:08x}..0x{range_end:08x}",
        "rootTailRangeHex": (
            f"0x{root_tail_start:08x}..0x{fill_start_va:08x}" if root_tail_start is not None else None
        ),
        "fillFragmentRangeHex": f"0x{fill_start_va:08x}..0x{fill_end_va:08x}",
        "targetVaHexes": [f"0x{target:08x}" for target in target_vas],
        "targetLow16Hexes": [f"0x{value:04x}" for value in sorted(target_low16s)],
        "rootRelativeU16Hexes": [f"0x{value:04x}" for value in sorted(target_root_rel16s)],
        "rawScalarCandidateCounts": counts,
        "rootTailRawScalarCandidateCounts": root_tail_counts,
        "rawScalarCandidateCount": raw_scalar_count,
        "rootTailRawScalarCandidateCount": root_tail_raw_scalar_count,
        "branchAttachedEncodedFieldCount": branch_attached_count,
        "modeledFixedAdvanceToFillCount": len(modeled_fixed_rows),
        "modeledControlFlowCandidateCount": modeled_control_flow_count,
        "promotingCandidateCount": promoting_count,
        "rawScalarCandidateRows": raw_rows,
        "branchAttachedEncodedRows": branch_attached_rows,
        "modeledFixedAdvanceRows": modeled_fixed_rows[:24],
        "classification": classification,
        "promotionStatus": "ready-for-review" if promoting_count else "blocked",
    }


def root_tail_isolation_scan(
    exe: bytes,
    sections: list[dict],
    root_stop_va: int | None,
    fill_start_va: int | None,
    fill_stop_va: int | None,
    current_reader_va: int | None,
) -> dict:
    if root_stop_va is None or fill_start_va is None or fill_stop_va is None:
        return {"available": False}
    if root_stop_va >= fill_start_va:
        return {"available": False, "reason": "root stop is not before fill fragment"}
    fill_end_va = fill_stop_va + 4
    handler_cache: dict[int, dict] = {}

    def cached_handler(opcode: int | None) -> dict:
        if opcode is None:
            return {}
        if opcode not in handler_cache:
            handler_cache[opcode] = handler_entry(exe, sections, opcode)
        return handler_cache[opcode]

    def row_at(va: int) -> dict:
        opcode = byte_at(exe, sections, va)
        value = u32_at(exe, sections, va)
        handler = cached_handler(opcode)
        return {
            "vaHex": f"0x{va:08x}",
            "valueHex": f"0x{value:08x}" if value is not None else None,
            "opcodeHex": f"0x{opcode:02x}" if opcode is not None else None,
            "handlerVaHex": handler.get("handlerVaHex"),
            "handlerSection": handler.get("handlerSection"),
            "fixedAdvances": handler.get("fixedAdvances") or [],
            "canJumpToDwordAtPlus4": handler.get("canJumpToDwordAtPlus4") is True,
        }

    def target_class_and_section(target: int | None) -> tuple[str, str]:
        if target is None:
            return "missing-target", "-"
        target_section = section_for_va(sections, target)
        target_section_name = str(target_section.get("name")) if target_section else "unmapped"
        if fill_start_va <= target < fill_end_va:
            target_class = "fill-fragment"
        elif current_reader_va is not None and target == current_reader_va:
            target_class = "current-reader"
        elif root_stop_va <= target < fill_start_va:
            target_class = "inside-root-tail"
        elif target < root_stop_va:
            target_class = "before-root-tail"
        elif fill_end_va <= target < fill_end_va + 0x100:
            target_class = "after-fill-near"
        elif target_section_name != "unmapped":
            target_class = f"mapped-{target_section_name}"
        else:
            target_class = "unmapped"
        return target_class, target_section_name

    text_handler_count = 0
    data_handler_count = 0
    other_handler_count = 0
    data_no_advance_count = 0
    branch_capable_count = 0
    branch_to_fill_rows = []
    branch_to_reader_rows = []
    branch_target_class_counts: dict[str, int] = {}
    branch_target_section_counts: dict[str, int] = {}
    branch_target_sample_rows = []
    fixed_fallthrough_to_fill_rows = []
    va = root_stop_va
    while va < fill_start_va:
        opcode = byte_at(exe, sections, va)
        handler = cached_handler(opcode)
        handler_section = handler.get("handlerSection")
        if handler_section == ".text":
            text_handler_count += 1
        elif handler_section == ".data":
            data_handler_count += 1
        else:
            other_handler_count += 1
        if handler_section == ".data" and not handler.get("fixedAdvances"):
            data_no_advance_count += 1
        if handler.get("canJumpToDwordAtPlus4"):
            branch_capable_count += 1
            target = u32_at(exe, sections, va + 4)
            target_class, target_section_name = target_class_and_section(target)
            bump_count(branch_target_section_counts, target_section_name)
            bump_count(branch_target_class_counts, target_class)
            if len(branch_target_sample_rows) < 24:
                branch_target_sample_rows.append({
                    "siteVaHex": f"0x{va:08x}",
                    "opcodeHex": f"0x{opcode:02x}" if opcode is not None else None,
                    "handlerVaHex": handler.get("handlerVaHex"),
                    "targetVaHex": f"0x{target:08x}" if target is not None else None,
                    "targetClass": target_class,
                    "targetSection": target_section_name,
                })
            if target is not None and fill_start_va <= target < fill_end_va:
                branch_to_fill_rows.append({
                    "siteVaHex": f"0x{va:08x}",
                    "targetVaHex": f"0x{target:08x}",
                    "handlerVaHex": handler.get("handlerVaHex"),
                })
            if current_reader_va is not None and target == current_reader_va:
                branch_to_reader_rows.append({
                    "siteVaHex": f"0x{va:08x}",
                    "targetVaHex": f"0x{target:08x}",
                    "handlerVaHex": handler.get("handlerVaHex"),
                })
        for advance in handler.get("fixedAdvances") or []:
            if va + advance == fill_start_va:
                fixed_fallthrough_to_fill_rows.append({
                    "siteVaHex": f"0x{va:08x}",
                    "advance": advance,
                    "handlerVaHex": handler.get("handlerVaHex"),
                })
        va += 4

    graph_nodes = set(range(root_stop_va, fill_end_va, 4))
    tail_nodes = set(range(root_stop_va, fill_start_va, 4))
    fill_target_nodes = set(range(fill_start_va, fill_end_va, 4))
    branch_seed_nodes: set[int] = set()
    predecessors: dict[int, list[int]] = {}
    closure_edge_count = 0
    closure_outside_successor_count = 0
    closure_stop_reason_counts: dict[str, int] = {}
    closure_outside_successor_class_counts: dict[str, int] = {}
    closure_outside_successor_section_counts: dict[str, int] = {}
    closure_outside_successor_sample_rows = []

    def record_closure_outside_successor(source: int, target: int | None) -> None:
        target_class, target_section_name = target_class_and_section(target)
        bump_count(closure_outside_successor_class_counts, target_class)
        bump_count(closure_outside_successor_section_counts, target_section_name)
        if len(closure_outside_successor_sample_rows) < 24:
            closure_outside_successor_sample_rows.append({
                "sourceVaHex": hex32(source),
                "targetVaHex": hex32(target),
                "targetClass": target_class,
                "targetSection": target_section_name,
            })

    def add_successor(source: int, target: int | None) -> None:
        nonlocal closure_edge_count, closure_outside_successor_count
        if target is None:
            closure_outside_successor_count += 1
            record_closure_outside_successor(source, target)
            return
        if target in graph_nodes or (current_reader_va is not None and target == current_reader_va):
            predecessors.setdefault(target, []).append(source)
            closure_edge_count += 1
            return
        closure_outside_successor_count += 1
        record_closure_outside_successor(source, target)

    for node_va in sorted(graph_nodes):
        opcode = byte_at(exe, sections, node_va)
        value = u32_at(exe, sections, node_va)
        if opcode is None or value is None:
            bump_count(closure_stop_reason_counts, "unreadable")
            continue
        handler = cached_handler(opcode)
        advances = handler.get("fixedAdvances") or []
        if node_va < fill_start_va and handler.get("canJumpToDwordAtPlus4"):
            branch_seed_nodes.add(node_va)
        if handler.get("canJumpToDwordAtPlus4"):
            add_successor(node_va, u32_at(exe, sections, node_va + 4))
            add_successor(node_va, node_va + (advances[0] if len(advances) == 1 else 8))
            continue
        if len(advances) == 1:
            add_successor(node_va, node_va + advances[0])
            continue
        bump_count(closure_stop_reason_counts, "no-fixed-advance" if not advances else "multiple-advances")

    def reverse_reachable(targets: set[int]) -> set[int]:
        seen = set(targets)
        queue = list(targets)
        while queue:
            target = queue.pop(0)
            for predecessor in predecessors.get(target, []):
                if predecessor in seen:
                    continue
                seen.add(predecessor)
                queue.append(predecessor)
        return seen

    fill_reachable_nodes = reverse_reachable(fill_target_nodes)
    current_reachable_nodes = reverse_reachable(
        {current_reader_va} if current_reader_va is not None else set()
    )
    branch_seed_reaches_fill = sorted(branch_seed_nodes & fill_reachable_nodes)
    branch_seed_reaches_current = sorted(branch_seed_nodes & current_reachable_nodes)
    root_tail_branch_closure = {
        "available": True,
        "nodeCount": len(graph_nodes),
        "tailNodeCount": len(tail_nodes),
        "fillTargetNodeCount": len(fill_target_nodes),
        "branchSeedCount": len(branch_seed_nodes),
        "edgeCount": closure_edge_count,
        "outsideSuccessorCount": closure_outside_successor_count,
        "outsideSuccessorClassCounts": dict(sorted(closure_outside_successor_class_counts.items())),
        "outsideSuccessorSectionCounts": dict(sorted(closure_outside_successor_section_counts.items())),
        "outsideSuccessorSampleRows": closure_outside_successor_sample_rows,
        "stopReasonCounts": dict(sorted(closure_stop_reason_counts.items())),
        "tailNodeReachFillCount": len(tail_nodes & fill_reachable_nodes),
        "tailNodeReachCurrentReaderCount": len(tail_nodes & current_reachable_nodes),
        "branchSeedReachFillCount": len(branch_seed_reaches_fill),
        "branchSeedReachCurrentReaderCount": len(branch_seed_reaches_current),
        "branchSeedReachFillRows": [{"siteVaHex": hex32(value)} for value in branch_seed_reaches_fill[:12]],
        "branchSeedReachCurrentReaderRows": [
            {"siteVaHex": hex32(value)} for value in branch_seed_reaches_current[:12]
        ],
    }
    root_tail_branch_closure["proofFound"] = (
        root_tail_branch_closure["branchSeedReachFillCount"] > 0
        or root_tail_branch_closure["branchSeedReachCurrentReaderCount"] > 0
    )
    root_tail_branch_closure["classification"] = (
        "branch-closure-candidate"
        if root_tail_branch_closure["proofFound"]
        else "branch-closure-no-fill-or-current-reader"
    )

    immediate_predecessor = row_at(fill_start_va - 4)
    nearby_start = max(root_stop_va, fill_start_va - 0x20)
    nearby_rows = [row_at(va) for va in range(nearby_start, fill_end_va, 4)]
    descriptor_isolated = (
        immediate_predecessor.get("handlerSection") == ".data"
        and not immediate_predecessor.get("fixedAdvances")
        and not branch_to_fill_rows
        and not fixed_fallthrough_to_fill_rows
    )
    return {
        "available": True,
        "rangeHex": f"0x{root_stop_va:08x}..0x{fill_start_va:08x}",
        "distanceBytes": fill_start_va - root_stop_va,
        "distanceHex": f"0x{fill_start_va - root_stop_va:04x}",
        "dwordCount": (fill_start_va - root_stop_va) // 4,
        "textHandlerRowCount": text_handler_count,
        "dataHandlerRowCount": data_handler_count,
        "otherHandlerRowCount": other_handler_count,
        "dataNoAdvanceRowCount": data_no_advance_count,
        "branchCapableRowCount": branch_capable_count,
        "branchTargetClassCounts": dict(sorted(branch_target_class_counts.items())),
        "branchTargetSectionCounts": dict(sorted(branch_target_section_counts.items())),
        "branchTargetSampleRows": branch_target_sample_rows,
        "branchToFillFragmentCount": len(branch_to_fill_rows),
        "branchToCurrentReaderCount": len(branch_to_reader_rows),
        "fixedFallthroughToFillCount": len(fixed_fallthrough_to_fill_rows),
        "immediatePredecessorRow": immediate_predecessor,
        "nearbyRows": nearby_rows,
        "branchToFillRows": branch_to_fill_rows[:12],
        "branchToCurrentReaderRows": branch_to_reader_rows[:12],
        "fixedFallthroughToFillRows": fixed_fallthrough_to_fill_rows[:12],
        "branchClosure": root_tail_branch_closure,
        "descriptorIsolatedTail": descriptor_isolated,
        "classification": "descriptor-isolated-tail" if descriptor_isolated else "tail-entry-candidate-present",
    }


def encoded_raw_scalar_rejection_summary(scan: dict | None) -> dict:
    scan = scan or {}
    rows = scan.get("rawScalarCandidateRows") or []
    handler_sections = [
        str(row.get("handlerSection") or "-")
        for row in rows
    ]
    kinds = [str(row.get("kind") or "-") for row in rows]
    no_fixed_advance_count = sum(1 for row in rows if not (row.get("handlerFixedAdvances") or []))
    no_branch_jump_count = sum(1 for row in rows if row.get("handlerCanJumpToDwordAtPlus4") is not True)
    branch_attached_count = sum(1 for row in rows if row.get("startsAtBranchTargetField") is True)
    scalar_only_count = sum(
        1
        for row in rows
        if row.get("startsAtBranchTargetField") is not True
        and row.get("handlerCanJumpToDwordAtPlus4") is not True
        and not (row.get("handlerFixedAdvances") or [])
    )
    all_scalar_only = bool(rows) and scalar_only_count == len(rows)
    return {
        "available": bool(rows),
        "rawScalarCandidateCount": len(rows),
        "rawScalarKindCounts": count_by(kinds),
        "rawScalarHandlerSectionCounts": count_by(handler_sections),
        "rawScalarNoFixedAdvanceCount": no_fixed_advance_count,
        "rawScalarNoBranchJumpCount": no_branch_jump_count,
        "rawScalarBranchAttachedCount": branch_attached_count,
        "rawScalarScalarOnlyCount": scalar_only_count,
        "rawScalarAllScalarOnly": all_scalar_only,
        "classification": (
            "scalar-only-no-branch-or-fixed-advance" if all_scalar_only
            else "review-required"
            if rows
            else "no-raw-scalar-candidates"
        ),
        "promotionStatus": "blocked" if all_scalar_only else "review-required",
    }


def predecessor_dispatch_slice_dependency(dispatch_table_context: dict | None) -> dict:
    dispatch_table_context = dispatch_table_context or {}
    rows_by_role = {
        row.get("role"): row
        for row in dispatch_table_context.get("routeRelevantDispatchRows") or []
    }
    predecessor_rows = [
        rows_by_role.get("predecessor-root-entry-stop"),
        rows_by_role.get("predecessor-fill-fragment-stop"),
    ]
    predecessor_rows = [row for row in predecessor_rows if row]
    raw_general_differs_count = sum(
        1 for row in predecessor_rows if row.get("rawGeneralDiffersFromSlice") is True
    )
    slice_data_descriptor_count = sum(
        1 for row in predecessor_rows if row.get("sliceHandlerIsDataDescriptor") is True
    )
    raw_general_code_count = sum(
        1 for row in predecessor_rows if row.get("rawGeneralHandlerIsCode") is True
    )
    slice_generic_byte_reachable_count = sum(
        1 for row in predecessor_rows if row.get("sliceHandlerReachableViaGenericByteDispatch") is True
    )
    slice_requires_table_base_switch_count = sum(
        1 for row in predecessor_rows if row.get("sliceHandlerRequiresSaveSelectorTableBase") is True
    )
    direct_runtime_dispatch_proof_found = (
        dispatch_table_context.get("saveSelectorSliceDirectRuntimeDispatchProofFound") is True
    )
    dispatch_table_proof_found = dispatch_table_context.get("proofFound") is True
    dispatch_table_failed_gate_ids = dispatch_table_context.get("failedDispatchTableGateIds") or []
    dispatch_table_missing_evidence = dispatch_table_context.get("missingEvidence") or []
    dispatch_table_evidence_refs = dispatch_table_context.get("evidenceRefs") or []
    dynamic_table_base_candidate_found = (
        dispatch_table_context.get("dynamicSaveSelectorTableBaseSwitchStaticCandidateFound") is True
    )
    dynamic_indexed_dispatch_rows = (
        dispatch_table_context.get("dynamicIndexedDispatchRows") or []
    )
    dynamic_dword_scaled_dispatch_rows = (
        dispatch_table_context.get("dynamicDwordScaledDispatchRows") or []
    )
    if not dynamic_dword_scaled_dispatch_rows:
        dynamic_dword_scaled_dispatch_rows = [
            row for row in dynamic_indexed_dispatch_rows if row.get("isDwordScaledIndex") is True
        ]
    dynamic_indexed_dispatch_count = dispatch_table_context.get("dynamicIndexedDispatchRowCount") or 0
    dynamic_dword_scaled_dispatch_count = dispatch_table_context.get("dynamicDwordScaledDispatchRowCount") or 0
    dynamic_scope_table_callback_count = dispatch_table_context.get("dynamicScopeTableCallbackCount") or 0
    dynamic_table_immediate_near_count = (
        dispatch_table_context.get("dynamicSaveSelectorTableImmediateNearCount") or 0
    )
    dynamic_table_base_candidate_count = (
        dispatch_table_context.get("dynamicSaveSelectorTableBaseCandidateCount") or 0
    )
    arithmetic_table_base_row_count = (
        dispatch_table_context.get("saveSelectorTableBaseArithmeticRowCount") or 0
    )
    arithmetic_table_base_candidate_count = (
        dispatch_table_context.get("saveSelectorTableBaseArithmeticCandidateCount") or 0
    )
    arithmetic_table_base_candidate_found = (
        dispatch_table_context.get("saveSelectorTableBaseArithmeticCandidateFound") is True
    )
    arithmetic_table_base_candidate_rows = (
        dispatch_table_context.get("saveSelectorTableBaseArithmeticCandidateRows") or []
    )
    dynamic_scope_table_callback_rows = (
        dispatch_table_context.get("dynamicScopeTableCallbackRows") or []
    )
    dynamic_table_base_candidate_rows = (
        dispatch_table_context.get("dynamicSaveSelectorTableBaseCandidateRows") or []
    )
    dynamic_scope_table_callback_sites = [
        row.get("instructionVaHex")
        for row in dynamic_scope_table_callback_rows
        if row.get("instructionVaHex")
    ]
    dynamic_table_base_candidate_sites = [
        row.get("instructionVaHex")
        for row in dynamic_table_base_candidate_rows
        if row.get("instructionVaHex")
    ]
    depends_on_slice_model = (
        len(predecessor_rows) == 2
        and raw_general_differs_count == 2
        and slice_data_descriptor_count == 2
        and raw_general_code_count == 2
        and slice_requires_table_base_switch_count == 2
        and not direct_runtime_dispatch_proof_found
        and not dynamic_table_base_candidate_found
        and not arithmetic_table_base_candidate_found
    )
    table_base_rejection_classification = (
        "table-base-switch-required-no-dynamic-save-selector-candidate"
        if depends_on_slice_model
        and slice_generic_byte_reachable_count == 0
        and slice_requires_table_base_switch_count == len(predecessor_rows)
        and dynamic_indexed_dispatch_count > 0
        and dynamic_dword_scaled_dispatch_count == dynamic_indexed_dispatch_count
        and dynamic_table_immediate_near_count == 0
        and dynamic_table_base_candidate_count == 0
        and arithmetic_table_base_candidate_count == 0
        and not dynamic_table_base_candidate_found
        and not arithmetic_table_base_candidate_found
        else "review-required"
        if predecessor_rows
        else "not-available"
    )
    table_base_rejection = {
        "classification": table_base_rejection_classification,
        "predecessorDispatchSliceRowCount": len(predecessor_rows),
        "predecessorDispatchSliceRequiresTableBaseSwitchCount": (
            slice_requires_table_base_switch_count
        ),
        "predecessorDispatchSliceGenericByteReachableCount": (
            slice_generic_byte_reachable_count
        ),
        "predecessorDispatchDynamicIndexedDispatchRowCount": dynamic_indexed_dispatch_count,
        "predecessorDispatchDynamicDwordScaledDispatchRowCount": dynamic_dword_scaled_dispatch_count,
        "predecessorDispatchDynamicScopeTableCallbackCount": dynamic_scope_table_callback_count,
        "predecessorDispatchDynamicSaveSelectorTableImmediateNearCount": (
            dynamic_table_immediate_near_count
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount": (
            dynamic_table_base_candidate_count
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticRowCount": (
            arithmetic_table_base_row_count
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount": (
            arithmetic_table_base_candidate_count
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateFound": (
            arithmetic_table_base_candidate_found
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateRows": (
            arithmetic_table_base_candidate_rows
        ),
        "predecessorDispatchDynamicScopeTableCallbackSites": dynamic_scope_table_callback_sites,
        "predecessorDispatchDynamicScopeTableCallbackRows": dynamic_scope_table_callback_rows,
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites": (
            dynamic_table_base_candidate_sites
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateRows": (
            dynamic_table_base_candidate_rows
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound": (
            dynamic_table_base_candidate_found or arithmetic_table_base_candidate_found
        ),
        "promotionStatus": "blocked"
        if table_base_rejection_classification
        == "table-base-switch-required-no-dynamic-save-selector-candidate"
        else "review-required",
    }
    root_row = rows_by_role.get("predecessor-root-entry-stop") or {}
    fill_row = rows_by_role.get("predecessor-fill-fragment-stop") or {}
    table_base_audit_rows = []
    for row in predecessor_rows:
        table_base_audit_rows.append(
            {
                "kind": "slice-descriptor-row",
                "siteVaHex": row.get("siteVaHex"),
                "role": row.get("role"),
                "status": "slice-descriptor-requires-table-base"
                if row.get("sliceHandlerRequiresSaveSelectorTableBase") is True
                else "review-required",
                "lowByteOpcodeHex": row.get("lowByteOpcodeHex"),
                "saveHandlerVaHex": row.get("saveHandlerVaHex"),
                "saveHandlerSection": row.get("saveHandlerSection"),
                "rawGeneralHandlerVaHex": row.get("generalRawHandlerVaHex"),
                "rawGeneralHandlerSection": row.get("generalRawHandlerSection"),
                "rawGeneralDiffersFromSlice": row.get("rawGeneralDiffersFromSlice"),
                "sliceHandlerReachableViaGenericByteDispatch": row.get(
                    "sliceHandlerReachableViaGenericByteDispatch"
                ),
                "sliceHandlerRequiresSaveSelectorTableBase": row.get(
                    "sliceHandlerRequiresSaveSelectorTableBase"
                ),
                "candidateForSaveSelectorTableBase": False,
                "detail": (
                    f"role={row.get('role')}; opcode={row.get('lowByteOpcodeHex')}; "
                    f"slice={row.get('saveHandlerVaHex')}/{row.get('saveHandlerSection')}; "
                    "raw="
                    f"{row.get('generalRawHandlerVaHex')}/{row.get('generalRawHandlerSection')}; "
                    f"byteReachable={row.get('sliceHandlerReachableViaGenericByteDispatch')}; "
                    f"rawDiffers={row.get('rawGeneralDiffersFromSlice')}; "
                    f"requiresTableBase={row.get('sliceHandlerRequiresSaveSelectorTableBase')}"
                ),
            }
        )
    for row in dynamic_indexed_dispatch_rows:
        table_base_audit_rows.append(
            {
                "kind": "dynamic-indexed-dispatch-row",
                "siteVaHex": row.get("instructionVaHex"),
                "status": "seh-scope-callback-not-save-selector"
                if row.get("candidateForSaveSelectorTableBase") is False
                and str(row.get("contextClassification") or "").startswith("seh")
                else "review-required",
                "instructionVaHex": row.get("instructionVaHex"),
                "dispatchKind": row.get("kind"),
                "baseRegister": row.get("baseRegister"),
                "indexRegister": row.get("indexRegister"),
                "scale": row.get("scale"),
                "displacementHex": row.get("displacementHex"),
                "isDwordScaledIndex": row.get("isDwordScaledIndex"),
                "contextClassification": row.get("contextClassification"),
                "scopeTableStrideBytes": row.get("scopeTableStrideBytes"),
                "candidateForSaveSelectorTableBase": row.get("candidateForSaveSelectorTableBase"),
                "nearbySaveSelectorTableImmediateCount": row.get(
                    "nearbySaveSelectorTableImmediateCount"
                ),
                "nearbyKnownDispatchTableImmediateCount": row.get(
                    "nearbyKnownDispatchTableImmediateCount"
                ),
                "hasSehRegistrationPattern": row.get("hasSehRegistrationPattern"),
                "hasSentinelMinusOneStateCheck": row.get("hasSentinelMinusOneStateCheck"),
                "hasTripletIndexScalePattern": row.get("hasTripletIndexScalePattern"),
                "detail": (
                    f"form={row.get('kind')} "
                    f"{row.get('baseRegister')}+{row.get('indexRegister')}*{row.get('scale')}"
                    f"{row.get('displacementHex')}; "
                    f"dwordScaled={row.get('isDwordScaledIndex')}; "
                    f"context={row.get('contextClassification')}; "
                    f"stride={row.get('scopeTableStrideBytes')}; "
                    f"saveImm={row.get('nearbySaveSelectorTableImmediateCount')}; "
                    f"knownImm={row.get('nearbyKnownDispatchTableImmediateCount')}; "
                    f"candidate={row.get('candidateForSaveSelectorTableBase')}; "
                    f"seh={row.get('hasSehRegistrationPattern')}; "
                    f"sentinel={row.get('hasSentinelMinusOneStateCheck')}; "
                    f"triplet={row.get('hasTripletIndexScalePattern')}"
                ),
            }
        )
    table_base_audit_rows.append(
        {
            "kind": "table-base-arithmetic-scan",
            "siteVaHex": "-",
            "status": "no-save-selector-table-base-arithmetic-candidate"
            if arithmetic_table_base_candidate_count == 0
            and arithmetic_table_base_candidate_found is False
            else "review-required",
            "rowCount": arithmetic_table_base_row_count,
            "candidateCount": arithmetic_table_base_candidate_count,
            "candidateFound": arithmetic_table_base_candidate_found,
            "candidateRowCount": len(arithmetic_table_base_candidate_rows),
            "detail": (
                f"rows={arithmetic_table_base_row_count}; "
                f"candidates={arithmetic_table_base_candidate_count}; "
                f"found={arithmetic_table_base_candidate_found}; "
                f"candidateRows={len(arithmetic_table_base_candidate_rows)}"
            ),
        }
    )
    table_base_rejection["predecessorDispatchDynamicIndexedDispatchRows"] = (
        dynamic_indexed_dispatch_rows
    )
    table_base_rejection["predecessorDispatchDynamicDwordScaledDispatchRows"] = (
        dynamic_dword_scaled_dispatch_rows
    )
    table_base_rejection["predecessorDispatchTableBaseAuditRows"] = table_base_audit_rows
    return {
        "available": bool(predecessor_rows),
        "proofFound": dispatch_table_proof_found,
        "dispatchTableProofFound": dispatch_table_proof_found,
        "failedDispatchTableGateIds": dispatch_table_failed_gate_ids,
        "missingEvidence": dispatch_table_missing_evidence,
        "evidenceRefs": dispatch_table_evidence_refs,
        "evidenceRefCount": len(dispatch_table_evidence_refs),
        "saveSelectorSliceDirectRuntimeDispatchProofFound": direct_runtime_dispatch_proof_found,
        "saveSelectorDispatchRuntimeProofFound": dispatch_table_context.get(
            "saveSelectorDispatchRuntimeProofFound",
            direct_runtime_dispatch_proof_found,
        ),
        "descriptorBoundaryDependsOnSaveSelectorSliceModel": depends_on_slice_model,
        "predecessorDispatchSliceRowCount": len(predecessor_rows),
        "predecessorDispatchSliceDataDescriptorCount": slice_data_descriptor_count,
        "predecessorDispatchRawGeneralCodeCount": raw_general_code_count,
        "predecessorDispatchRawGeneralDiffersFromSliceCount": raw_general_differs_count,
        "predecessorDispatchSliceGenericByteReachableCount": slice_generic_byte_reachable_count,
        "predecessorDispatchSliceRequiresTableBaseSwitchCount": (
            slice_requires_table_base_switch_count
        ),
        "predecessorDispatchDynamicIndexedDispatchRowCount": dynamic_indexed_dispatch_count,
        "predecessorDispatchDynamicDwordScaledDispatchRowCount": dynamic_dword_scaled_dispatch_count,
        "predecessorDispatchDynamicIndexedDispatchRows": dynamic_indexed_dispatch_rows,
        "predecessorDispatchDynamicDwordScaledDispatchRows": dynamic_dword_scaled_dispatch_rows,
        "predecessorDispatchDynamicScopeTableCallbackCount": dynamic_scope_table_callback_count,
        "predecessorDispatchDynamicSaveSelectorTableImmediateNearCount": (
            dynamic_table_immediate_near_count
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount": (
            dynamic_table_base_candidate_count
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticRowCount": (
            arithmetic_table_base_row_count
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount": (
            arithmetic_table_base_candidate_count
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateFound": (
            arithmetic_table_base_candidate_found
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateRows": (
            arithmetic_table_base_candidate_rows
        ),
        "predecessorDispatchDynamicScopeTableCallbackSites": dynamic_scope_table_callback_sites,
        "predecessorDispatchDynamicScopeTableCallbackRows": dynamic_scope_table_callback_rows,
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites": (
            dynamic_table_base_candidate_sites
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateRows": (
            dynamic_table_base_candidate_rows
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound": (
            dynamic_table_base_candidate_found or arithmetic_table_base_candidate_found
        ),
        "predecessorDispatchTableBaseRejection": table_base_rejection,
        "predecessorDispatchTableBaseRejectionClassification": (
            table_base_rejection_classification
        ),
        "predecessorDispatchTableBaseAuditRows": table_base_audit_rows,
        "predecessorDispatchRows": predecessor_rows,
        "predecessorRootStopSliceHandlerHex": root_row.get("saveHandlerVaHex"),
        "predecessorRootStopSliceHandlerSection": root_row.get("saveHandlerSection"),
        "predecessorRootStopRawGeneralHandlerHex": root_row.get("generalRawHandlerVaHex"),
        "predecessorRootStopRawGeneralHandlerSection": root_row.get("generalRawHandlerSection"),
        "predecessorRootStopSliceGenericByteReachable": root_row.get(
            "sliceHandlerReachableViaGenericByteDispatch"
        ),
        "predecessorRootStopSliceRequiresTableBaseSwitch": root_row.get(
            "sliceHandlerRequiresSaveSelectorTableBase"
        ),
        "predecessorFillStopSliceHandlerHex": fill_row.get("saveHandlerVaHex"),
        "predecessorFillStopSliceHandlerSection": fill_row.get("saveHandlerSection"),
        "predecessorFillStopRawGeneralHandlerHex": fill_row.get("generalRawHandlerVaHex"),
        "predecessorFillStopRawGeneralHandlerSection": fill_row.get("generalRawHandlerSection"),
        "predecessorFillStopSliceGenericByteReachable": fill_row.get(
            "sliceHandlerReachableViaGenericByteDispatch"
        ),
        "predecessorFillStopSliceRequiresTableBaseSwitch": fill_row.get(
            "sliceHandlerRequiresSaveSelectorTableBase"
        ),
        "promotionStatus": "blocked" if depends_on_slice_model else "review-required",
    }


def fixed_reachability(
    exe: bytes,
    sections: list[dict],
    start_va: int | None,
    root_end_va: int | None,
    target_hexes: list[str],
    max_nodes: int = 512,
) -> dict:
    if start_va is None or root_end_va is None:
        return {"available": False}
    targets = {target for target in (hex_to_int(value) for value in target_hexes) if target is not None}
    queue = [(start_va, [])]
    seen: set[int] = set()
    reached: dict[int, list[int]] = {}
    stops = []
    while queue and len(seen) < max_nodes:
        va, path = queue.pop(0)
        if va in seen:
            continue
        seen.add(va)
        new_path = path + [va]
        if va in targets:
            reached[va] = new_path
        if not (start_va <= va < root_end_va):
            stops.append({"vaHex": f"0x{va:08x}", "reason": "outside-root-range"})
            continue
        opcode = byte_at(exe, sections, va)
        value = u32_at(exe, sections, va)
        if opcode is None or value is None:
            stops.append({"vaHex": f"0x{va:08x}", "reason": "unreadable"})
            continue
        handler = handler_entry(exe, sections, opcode)
        advances = handler.get("fixedAdvances") or []
        next_vas = []
        if handler.get("canJumpToDwordAtPlus4"):
            branch_target = u32_at(exe, sections, va + 4)
            if branch_target is not None and va_to_offset(sections, branch_target) is not None:
                next_vas.append(branch_target)
            next_vas.append(va + (advances[0] if len(advances) == 1 else 8))
        elif len(advances) == 1:
            next_vas.append(va + advances[0])
        else:
            stops.append({
                "vaHex": f"0x{va:08x}",
                "reason": "no-fixed-advance" if not advances else "multiple-advances",
                "valueHex": f"0x{value:08x}",
                "opcodeHex": f"0x{opcode:02x}",
                "handlerVaHex": handler.get("handlerVaHex"),
            })
            continue
        for next_va in next_vas:
            if next_va not in seen:
                queue.append((next_va, new_path))
    return {
        "available": True,
        "startHex": f"0x{start_va:08x}",
        "rootEndHex": f"0x{root_end_va:08x}",
        "visitedNodeCount": len(seen),
        "maxNodes": max_nodes,
        "targetHexes": target_hexes,
        "reachableTargetHexes": [f"0x{target:08x}" for target in sorted(reached)],
        "allTargetsReachable": targets == set(reached),
        "stopRows": stops[:12],
    }


def current_reader_hex(
    predecessor_branch_state_execution_gap: dict,
    frontier_reader_branch_context: dict | None,
) -> str:
    return (
        predecessor_branch_state_execution_gap.get("currentReaderHex")
        or (frontier_reader_branch_context or {}).get("readerVaHex")
        or "0x00542b0c"
    )


def build_summary(
    exe: bytes,
    predecessor_branch_state_execution_gap: dict,
    predecessor_tail_reset: dict,
    secondary_global_reset_gap: dict,
    predecessor_persistence_gap: dict,
    predecessor_route_order: dict,
    merge_execution_gap: dict,
    merge_runtime_context: dict | None = None,
    merge_closure_context: dict | None = None,
    frontier_reader_branch_context: dict | None = None,
    data_descriptor_opcode_map: dict | None = None,
    dispatch_table_context: dict | None = None,
    max_steps: int = 8,
    field_entry_sequence_scan: dict | None = None,
    coordinate_source_scan: dict | None = None,
) -> dict:
    merge_runtime_context = merge_runtime_context or {}
    merge_closure_context = merge_closure_context or {}
    fill_sites = (
        predecessor_branch_state_execution_gap.get("predecessorFillVas")
        or secondary_global_reset_gap.get("predecessorFillVas")
        or predecessor_tail_reset.get("predecessorFillVas")
        or []
    )
    fill_start_hex = fill_sites[0] if fill_sites else None
    fill_start = hex_to_int(fill_start_hex)
    sections = read_sections(exe)
    strings = find_cns_strings(exe, sections)
    local_trace = trace_stream(exe, sections, strings, fill_start, max_steps) if fill_start is not None else []
    compact_trace = [compact_trace_row(row) for row in local_trace]
    predecessor_root_start = hex_to_int(
        predecessor_branch_state_execution_gap.get("predecessorRootHex")
        or predecessor_persistence_gap.get("predecessorRootHex")
    )
    predecessor_root_end = hex_to_int(
        predecessor_tail_reset.get("nextRootHex")
        or (predecessor_tail_reset.get("predecessorRootRangeHex") or "..").split("..")[-1]
    )
    root_reachability = fixed_reachability(
        exe,
        sections,
        predecessor_root_start,
        predecessor_root_end,
        fill_sites,
    )
    direct_fill_site_ref_counts = direct_dword_ref_counts(exe, sections, fill_sites)
    trace_vas = {row.get("vaHex") for row in compact_trace}
    stop = stop_row(compact_trace)
    reader_hex = current_reader_hex(predecessor_branch_state_execution_gap, frontier_reader_branch_context)
    stop_va = hex_to_int(stop.get("vaHex"))
    fill_entry_candidates = fill_entry_candidate_scan(
        exe,
        sections,
        predecessor_root_start,
        predecessor_root_end,
        fill_start,
        stop_va,
    )
    root_stop_va = hex_to_int(((root_reachability.get("stopRows") or [{}])[0]).get("vaHex"))
    encoded_fill_entry_candidates = encoded_fill_entry_candidate_scan(
        exe,
        sections,
        predecessor_root_start,
        root_stop_va,
        fill_start,
        stop_va,
    )
    encoded_raw_scalar_rejection = encoded_raw_scalar_rejection_summary(
        encoded_fill_entry_candidates
    )
    root_tail_isolation = root_tail_isolation_scan(
        exe,
        sections,
        root_stop_va,
        fill_start,
        stop_va,
        hex_to_int(reader_hex),
    )
    data_descriptor_opcode_map = data_descriptor_opcode_map or {}
    descriptor_sites = {
        row.get("role"): row for row in data_descriptor_opcode_map.get("sites") or []
    }
    predecessor_root_stop_descriptor = descriptor_sites.get("predecessor-root-entry-stop") or {}
    predecessor_fill_stop_descriptor = descriptor_sites.get("predecessor-fill-fragment-stop") or {}
    predecessor_descriptor_boundaries_proven = (
        data_descriptor_opcode_map.get("predecessorRootStopIsDataDescriptor") is True
        and data_descriptor_opcode_map.get("predecessorFillStopIsDataDescriptor") is True
    )
    predecessor_descriptor_boundary_detail = (
        "rootStop="
        f"{predecessor_root_stop_descriptor.get('siteVaHex')}/"
        f"{predecessor_root_stop_descriptor.get('lowByteOpcodeHex')}->"
        f"{predecessor_root_stop_descriptor.get('handlerValueHex')} "
        f"{predecessor_root_stop_descriptor.get('handlerSection')}; "
        "fillStop="
        f"{predecessor_fill_stop_descriptor.get('siteVaHex')}/"
        f"{predecessor_fill_stop_descriptor.get('lowByteOpcodeHex')}->"
        f"{predecessor_fill_stop_descriptor.get('handlerValueHex')} "
        f"{predecessor_fill_stop_descriptor.get('handlerSection')}; "
        "d0Opcodes="
        f"{list_text(data_descriptor_opcode_map.get('d0DescriptorSharedHandlerOpcodes'))}; "
        "c0Opcodes="
        f"{list_text(data_descriptor_opcode_map.get('c0DescriptorSharedHandlerOpcodes'))}"
    )
    dispatch_slice_dependency = predecessor_dispatch_slice_dependency(dispatch_table_context)
    predecessor_dispatch_slice_detail = (
        "sliceRuntimeProof="
        f"{dispatch_slice_dependency.get('saveSelectorSliceDirectRuntimeDispatchProofFound')}; "
        "dispatchTableProof="
        f"{dispatch_slice_dependency.get('dispatchTableProofFound')}; "
        "dispatchFailedGates="
        f"{list_text(dispatch_slice_dependency.get('failedDispatchTableGateIds'))}; "
        "dispatchMissingEvidenceCount="
        f"{len(dispatch_slice_dependency.get('missingEvidence') or [])}; "
        "dispatchEvidenceRefs="
        f"{dispatch_slice_dependency.get('evidenceRefCount')}; "
        "descriptorDependsOnSlice="
        f"{dispatch_slice_dependency.get('descriptorBoundaryDependsOnSaveSelectorSliceModel')}; "
        "rows="
        f"{dispatch_slice_dependency.get('predecessorDispatchSliceRowCount')}; "
        "sliceData="
        f"{dispatch_slice_dependency.get('predecessorDispatchSliceDataDescriptorCount')}; "
        "rawCode="
        f"{dispatch_slice_dependency.get('predecessorDispatchRawGeneralCodeCount')}; "
        "rawDiffers="
        f"{dispatch_slice_dependency.get('predecessorDispatchRawGeneralDiffersFromSliceCount')}; "
        "byteReachable="
        f"{dispatch_slice_dependency.get('predecessorDispatchSliceGenericByteReachableCount')}; "
        "requiresTableBase="
        f"{dispatch_slice_dependency.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')}; "
        "dynamicDispatches="
        f"{dispatch_slice_dependency.get('predecessorDispatchDynamicIndexedDispatchRowCount')}/"
        f"{dispatch_slice_dependency.get('predecessorDispatchDynamicScopeTableCallbackCount')}/"
        f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')}; "
        "scopeSites="
        f"{list_text(dispatch_slice_dependency.get('predecessorDispatchDynamicScopeTableCallbackSites'))}; "
        "dynamicTableBaseCandidate="
        f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}; "
        "dynamicTableBaseCandidateCount="
        f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')}; "
        "tableBaseArithmeticRows="
        f"{dispatch_slice_dependency.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')}; "
        "tableBaseArithmeticCandidates="
        f"{dispatch_slice_dependency.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')}; "
        "dynamicTableBaseCandidateSites="
        f"{list_text(dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites'))}; "
        "tableBaseReject="
        f"{dispatch_slice_dependency.get('predecessorDispatchTableBaseRejectionClassification')}; "
        "rootSlice/raw="
        f"{dispatch_slice_dependency.get('predecessorRootStopSliceHandlerHex')}/"
        f"{dispatch_slice_dependency.get('predecessorRootStopRawGeneralHandlerHex')}; "
        "fillSlice/raw="
        f"{dispatch_slice_dependency.get('predecessorFillStopSliceHandlerHex')}/"
        f"{dispatch_slice_dependency.get('predecessorFillStopRawGeneralHandlerHex')}"
    )
    raw_generic_contrast = raw_generic_handler_contrast(
        exe,
        sections,
        dispatch_slice_dependency,
        predecessor_root_start,
        root_stop_va,
        fill_sites,
        stop_va,
        hex_to_int(
            predecessor_branch_state_execution_gap.get("currentRootHex")
            or predecessor_persistence_gap.get("currentRootHex")
        ),
        hex_to_int(reader_hex),
    )
    raw_generic_contrast_detail = (
        f"handlers={raw_generic_contrast.get('handlerCount')}; "
        f"routeImm={raw_generic_contrast.get('routeImmediateHitCount')}; "
        f"fillImm={raw_generic_contrast.get('fillImmediateHitCount')}; "
        f"currentImm={raw_generic_contrast.get('currentImmediateHitCount')}; "
        f"selectedPtrImm={raw_generic_contrast.get('selectedPointerImmediateHitCount')}; "
        f"branchStateImm={raw_generic_contrast.get('branchStateImmediateHitCount')}; "
        f"directCalls={raw_generic_contrast.get('directCallCount')}; "
        f"mappedCalls={raw_generic_contrast.get('mappedDirectCallCount')}; "
        f"oneHopRouteImm={raw_generic_contrast.get('oneHopRouteImmediateHitCount')}; "
        f"oneHopFillImm={raw_generic_contrast.get('oneHopFillImmediateHitCount')}; "
        f"oneHopRouteTransfers={raw_generic_contrast.get('oneHopRouteDirectTransferHitCount')}; "
        f"routeTransfers={raw_generic_contrast.get('routeDirectTransferHitCount')}; "
        f"fillTransfers={raw_generic_contrast.get('fillDirectTransferHitCount')}; "
        f"callGraph={raw_generic_contrast.get('callGraphClassification')}; "
        f"callGraphDepth={raw_generic_contrast.get('callGraphMaxDepth')}; "
        f"callGraphFunctions={raw_generic_contrast.get('callGraphReachableFunctionCount')}; "
        f"callGraphEdges={raw_generic_contrast.get('callGraphDirectCallEdgeCount')}; "
        "callGraphRoute/fill/currentImm="
        f"{raw_generic_contrast.get('callGraphRouteImmediateHitCount')}/"
        f"{raw_generic_contrast.get('callGraphFillImmediateHitCount')}/"
        f"{raw_generic_contrast.get('callGraphCurrentImmediateHitCount')}; "
        "callGraphSelected/branchImm="
        f"{raw_generic_contrast.get('callGraphSelectedPointerImmediateHitCount')}/"
        f"{raw_generic_contrast.get('callGraphBranchStateImmediateHitCount')}; "
        "callGraphRoute/fillTransfers="
        f"{raw_generic_contrast.get('callGraphRouteDirectTransferHitCount')}/"
        f"{raw_generic_contrast.get('callGraphFillDirectTransferHitCount')}; "
        f"callGraphProof={raw_generic_contrast.get('callGraphProofFound')}; "
        "depthSensitivity="
        f"{raw_generic_contrast.get('callGraphDepthSensitivityMaxDepthChecked')}/"
        f"{raw_generic_contrast.get('callGraphDepthSensitivityProofAbsentAcrossCheckedDepths')}/"
        f"{raw_generic_contrast.get('callGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth')}; "
        f"routeProof={raw_generic_contrast.get('routeProofFound')}; "
        f"maxWindow=0x{RAW_GENERIC_MAX_BYTES:x}"
    )
    local_trace_contains_all_fill_sites = bool(fill_sites) and all(site in trace_vas for site in fill_sites)
    local_trace_reaches_reader = reader_hex in trace_vas
    runtime_split = predecessor_branch_state_execution_gap.get("runtimeBranchStateSplit") or {}
    public_predecessor_reached = runtime_split.get("publicPredecessorReached") is True
    runtime_observed_fill = (
        predecessor_branch_state_execution_gap.get("runtimePredecessorFillObserved") is True
        or runtime_split.get("observedMatchesFill") is True
    )
    field_entry_sequence_context = compact_field_entry_sequence_context(field_entry_sequence_scan)
    field_entry_route_candidate_found = (
        int(field_entry_sequence_context.get("fieldEntryCandidateCount") or 0) > 0
        or int(field_entry_sequence_context.get("snapshotRouteCandidateCount") or 0) > 0
        or "2:0" in (field_entry_sequence_context.get("finalSelectorCounts") or {})
        or "2:0" in (field_entry_sequence_context.get("snapshotSelectorCounts") or {})
    )
    field_entry_input_status = (
        "field-entry-route-candidate-found"
        if field_entry_route_candidate_found
        else "field-entry-not-found"
        if field_entry_sequence_context.get("sequenceCount") is not None
        else "field-entry-scan-missing"
    )
    coordinate_source_context = compact_coordinate_source_context(coordinate_source_scan)
    coordinate_source_status = (
        "coordinate-source-diagnostic-only"
        if coordinate_source_context.get("promotionStatus") == "diagnostic-only"
        else "coordinate-source-review"
        if coordinate_source_context.get("classification")
        else "coordinate-source-scan-missing"
    )
    branch_state_all_zero = (
        predecessor_branch_state_execution_gap.get("publicPredecessorBranchStateAllZero") is True
        or runtime_split.get("observedAllZero") is True
    )
    static_no_local_tail_reset = (
        predecessor_tail_reset.get("localTailResetFound") is False
        and predecessor_tail_reset.get("tailValidSecondaryFillCount") == 0
    )
    static_reset_scope_closed = (
        predecessor_branch_state_execution_gap.get("closedStaticResetScope") is True
        or secondary_global_reset_gap.get("closedStaticResetScope") is True
    )
    selector_order_reset_gap_closed = (
        predecessor_branch_state_execution_gap.get("selectorOrderResetGapClosed") is True
        or secondary_global_reset_gap.get("selectorOrderResetGapClosed") is True
    )
    predecessor_to_current_forward_bridge_found = (
        int(merge_execution_gap.get("predecessorToCurrentHitCount") or 0) > 0
        or int(merge_execution_gap.get("forwardMergeBridgeHitCount") or 0) > 0
        or merge_execution_gap.get("directMergeExecutionBridgeFound") is True
    )
    route_order_proven = predecessor_route_order.get("routeOrderProven") is True
    selector_merge_runtime_proof_found = (
        merge_runtime_context.get("selectorMergeRuntimeProofFound") is True
    )
    selector_merge_closure_proof_found = (
        merge_closure_context.get("selectorMergeClosureProofFound") is True
    )
    predecessor_persistence_usable_for_current = (
        merge_closure_context.get("predecessorPersistenceUsableForCurrent") is True
    )
    selector_merge_shape_only = (
        merge_runtime_context.get("mergeShapeOnly") is True
        or merge_closure_context.get("mergeShapeOnly") is True
    )
    selector_merge_forward_bridge_absent = (
        merge_runtime_context.get("forwardBridgeAbsent") is True
        or merge_closure_context.get("forwardBridgeAbsent") is True
    )
    selector_merge_reverse_reuse_before_fill_only = (
        merge_runtime_context.get("reverseReuseBeforeFillOnly") is True
        or merge_closure_context.get("reverseReuseBeforeFillOnly") is True
    )
    selector_merge_gap_open = (
        predecessor_branch_state_execution_gap.get("selectorMergeGapOpen") is True
        or predecessor_route_order.get("selectorMergeGapOpen") is True
        or merge_execution_gap.get("selectorMergeGapOpen") is True
        or merge_runtime_context.get("selectorMergeGapOpen") is True
        or merge_closure_context.get("selectorMergeGapOpen") is True
    )
    route_order_and_selector_merge_closed = route_order_proven and not selector_merge_gap_open
    proof_found = (
        local_trace_reaches_reader
        and runtime_observed_fill
        and predecessor_to_current_forward_bridge_found
        and route_order_and_selector_merge_closed
    )
    evidence = [
        {
            "kind": "local-fill-stream",
            "status": "fills-then-descriptor-boundary"
            if local_trace_contains_all_fill_sites and stop.get("stopReason") == "no-fixed-advance"
            else "not-proven",
            "detail": (
                f"start={fill_start_hex}; sites={list_text(fill_sites)}; "
                f"containsAllFillSites={local_trace_contains_all_fill_sites}; "
                f"stop={stop.get('vaHex')} reason={stop.get('stopReason')} "
                f"handler={stop.get('handlerVaHex')}; reachesReader={local_trace_reaches_reader}"
            ),
        },
        {
            "kind": "root-entry-fixed-traversal",
            "status": "fill-sites-not-reached"
            if root_reachability.get("available")
            and root_reachability.get("allTargetsReachable") is False
            else "all-fill-sites-reached",
            "detail": (
                f"start={root_reachability.get('startHex')}; "
                f"rootEnd={root_reachability.get('rootEndHex')}; "
                f"visited={root_reachability.get('visitedNodeCount')}; "
                f"targets={list_text(root_reachability.get('targetHexes'))}; "
                f"reached={list_text(root_reachability.get('reachableTargetHexes'))}; "
                f"stops={list_text([row.get('vaHex') for row in root_reachability.get('stopRows') or []])}; "
                f"directFillRefs={direct_fill_site_ref_counts}"
            ),
        },
        {
            "kind": "fill-fragment-entry-candidates",
            "status": "no-direct-entry-candidates"
            if fill_entry_candidates.get("available")
            and fill_entry_candidates.get("entryCandidateFound") is False
            else "entry-candidate-found",
            "detail": (
                f"range={fill_entry_candidates.get('fillFragmentRangeHex')}; "
                f"allDwordRefs={fill_entry_candidates.get('allDwordRefCount')}; "
                "rootRangeDwordRefs="
                f"{fill_entry_candidates.get('predecessorRootRangeDwordRefCount')}; "
                "rootBranchTargets="
                f"{fill_entry_candidates.get('rootBranchTargetCandidateCount')}"
            ),
        },
        {
            "kind": "encoded-fill-entry-candidates",
            "status": encoded_fill_entry_candidates.get("classification") or "not-available",
            "detail": (
                f"range={encoded_fill_entry_candidates.get('scanRangeHex')}; "
                f"targetLow16={list_text(encoded_fill_entry_candidates.get('targetLow16Hexes'))}; "
                "rawScalars="
                f"{encoded_fill_entry_candidates.get('rawScalarCandidateCount')}; "
                "rootTailRawScalars="
                f"{encoded_fill_entry_candidates.get('rootTailRawScalarCandidateCount')}; "
                "branchAttached="
                f"{encoded_fill_entry_candidates.get('branchAttachedEncodedFieldCount')}; "
                "modeledControlFlow="
                f"{encoded_fill_entry_candidates.get('modeledControlFlowCandidateCount')}; "
                f"promoting={encoded_fill_entry_candidates.get('promotingCandidateCount')}"
            ),
        },
        {
            "kind": "encoded-raw-scalar-rejection",
            "status": encoded_raw_scalar_rejection.get("classification") or "not-available",
            "detail": (
                f"rawScalars={encoded_raw_scalar_rejection.get('rawScalarCandidateCount')}; "
                f"kinds={encoded_raw_scalar_rejection.get('rawScalarKindCounts')}; "
                f"sections={encoded_raw_scalar_rejection.get('rawScalarHandlerSectionCounts')}; "
                "noFixed/noBranch/branchAttached/scalarOnly="
                f"{encoded_raw_scalar_rejection.get('rawScalarNoFixedAdvanceCount')}/"
                f"{encoded_raw_scalar_rejection.get('rawScalarNoBranchJumpCount')}/"
                f"{encoded_raw_scalar_rejection.get('rawScalarBranchAttachedCount')}/"
                f"{encoded_raw_scalar_rejection.get('rawScalarScalarOnlyCount')}"
            ),
        },
        {
            "kind": "root-tail-isolation",
            "status": root_tail_isolation.get("classification") or "not-available",
            "detail": (
                f"range={root_tail_isolation.get('rangeHex')}; "
                f"distance={root_tail_isolation.get('distanceHex')}; "
                f"rows={root_tail_isolation.get('dwordCount')}; "
                "handlers="
                f"{root_tail_isolation.get('textHandlerRowCount')}/"
                f"{root_tail_isolation.get('dataHandlerRowCount')}/"
                f"{root_tail_isolation.get('otherHandlerRowCount')}; "
                f"branchRows={root_tail_isolation.get('branchCapableRowCount')}; "
                f"branchTargetClasses={root_tail_isolation.get('branchTargetClassCounts')}; "
                f"branchTargetSections={root_tail_isolation.get('branchTargetSectionCounts')}; "
                f"branchToFill={root_tail_isolation.get('branchToFillFragmentCount')}; "
                f"branchToReader={root_tail_isolation.get('branchToCurrentReaderCount')}; "
                f"fixedToFill={root_tail_isolation.get('fixedFallthroughToFillCount')}; "
                "branchClosure="
                f"{(root_tail_isolation.get('branchClosure') or {}).get('branchSeedCount')}/"
                f"{(root_tail_isolation.get('branchClosure') or {}).get('edgeCount')}/"
                f"{(root_tail_isolation.get('branchClosure') or {}).get('branchSeedReachFillCount')}/"
                f"{(root_tail_isolation.get('branchClosure') or {}).get('branchSeedReachCurrentReaderCount')}; "
                "branchClosureOutside="
                f"{(root_tail_isolation.get('branchClosure') or {}).get('outsideSuccessorCount')}/"
                f"{(root_tail_isolation.get('branchClosure') or {}).get('outsideSuccessorClassCounts')}/"
                f"{(root_tail_isolation.get('branchClosure') or {}).get('outsideSuccessorSectionCounts')}; "
                "immediateBeforeFill="
                f"{(root_tail_isolation.get('immediatePredecessorRow') or {}).get('vaHex')}:"
                f"{(root_tail_isolation.get('immediatePredecessorRow') or {}).get('opcodeHex')}/"
                f"{(root_tail_isolation.get('immediatePredecessorRow') or {}).get('handlerSection')}"
            ),
        },
        {
            "kind": "predecessor-data-descriptor-boundaries",
            "status": "data-descriptors-not-control-flow"
            if predecessor_descriptor_boundaries_proven
            else "descriptor-boundary-unverified",
            "detail": predecessor_descriptor_boundary_detail,
        },
        {
            "kind": "predecessor-dispatch-slice-dependency",
            "status": "slice-runtime-proof-missing"
            if dispatch_slice_dependency.get("descriptorBoundaryDependsOnSaveSelectorSliceModel")
            else "review-required",
            "detail": predecessor_dispatch_slice_detail,
        },
        {
            "kind": "predecessor-dispatch-table-base-rejection",
            "status": dispatch_slice_dependency.get(
                "predecessorDispatchTableBaseRejectionClassification"
            )
            or "not-available",
            "detail": (
                "requiresTableBase="
                f"{dispatch_slice_dependency.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')}; "
                "byteReachable="
                f"{dispatch_slice_dependency.get('predecessorDispatchSliceGenericByteReachableCount')}; "
                "dynamicDispatches="
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicIndexedDispatchRowCount')}/"
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicDwordScaledDispatchRowCount')}; "
                "scopeCallbacks="
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicScopeTableCallbackCount')}; "
                "scopeSites="
                f"{list_text(dispatch_slice_dependency.get('predecessorDispatchDynamicScopeTableCallbackSites'))}; "
                "tableImmediateNear="
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')}; "
                "tableBaseCandidates="
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')}; "
                "tableBaseCandidateSites="
                f"{list_text(dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites'))}; "
                "tableBaseStaticCandidate="
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}"
            ),
        },
        {
            "kind": "predecessor-raw-generic-handler-contrast",
            "status": raw_generic_contrast.get("classification") or "not-available",
            "detail": raw_generic_contrast_detail,
        },
        {
            "kind": "runtime-branch-state",
            "status": "public-predecessor-fill-not-observed"
            if public_predecessor_reached and not runtime_observed_fill and branch_state_all_zero
            else "not-classified",
            "detail": (
                f"publicPredecessorReached={public_predecessor_reached}; "
                f"runtimeObservedFill={runtime_observed_fill}; "
                f"branchStateAllZero={branch_state_all_zero}; "
                f"split={runtime_split.get('classification')}"
            ),
        },
        {
            "kind": "runtime-field-entry-input",
            "status": field_entry_input_status,
            "detail": (
                f"sequences={field_entry_sequence_context.get('sequenceCount')}; "
                f"fieldEntryCandidates={field_entry_sequence_context.get('fieldEntryCandidateCount')}; "
                f"fieldEntryNames={list_text(field_entry_sequence_context.get('fieldEntryCandidateNames'))}; "
                f"snapshots={field_entry_sequence_context.get('snapshotCount')}; "
                f"snapshotRouteCandidates={field_entry_sequence_context.get('snapshotRouteCandidateCount')}; "
                f"snapshotRouteNames={list_text(field_entry_sequence_context.get('snapshotRouteCandidateNames'))}; "
                f"finalSelectors={field_entry_sequence_context.get('finalSelectorCounts')}; "
                f"finalCameras={field_entry_sequence_context.get('finalCameraTileCounts')}; "
                f"snapshotSelectors={field_entry_sequence_context.get('snapshotSelectorCounts')}; "
                f"snapshotCameras={field_entry_sequence_context.get('snapshotCameraTileCounts')}; "
                f"classes={field_entry_sequence_context.get('classificationCounts')}; "
                f"promotes={field_entry_sequence_context.get('promotionStatus')}"
            ),
        },
        {
            "kind": "runtime-coordinate-source",
            "status": coordinate_source_status,
            "detail": (
                f"classification={coordinate_source_context.get('classification')}; "
                "reject="
                f"{coordinate_source_context.get('coordinateSourceRejectionClassification')}; "
                f"finalSelector={coordinate_source_context.get('finalSelector')}; "
                f"finalCamera={coordinate_source_context.get('finalCameraTile')}; "
                "publicStartPtr/static/trail/image="
                f"{coordinate_source_context.get('publicSaveStartPointerTableTileHitCount')}/"
                f"{coordinate_source_context.get('publicSaveStartStaticBaseHitCount')}/"
                f"{coordinate_source_context.get('publicSaveStartTrailRingHitCount')}/"
                f"{coordinate_source_context.get('publicSaveStartImageHitCount')}; "
                "observedTrailPtr/static/trail/image="
                f"{coordinate_source_context.get('observedTrailPointerTableTileHitCount')}/"
                f"{coordinate_source_context.get('observedTrailStaticBaseHitCount')}/"
                f"{coordinate_source_context.get('observedTrailTrailRingHitCount')}/"
                f"{coordinate_source_context.get('observedTrailImageHitCount')}; "
                "reciprocalPtr/static/trail/image="
                f"{coordinate_source_context.get('reciprocalPointerTableTileHitCount')}/"
                f"{coordinate_source_context.get('reciprocalStaticBaseHitCount')}/"
                f"{coordinate_source_context.get('reciprocalTrailRingHitCount')}/"
                f"{coordinate_source_context.get('reciprocalImageHitCount')}; "
                f"promotes={coordinate_source_context.get('promotionStatus')}"
            ),
        },
        {
            "kind": "static-reset-window",
            "status": "closed-static-reset-window"
            if static_no_local_tail_reset and static_reset_scope_closed and selector_order_reset_gap_closed
            else "open",
            "detail": (
                f"localTailReset={predecessor_tail_reset.get('localTailResetFound')}; "
                f"tailValidSecondary={predecessor_tail_reset.get('tailValidSecondaryFillCount')}; "
                f"staticResetScopeClosed={static_reset_scope_closed}; "
                f"selectorOrderResetGapClosed={selector_order_reset_gap_closed}"
            ),
        },
        {
            "kind": "predecessor-current-bridge",
            "status": "no-forward-bridge" if not predecessor_to_current_forward_bridge_found else "found",
            "detail": (
                f"predecessorToCurrent={merge_execution_gap.get('predecessorToCurrentHitCount')}; "
                f"currentToPredecessor={merge_execution_gap.get('currentToPredecessorHitCount')}; "
                f"reverseBeforeFill={merge_execution_gap.get('currentToPredecessorBeforeFillHitCount')}; "
                f"reverseFillSite={merge_execution_gap.get('currentToPredecessorFillSiteHitCount')}; "
                f"forwardMergeBridge={merge_execution_gap.get('forwardMergeBridgeHitCount')}"
            ),
        },
        {
            "kind": "selector-route-order",
            "status": "route-order-unproven" if not route_order_proven else "proven",
            "detail": (
                f"routeOrderProven={route_order_proven}; "
                f"sourcePrevious={predecessor_route_order.get('sourceRoutePreviousSelector')}; "
                f"predecessorTargetOnly={predecessor_route_order.get('predecessorIsTargetSideOnly')}; "
                f"selectorMergeGapOpen={selector_merge_gap_open}"
            ),
        },
        {
            "kind": "selector-merge-closure",
            "status": "selector-merge-closed"
            if route_order_and_selector_merge_closed
            else "selector-merge-open",
            "detail": (
                f"shapeOnly={selector_merge_shape_only}; "
                f"forwardBridgeAbsent={selector_merge_forward_bridge_absent}; "
                f"reverseBeforeFillOnly={selector_merge_reverse_reuse_before_fill_only}; "
                f"runtimeProof={selector_merge_runtime_proof_found}; "
                f"closureProof={selector_merge_closure_proof_found}; "
                f"persistenceUsable={predecessor_persistence_usable_for_current}; "
                f"encodedBridge={merge_runtime_context.get('encodedMergeExecutionBridgeFound')}; "
                f"diagnosticExcluded={merge_runtime_context.get('constructedDiagnosticExcludedFromProof')}"
            ),
        },
    ]
    root_tail_branch_closure = root_tail_isolation.get("branchClosure") or {}
    proof_gate_rows = [
        {
            "id": "localFillStreamReachesCurrentReader",
            "pass": local_trace_reaches_reader,
            "status": "reaches-current-reader"
            if local_trace_reaches_reader
            else "stops-before-current-reader",
            "detail": (
                f"{fill_start_hex}->{stop.get('vaHex')} "
                f"reason={stop.get('stopReason')} reader={reader_hex}"
            ),
        },
        {
            "id": "rootEntryFixedTraversalReachesFillSites",
            "pass": root_reachability.get("allTargetsReachable") is True,
            "status": "reaches-fill-sites"
            if root_reachability.get("allTargetsReachable") is True
            else "fill-sites-not-reached",
            "detail": (
                f"visited={root_reachability.get('visitedNodeCount')} "
                f"reached={list_text(root_reachability.get('reachableTargetHexes'))}"
            ),
        },
        {
            "id": "fillFragmentEntryCandidateFound",
            "pass": fill_entry_candidates.get("entryCandidateFound") is True,
            "status": "entry-candidate-found"
            if fill_entry_candidates.get("entryCandidateFound") is True
            else "no-direct-entry-candidates",
            "detail": (
                f"dwordRefs={fill_entry_candidates.get('allDwordRefCount')} "
                f"rootBranchTargets={fill_entry_candidates.get('rootBranchTargetCandidateCount')}"
            ),
        },
        {
            "id": "encodedFillEntryControlFlowCandidateFound",
            "pass": int(encoded_fill_entry_candidates.get("promotingCandidateCount") or 0) > 0,
            "status": encoded_fill_entry_candidates.get("classification") or "not-available",
            "detail": (
                f"raw={encoded_fill_entry_candidates.get('rawScalarCandidateCount')} "
                f"branchAttached={encoded_fill_entry_candidates.get('branchAttachedEncodedFieldCount')} "
                f"modeled={encoded_fill_entry_candidates.get('modeledControlFlowCandidateCount')} "
                f"promoting={encoded_fill_entry_candidates.get('promotingCandidateCount')}"
            ),
        },
        {
            "id": "rootTailBranchClosureReachesFillOrReader",
            "pass": root_tail_branch_closure.get("proofFound") is True,
            "status": root_tail_branch_closure.get("classification") or "not-available",
            "detail": (
                f"seeds={root_tail_branch_closure.get('branchSeedCount')} "
                f"edges={root_tail_branch_closure.get('edgeCount')} "
                f"fill={root_tail_branch_closure.get('branchSeedReachFillCount')} "
                f"reader={root_tail_branch_closure.get('branchSeedReachCurrentReaderCount')}"
            ),
        },
        {
            "id": "descriptorSliceRuntimeDispatchProven",
            "pass": dispatch_slice_dependency.get("saveSelectorSliceDirectRuntimeDispatchProofFound")
            is True,
            "status": "slice-runtime-proof-found"
            if dispatch_slice_dependency.get("saveSelectorSliceDirectRuntimeDispatchProofFound")
            is True
            else "slice-runtime-proof-missing",
            "detail": (
                "dependsOnSlice="
                f"{dispatch_slice_dependency.get('descriptorBoundaryDependsOnSaveSelectorSliceModel')} "
                "requiresTableBase="
                f"{dispatch_slice_dependency.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')} "
                "tableBaseCandidates="
                f"{dispatch_slice_dependency.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')}"
            ),
        },
        {
            "id": "rawGenericRouteProofFound",
            "pass": raw_generic_contrast.get("routeProofFound") is True,
            "status": raw_generic_contrast.get("classification") or "not-available",
            "detail": (
                f"routeImm={raw_generic_contrast.get('routeImmediateHitCount')} "
                f"fillImm={raw_generic_contrast.get('fillImmediateHitCount')} "
                f"currentImm={raw_generic_contrast.get('currentImmediateHitCount')} "
                f"callGraphProof={raw_generic_contrast.get('callGraphProofFound')}"
            ),
        },
        {
            "id": "runtimeObservedPredecessorFill",
            "pass": runtime_observed_fill,
            "status": "runtime-fill-observed"
            if runtime_observed_fill
            else "runtime-fill-not-observed",
            "detail": (
                f"publicPredecessorReached={public_predecessor_reached} "
                f"branchStateAllZero={branch_state_all_zero}"
            ),
        },
        {
            "id": "predecessorToCurrentForwardBridgeFound",
            "pass": predecessor_to_current_forward_bridge_found,
            "status": "forward-bridge-found"
            if predecessor_to_current_forward_bridge_found
            else "no-forward-bridge",
            "detail": (
                f"predecessorToCurrent={merge_execution_gap.get('predecessorToCurrentHitCount')} "
                f"forwardMerge={merge_execution_gap.get('forwardMergeBridgeHitCount')}"
            ),
        },
        {
            "id": "routeOrderAndSelectorMergeClosed",
            "pass": route_order_and_selector_merge_closed,
            "status": "route-order-proven"
            if route_order_and_selector_merge_closed
            else "route-order-unproven-or-merge-gap-open",
            "detail": (
                f"routeOrderProven={route_order_proven} "
                f"selectorMergeGapOpen={selector_merge_gap_open}"
            ),
        },
    ]
    proof_gate_count = len(proof_gate_rows)
    proof_gate_pass_count = sum(1 for row in proof_gate_rows if row.get("pass") is True)
    proof_gate_blocked_count = proof_gate_count - proof_gate_pass_count
    proof_gate_blocked_ids = [
        str(row.get("id")) for row in proof_gate_rows if row.get("pass") is not True
    ]
    missing_evidence = [
        PREDECESSOR_FILL_ORDER_MISSING_EVIDENCE_BY_GATE.get(gate_id, gate_id)
        for gate_id in proof_gate_blocked_ids
    ]
    remaining_proofs = [
        "prove the 1:0 fill fragment is entered on the normal public route before the 0x00542b0c reader",
        "connect the predecessor root entry to the 0x004844d0 fill fragment through a decoded non-linear path",
        "bridge the descriptor boundary at 0x004844dc without guessing through data rows",
        "prove the predecessor descriptor stops are reached through the 0x00440720 save-selector slice at runtime",
        "replace the bounded raw generic handler/call-graph non-route contrast with a real save-selector table-base runtime dispatch proof",
        "find a field-entry input path that reaches selector 2:0 or a route-relevant runtime object tile",
        "observe the predecessor fill values at runtime on a route-relevant path",
        "prove selector route order and close the selector merge gap",
    ]
    evidence_refs = [
        {
            "path": "out/save_selector_predecessor_branch_state_execution_gap.json",
            "fields": [
                "publicPredecessorReached",
                "runtimeObservedFill",
                "runtimeBranchStateAllZero",
                "predecessorFillExecutionOrderGap",
                "branchStateExecutionProofFound",
            ],
        },
        {
            "path": "out/save_selector_predecessor_tail_reset.json",
            "fields": [
                "localTailResetFound",
                "tailValidSecondaryFillCount",
                "tailDirectCurrentRouteBridgeFound",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_predecessor_persistence_gap.json",
            "fields": [
                "predecessorFillWouldPassCurrentReader",
                "currentRootHasNoKnownBeforeFrontierOverwrite",
                "persistenceProven",
                "selectorMergeGapOpen",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_predecessor_route_order.json",
            "fields": [
                "routeOrderProven",
                "selectorMergeGapOpen",
                "selectorIndexOrderSupportsPredecessor",
                "selectorProgressSupportsPredecessor",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_data_descriptor_opcode_map.json",
            "fields": [
                "proofFound",
                "failedDataDescriptorGateIds",
                "missingEvidence",
                "evidenceRefCount",
                "predecessorRootStopIsDataDescriptor",
                "predecessorFillStopIsDataDescriptor",
                "d0DescriptorSharedHandlerOpcodes",
                "c0DescriptorSharedHandlerOpcodes",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_dispatch_table_context.json",
            "fields": [
                "proofFound",
                "failedDispatchTableGateIds",
                "missingEvidence",
                "evidenceRefCount",
                "saveSelectorSliceDirectRuntimeDispatchProofFound",
                "descriptorBoundaryDependsOnSaveSelectorSliceModel",
                "routeRelevantSliceDataDescriptorRequiresTableBaseSwitchCount",
                "dynamicSaveSelectorTableBaseCandidateCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/runtime_predecessor_field_entry_sequence_scan.json",
            "fields": [
                "sequenceCount",
                "fieldEntryCandidateCount",
                "snapshotCount",
                "snapshotRouteCandidateCount",
                "finalSelectorCounts",
                "proofFound",
                "predecessorFieldEntryProofFound",
                "failedPredecessorFieldEntryGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/runtime_predecessor_coordinate_source_scan.json",
            "fields": [
                "classification",
                "coordinateSourceRejectionClassification",
                "publicSaveStartPointerTableTileHitCount",
                "observedTrailTrailRingHitCount",
                "reciprocalImageHitCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_merge_execution_gap.json",
            "fields": [
                "predecessorToCurrentHitCount",
                "forwardMergeBridgeHitCount",
                "currentToPredecessorBeforeFillHitCount",
                "selectorMergeExecutionProofFound",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_merge_runtime_context.json",
            "fields": [
                "mergeShapeOnly",
                "forwardBridgeAbsent",
                "reverseReuseBeforeFillOnly",
                "selectorMergeRuntimeProofFound",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_merge_closure_context.json",
            "fields": [
                "selectorMergeClosureProofFound",
                "predecessorPersistenceUsableForCurrent",
                "routeOrderProven",
                "selectedRootExecutionRefFound",
                "promotionStatus",
            ],
        },
    ]
    closure_outside_class_counts = root_tail_branch_closure.get("outsideSuccessorClassCounts") or {}
    closure_outside_class_text = ", ".join(
        f"{key}={value}" for key, value in closure_outside_class_counts.items()
    ) or "unavailable"
    conclusion = (
        "The 1:0 predecessor fill sites form a real local stream fragment and both modeled fill opcodes are "
        "reachable from 0x004844d0 by linear handler advances, but bounded root-entry traversal through fixed "
        "advances and valid branch targets does not reach those fill sites. The local fill trace stops at "
        "0x004844dc on a no-fixed-advance descriptor boundary and never reaches the current 0x00542b0c reader. Runtime polling "
        "reached the public predecessor selector yet still observed all-zero secondaryBranchState. The root-entry "
        "tail branch-target audit classifies all 591 branch-capable rows as before-tail, inside-tail, mapped data, "
        "or unmapped targets, with 0 branches to the fill fragment or current reader. A multi-hop root-tail "
        "branch closure over 12352 nodes and 7249 graph edges likewise reaches 0 fill/current-reader seeds; its "
        f"512 outside successors classify as {closure_outside_class_text}. The root-entry "
        "stop and fill-fragment stop both resolve through .data descriptor rows under the save-selector slice, while the same low "
        "bytes resolve to executable handlers under the raw generic table. Because direct runtime dispatch into the slice is still "
        "unproven, those descriptor boundaries are static model evidence rather than predecessor execution proof. Bounded raw "
        "generic handler windows, their mapped one-hop callees, and the bounded raw generic call graph contain no direct "
        "route/fill/current immediates or route/fill direct transfer targets, so the raw generic alternative does not "
        "supply the missing bridge either. The field-entry input sweep also found 0 selector 2:0 route candidates "
        f"across {field_entry_sequence_context.get('sequenceCount')} sequences and "
        f"{field_entry_sequence_context.get('snapshotCount')} snapshots. The coordinate-source scan leaves the "
        "public predecessor start coordinate in save/camera/image memory only and keeps reciprocal target coordinates "
        "out of object/trail sources, so it is diagnostic rather than a route object source. No forward "
        "predecessor-to-current execution bridge or route-order proof is present."
    )
    return {
        "source": predecessor_branch_state_execution_gap.get("source")
        or predecessor_persistence_gap.get("source")
        or "map1_01a",
        "target": predecessor_branch_state_execution_gap.get("target")
        or predecessor_persistence_gap.get("target")
        or "map2_02d",
        "predecessorSelector": predecessor_branch_state_execution_gap.get("predecessorSelector")
        or predecessor_persistence_gap.get("predecessorSelector"),
        "predecessorRootHex": predecessor_branch_state_execution_gap.get("predecessorRootHex")
        or predecessor_persistence_gap.get("predecessorRootHex"),
        "currentSelector": predecessor_branch_state_execution_gap.get("currentSelector")
        or predecessor_persistence_gap.get("currentSelector"),
        "currentRootHex": predecessor_branch_state_execution_gap.get("currentRootHex")
        or predecessor_persistence_gap.get("currentRootHex"),
        "currentReaderHex": reader_hex,
        "fillSites": fill_sites,
        "localFillTraceStartHex": fill_start_hex,
        "localFillTrace": compact_trace,
        "localFillTraceContainsAllFillSites": local_trace_contains_all_fill_sites,
        "localFillTraceStopHex": stop.get("vaHex"),
        "localFillTraceStopValueHex": stop.get("valueHex"),
        "localFillTraceStopOpcodeHex": stop.get("opcodeHex"),
        "localFillTraceStopReason": stop.get("stopReason"),
        "localFillTraceStopHandlerHex": stop.get("handlerVaHex"),
        "localFillTraceReachesCurrentReader": local_trace_reaches_reader,
        "rootEntryFixedTraversal": root_reachability,
        "rootEntryFixedTraversalFillSitesReachable": root_reachability.get("allTargetsReachable"),
        "directFillSiteRefCounts": direct_fill_site_ref_counts,
        "fillEntryCandidateScan": fill_entry_candidates,
        "encodedFillEntryCandidateScan": encoded_fill_entry_candidates,
        "encodedFillEntryRawScalarCandidateCount": encoded_fill_entry_candidates.get(
            "rawScalarCandidateCount"
        ),
        "encodedFillEntryRootTailRawScalarCandidateCount": encoded_fill_entry_candidates.get(
            "rootTailRawScalarCandidateCount"
        ),
        "encodedFillEntryBranchAttachedEncodedFieldCount": encoded_fill_entry_candidates.get(
            "branchAttachedEncodedFieldCount"
        ),
        "encodedFillEntryModeledControlFlowCandidateCount": encoded_fill_entry_candidates.get(
            "modeledControlFlowCandidateCount"
        ),
        "encodedFillEntryPromotingCandidateCount": encoded_fill_entry_candidates.get(
            "promotingCandidateCount"
        ),
        "encodedFillEntryClassification": encoded_fill_entry_candidates.get("classification"),
        "encodedRawScalarRejection": encoded_raw_scalar_rejection,
        "encodedRawScalarRejectionClassification": encoded_raw_scalar_rejection.get("classification"),
        "encodedRawScalarAllScalarOnly": encoded_raw_scalar_rejection.get("rawScalarAllScalarOnly"),
        "encodedRawScalarNoFixedAdvanceCount": encoded_raw_scalar_rejection.get(
            "rawScalarNoFixedAdvanceCount"
        ),
        "encodedRawScalarNoBranchJumpCount": encoded_raw_scalar_rejection.get(
            "rawScalarNoBranchJumpCount"
        ),
        "encodedRawScalarBranchAttachedCount": encoded_raw_scalar_rejection.get(
            "rawScalarBranchAttachedCount"
        ),
        "encodedRawScalarScalarOnlyCount": encoded_raw_scalar_rejection.get(
            "rawScalarScalarOnlyCount"
        ),
        "encodedRawScalarKindCounts": encoded_raw_scalar_rejection.get("rawScalarKindCounts"),
        "encodedRawScalarHandlerSectionCounts": encoded_raw_scalar_rejection.get(
            "rawScalarHandlerSectionCounts"
        ),
        "rootTailIsolationScan": root_tail_isolation,
        "rootTailDescriptorIsolated": root_tail_isolation.get("descriptorIsolatedTail"),
        "rootTailBranchTargetClassCounts": root_tail_isolation.get("branchTargetClassCounts"),
        "rootTailBranchTargetSectionCounts": root_tail_isolation.get("branchTargetSectionCounts"),
        "rootTailBranchToFillFragmentCount": root_tail_isolation.get("branchToFillFragmentCount"),
        "rootTailBranchToCurrentReaderCount": root_tail_isolation.get("branchToCurrentReaderCount"),
        "rootTailFixedFallthroughToFillCount": root_tail_isolation.get("fixedFallthroughToFillCount"),
        "rootTailBranchClosure": root_tail_isolation.get("branchClosure"),
        "rootTailBranchClosureClassification": (
            (root_tail_isolation.get("branchClosure") or {}).get("classification")
        ),
        "rootTailBranchClosureNodeCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("nodeCount")
        ),
        "rootTailBranchClosureBranchSeedCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("branchSeedCount")
        ),
        "rootTailBranchClosureEdgeCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("edgeCount")
        ),
        "rootTailBranchClosureTailNodeReachFillCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("tailNodeReachFillCount")
        ),
        "rootTailBranchClosureTailNodeReachCurrentReaderCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("tailNodeReachCurrentReaderCount")
        ),
        "rootTailBranchClosureBranchSeedReachFillCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("branchSeedReachFillCount")
        ),
        "rootTailBranchClosureBranchSeedReachCurrentReaderCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("branchSeedReachCurrentReaderCount")
        ),
        "rootTailBranchClosureProofFound": (
            (root_tail_isolation.get("branchClosure") or {}).get("proofFound")
        ),
        "rootTailBranchClosureOutsideSuccessorCount": (
            (root_tail_isolation.get("branchClosure") or {}).get("outsideSuccessorCount")
        ),
        "rootTailBranchClosureOutsideSuccessorClassCounts": (
            (root_tail_isolation.get("branchClosure") or {}).get("outsideSuccessorClassCounts")
        ),
        "rootTailBranchClosureOutsideSuccessorSectionCounts": (
            (root_tail_isolation.get("branchClosure") or {}).get("outsideSuccessorSectionCounts")
        ),
        "rootTailBranchClosureOutsideSuccessorSampleRows": (
            (root_tail_isolation.get("branchClosure") or {}).get("outsideSuccessorSampleRows")
        ),
        "publicPredecessorReached": public_predecessor_reached,
        "runtimeObservedFill": runtime_observed_fill,
        "fieldEntrySequenceContext": field_entry_sequence_context,
        "fieldEntrySequenceCount": field_entry_sequence_context.get("sequenceCount"),
        "fieldEntryCandidateCount": field_entry_sequence_context.get("fieldEntryCandidateCount"),
        "fieldEntryCandidateNames": field_entry_sequence_context.get("fieldEntryCandidateNames"),
        "fieldEntrySnapshotCount": field_entry_sequence_context.get("snapshotCount"),
        "fieldEntrySnapshotRouteCandidateCount": field_entry_sequence_context.get(
            "snapshotRouteCandidateCount"
        ),
        "fieldEntrySnapshotRouteCandidateNames": field_entry_sequence_context.get(
            "snapshotRouteCandidateNames"
        ),
        "fieldEntryFinalSelectorCounts": field_entry_sequence_context.get("finalSelectorCounts"),
        "fieldEntryFinalCameraTileCounts": field_entry_sequence_context.get("finalCameraTileCounts"),
        "fieldEntrySnapshotSelectorCounts": field_entry_sequence_context.get("snapshotSelectorCounts"),
        "fieldEntrySnapshotCameraTileCounts": field_entry_sequence_context.get("snapshotCameraTileCounts"),
        "fieldEntryClassificationCounts": field_entry_sequence_context.get("classificationCounts"),
        "fieldEntryRouteCandidateFound": field_entry_route_candidate_found,
        "fieldEntryInputStatus": field_entry_input_status,
        "fieldEntryProofFound": field_entry_sequence_context.get("proofFound"),
        "predecessorFieldEntryProofFound": field_entry_sequence_context.get(
            "predecessorFieldEntryProofFound"
        ),
        "fieldEntryFailedGateIds": field_entry_sequence_context.get(
            "failedPredecessorFieldEntryGateIds"
        ),
        "fieldEntryMissingEvidence": field_entry_sequence_context.get("missingEvidence"),
        "fieldEntryEvidenceRefCount": field_entry_sequence_context.get("evidenceRefCount"),
        "fieldEntryEvidenceRefs": field_entry_sequence_context.get("evidenceRefs"),
        "coordinateSourceContext": coordinate_source_context,
        "coordinateSourceClassification": coordinate_source_context.get("classification"),
        "coordinateSourceRejectionClassification": coordinate_source_context.get(
            "coordinateSourceRejectionClassification"
        ),
        "coordinateSourcePromotionStatus": coordinate_source_context.get("promotionStatus"),
        "coordinateSourceFinalSelector": coordinate_source_context.get("finalSelector"),
        "coordinateSourceFinalCameraTile": coordinate_source_context.get("finalCameraTile"),
        "coordinateSourcePublicStartPointerTableTileHitCount": coordinate_source_context.get(
            "publicSaveStartPointerTableTileHitCount"
        ),
        "coordinateSourcePublicStartStaticBaseHitCount": coordinate_source_context.get(
            "publicSaveStartStaticBaseHitCount"
        ),
        "coordinateSourcePublicStartTrailRingHitCount": coordinate_source_context.get(
            "publicSaveStartTrailRingHitCount"
        ),
        "coordinateSourcePublicStartImageHitCount": coordinate_source_context.get(
            "publicSaveStartImageHitCount"
        ),
        "coordinateSourceObservedTrailPointerTableTileHitCount": coordinate_source_context.get(
            "observedTrailPointerTableTileHitCount"
        ),
        "coordinateSourceObservedTrailStaticBaseHitCount": coordinate_source_context.get(
            "observedTrailStaticBaseHitCount"
        ),
        "coordinateSourceObservedTrailTrailRingHitCount": coordinate_source_context.get(
            "observedTrailTrailRingHitCount"
        ),
        "coordinateSourceObservedTrailImageHitCount": coordinate_source_context.get(
            "observedTrailImageHitCount"
        ),
        "coordinateSourceReciprocalPointerTableTileHitCount": coordinate_source_context.get(
            "reciprocalPointerTableTileHitCount"
        ),
        "coordinateSourceReciprocalStaticBaseHitCount": coordinate_source_context.get(
            "reciprocalStaticBaseHitCount"
        ),
        "coordinateSourceReciprocalTrailRingHitCount": coordinate_source_context.get(
            "reciprocalTrailRingHitCount"
        ),
        "coordinateSourceReciprocalImageHitCount": coordinate_source_context.get(
            "reciprocalImageHitCount"
        ),
        "runtimeBranchStateAllZero": branch_state_all_zero,
        "staticNoLocalTailReset": static_no_local_tail_reset,
        "staticResetScopeClosed": static_reset_scope_closed,
        "selectorOrderResetGapClosed": selector_order_reset_gap_closed,
        "predecessorToCurrentForwardBridgeFound": predecessor_to_current_forward_bridge_found,
        "predecessorToCurrentHitCount": merge_execution_gap.get("predecessorToCurrentHitCount"),
        "currentToPredecessorHitCount": merge_execution_gap.get("currentToPredecessorHitCount"),
        "reverseReuseBeforeFillCount": merge_execution_gap.get("currentToPredecessorBeforeFillHitCount"),
        "reverseReuseFillSiteHitCount": merge_execution_gap.get("currentToPredecessorFillSiteHitCount"),
        "forwardMergeBridgeHitCount": merge_execution_gap.get("forwardMergeBridgeHitCount"),
        "predecessorRootStopIsDataDescriptor": data_descriptor_opcode_map.get(
            "predecessorRootStopIsDataDescriptor"
        ),
        "predecessorFillStopIsDataDescriptor": data_descriptor_opcode_map.get(
            "predecessorFillStopIsDataDescriptor"
        ),
        "predecessorRootStopDescriptorHex": predecessor_root_stop_descriptor.get("handlerValueHex"),
        "predecessorFillStopDescriptorHex": predecessor_fill_stop_descriptor.get("handlerValueHex"),
        "predecessorRootStopDescriptorSharedOpcodes": (
            data_descriptor_opcode_map.get("d0DescriptorSharedHandlerOpcodes") or []
        ),
        "predecessorFillStopDescriptorSharedOpcodes": (
            data_descriptor_opcode_map.get("c0DescriptorSharedHandlerOpcodes") or []
        ),
        "predecessorDataDescriptorBoundariesProven": predecessor_descriptor_boundaries_proven,
        "predecessorDataDescriptorBoundaryPromotes": False,
        "predecessorDispatchSliceDependency": dispatch_slice_dependency,
        "predecessorDispatchTableProofFound": dispatch_slice_dependency.get(
            "dispatchTableProofFound"
        ),
        "predecessorDispatchTableFailedGateIds": dispatch_slice_dependency.get(
            "failedDispatchTableGateIds"
        )
        or [],
        "predecessorDispatchTableMissingEvidence": dispatch_slice_dependency.get(
            "missingEvidence"
        )
        or [],
        "predecessorDispatchTableEvidenceRefs": dispatch_slice_dependency.get("evidenceRefs")
        or [],
        "predecessorDispatchTableEvidenceRefCount": dispatch_slice_dependency.get(
            "evidenceRefCount"
        ),
        "predecessorDispatchSliceRuntimeProofFound": dispatch_slice_dependency.get(
            "saveSelectorSliceDirectRuntimeDispatchProofFound"
        ),
        "predecessorDescriptorDependsOnSaveSelectorSliceModel": dispatch_slice_dependency.get(
            "descriptorBoundaryDependsOnSaveSelectorSliceModel"
        ),
        "predecessorDispatchSliceRowCount": dispatch_slice_dependency.get(
            "predecessorDispatchSliceRowCount"
        ),
        "predecessorDispatchSliceDataDescriptorCount": dispatch_slice_dependency.get(
            "predecessorDispatchSliceDataDescriptorCount"
        ),
        "predecessorDispatchRawGeneralCodeCount": dispatch_slice_dependency.get(
            "predecessorDispatchRawGeneralCodeCount"
        ),
        "predecessorDispatchRawGeneralDiffersFromSliceCount": dispatch_slice_dependency.get(
            "predecessorDispatchRawGeneralDiffersFromSliceCount"
        ),
        "predecessorDispatchSliceGenericByteReachableCount": dispatch_slice_dependency.get(
            "predecessorDispatchSliceGenericByteReachableCount"
        ),
        "predecessorDispatchSliceRequiresTableBaseSwitchCount": dispatch_slice_dependency.get(
            "predecessorDispatchSliceRequiresTableBaseSwitchCount"
        ),
        "predecessorDispatchDynamicIndexedDispatchRowCount": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicIndexedDispatchRowCount"
        ),
        "predecessorDispatchDynamicDwordScaledDispatchRowCount": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicDwordScaledDispatchRowCount"
        ),
        "predecessorDispatchDynamicIndexedDispatchRows": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicIndexedDispatchRows"
        )
        or [],
        "predecessorDispatchDynamicDwordScaledDispatchRows": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicDwordScaledDispatchRows"
        )
        or [],
        "predecessorDispatchDynamicScopeTableCallbackCount": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicScopeTableCallbackCount"
        ),
        "predecessorDispatchDynamicScopeTableCallbackSites": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicScopeTableCallbackSites"
        ) or [],
        "predecessorDispatchDynamicScopeTableCallbackRows": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicScopeTableCallbackRows"
        ) or [],
        "predecessorDispatchDynamicSaveSelectorTableImmediateNearCount": dispatch_slice_dependency.get(
            "predecessorDispatchDynamicSaveSelectorTableImmediateNearCount"
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount": (
            dispatch_slice_dependency.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount"
            )
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites": (
            dispatch_slice_dependency.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites"
            )
            or []
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateRows": (
            dispatch_slice_dependency.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseCandidateRows"
            )
            or []
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticRowCount": (
            dispatch_slice_dependency.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticRowCount"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount": (
            dispatch_slice_dependency.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateFound": (
            dispatch_slice_dependency.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateFound"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateRows": (
            dispatch_slice_dependency.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateRows"
            )
            or []
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound": (
            dispatch_slice_dependency.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound"
            )
        ),
        "predecessorDispatchTableBaseRejection": dispatch_slice_dependency.get(
            "predecessorDispatchTableBaseRejection"
        ),
        "predecessorDispatchTableBaseRejectionClassification": dispatch_slice_dependency.get(
            "predecessorDispatchTableBaseRejectionClassification"
        ),
        "predecessorDispatchTableBaseAuditRows": dispatch_slice_dependency.get(
            "predecessorDispatchTableBaseAuditRows"
        )
        or [],
        "rawGenericDispatchContrast": raw_generic_contrast,
        "rawGenericHandlerCount": raw_generic_contrast.get("handlerCount"),
        "rawGenericClassification": raw_generic_contrast.get("classification"),
        "rawGenericRouteImmediateHitCount": raw_generic_contrast.get("routeImmediateHitCount"),
        "rawGenericFillImmediateHitCount": raw_generic_contrast.get("fillImmediateHitCount"),
        "rawGenericCurrentImmediateHitCount": raw_generic_contrast.get("currentImmediateHitCount"),
        "rawGenericSelectedPointerImmediateHitCount": raw_generic_contrast.get(
            "selectedPointerImmediateHitCount"
        ),
        "rawGenericBranchStateImmediateHitCount": raw_generic_contrast.get(
            "branchStateImmediateHitCount"
        ),
        "rawGenericDirectTransferCount": raw_generic_contrast.get("directTransferCount"),
        "rawGenericDirectCallCount": raw_generic_contrast.get("directCallCount"),
        "rawGenericMappedDirectCallCount": raw_generic_contrast.get("mappedDirectCallCount"),
        "rawGenericUnmappedDirectCallCount": raw_generic_contrast.get("unmappedDirectCallCount"),
        "rawGenericMappedDirectCallTargets": raw_generic_contrast.get("mappedDirectCallTargets"),
        "rawGenericRouteDirectTransferHitCount": raw_generic_contrast.get(
            "routeDirectTransferHitCount"
        ),
        "rawGenericFillDirectTransferHitCount": raw_generic_contrast.get(
            "fillDirectTransferHitCount"
        ),
        "rawGenericOneHopMappedCalleeCount": raw_generic_contrast.get("oneHopMappedCalleeCount"),
        "rawGenericOneHopRouteImmediateHitCount": raw_generic_contrast.get(
            "oneHopRouteImmediateHitCount"
        ),
        "rawGenericOneHopFillImmediateHitCount": raw_generic_contrast.get(
            "oneHopFillImmediateHitCount"
        ),
        "rawGenericOneHopCurrentImmediateHitCount": raw_generic_contrast.get(
            "oneHopCurrentImmediateHitCount"
        ),
        "rawGenericOneHopSelectedPointerImmediateHitCount": raw_generic_contrast.get(
            "oneHopSelectedPointerImmediateHitCount"
        ),
        "rawGenericOneHopBranchStateImmediateHitCount": raw_generic_contrast.get(
            "oneHopBranchStateImmediateHitCount"
        ),
        "rawGenericOneHopRouteDirectTransferHitCount": raw_generic_contrast.get(
            "oneHopRouteDirectTransferHitCount"
        ),
        "rawGenericOneHopFillDirectTransferHitCount": raw_generic_contrast.get(
            "oneHopFillDirectTransferHitCount"
        ),
        "rawGenericOneHopRouteProofFound": raw_generic_contrast.get("oneHopRouteProofFound"),
        "rawGenericCallGraphContrast": raw_generic_contrast.get("callGraphContrast"),
        "rawGenericCallGraphDepthSensitivity": raw_generic_contrast.get(
            "callGraphDepthSensitivity"
        ),
        "rawGenericCallGraphClassification": raw_generic_contrast.get(
            "callGraphClassification"
        ),
        "rawGenericCallGraphProofFound": raw_generic_contrast.get("callGraphProofFound"),
        "rawGenericCallGraphRouteContextFound": raw_generic_contrast.get(
            "callGraphRouteContextFound"
        ),
        "rawGenericCallGraphRouteContextHitCount": raw_generic_contrast.get(
            "callGraphRouteContextHitCount"
        ),
        "rawGenericCallGraphMaxDepth": raw_generic_contrast.get("callGraphMaxDepth"),
        "rawGenericCallGraphReachableFunctionCount": raw_generic_contrast.get(
            "callGraphReachableFunctionCount"
        ),
        "rawGenericCallGraphDirectCallEdgeCount": raw_generic_contrast.get(
            "callGraphDirectCallEdgeCount"
        ),
        "rawGenericCallGraphMappedDirectCallEdgeCount": raw_generic_contrast.get(
            "callGraphMappedDirectCallEdgeCount"
        ),
        "rawGenericCallGraphTextDirectCallEdgeCount": raw_generic_contrast.get(
            "callGraphTextDirectCallEdgeCount"
        ),
        "rawGenericCallGraphRouteImmediateHitCount": raw_generic_contrast.get(
            "callGraphRouteImmediateHitCount"
        ),
        "rawGenericCallGraphFillImmediateHitCount": raw_generic_contrast.get(
            "callGraphFillImmediateHitCount"
        ),
        "rawGenericCallGraphCurrentImmediateHitCount": raw_generic_contrast.get(
            "callGraphCurrentImmediateHitCount"
        ),
        "rawGenericCallGraphSelectedPointerImmediateHitCount": raw_generic_contrast.get(
            "callGraphSelectedPointerImmediateHitCount"
        ),
        "rawGenericCallGraphBranchStateImmediateHitCount": raw_generic_contrast.get(
            "callGraphBranchStateImmediateHitCount"
        ),
        "rawGenericCallGraphRouteDirectTransferHitCount": raw_generic_contrast.get(
            "callGraphRouteDirectTransferHitCount"
        ),
        "rawGenericCallGraphFillDirectTransferHitCount": raw_generic_contrast.get(
            "callGraphFillDirectTransferHitCount"
        ),
        "rawGenericCallGraphDepthSensitivityMaxDepthChecked": raw_generic_contrast.get(
            "callGraphDepthSensitivityMaxDepthChecked"
        ),
        "rawGenericCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
            raw_generic_contrast.get("callGraphDepthSensitivityProofAbsentAcrossCheckedDepths")
        ),
        "rawGenericCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth": (
            raw_generic_contrast.get("callGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth")
        ),
        "rawGenericRouteProofFound": raw_generic_contrast.get("routeProofFound"),
        "predecessorRootStopRawGeneralHandlerHex": dispatch_slice_dependency.get(
            "predecessorRootStopRawGeneralHandlerHex"
        ),
        "predecessorFillStopRawGeneralHandlerHex": dispatch_slice_dependency.get(
            "predecessorFillStopRawGeneralHandlerHex"
        ),
        "predecessorRootStopSliceGenericByteReachable": dispatch_slice_dependency.get(
            "predecessorRootStopSliceGenericByteReachable"
        ),
        "predecessorFillStopSliceGenericByteReachable": dispatch_slice_dependency.get(
            "predecessorFillStopSliceGenericByteReachable"
        ),
        "predecessorRootStopSliceRequiresTableBaseSwitch": dispatch_slice_dependency.get(
            "predecessorRootStopSliceRequiresTableBaseSwitch"
        ),
        "predecessorFillStopSliceRequiresTableBaseSwitch": dispatch_slice_dependency.get(
            "predecessorFillStopSliceRequiresTableBaseSwitch"
        ),
        "routeOrderProven": route_order_proven,
        "selectorMergeGapOpen": selector_merge_gap_open,
        "routeOrderAndSelectorMergeClosed": route_order_and_selector_merge_closed,
        "selectorMergeShapeOnly": selector_merge_shape_only,
        "selectorMergeForwardBridgeAbsent": selector_merge_forward_bridge_absent,
        "selectorMergeReverseReuseBeforeFillOnly": selector_merge_reverse_reuse_before_fill_only,
        "selectorMergeRuntimeProofFound": selector_merge_runtime_proof_found,
        "selectorMergeClosureProofFound": selector_merge_closure_proof_found,
        "predecessorPersistenceUsableForCurrent": predecessor_persistence_usable_for_current,
        "selectorMergeEncodedExecutionBridgeFound": merge_runtime_context.get(
            "encodedMergeExecutionBridgeFound"
        ),
        "selectorMergeConstructedDiagnosticExcludedFromProof": merge_runtime_context.get(
            "constructedDiagnosticExcludedFromProof"
        ),
        "selectorMergeRemainingProofs": sorted(
            set(
                (merge_runtime_context.get("remainingProofs") or [])
                + (merge_closure_context.get("remainingProofs") or [])
            )
        ),
        "predecessorFillProofGateRows": proof_gate_rows,
        "predecessorFillProofGateCount": proof_gate_count,
        "predecessorFillProofGatePassCount": proof_gate_pass_count,
        "predecessorFillProofGateBlockedCount": proof_gate_blocked_count,
        "predecessorFillProofGateBlockedIds": proof_gate_blocked_ids,
        "predecessorFillAllProofGatesBlocked": (
            proof_gate_count > 0 and proof_gate_pass_count == 0
        ),
        "evidenceRefs": evidence_refs,
        "evidenceRefCount": len(evidence_refs),
        "proofFound": proof_found,
        "failedPredecessorFillOrderGateIds": proof_gate_blocked_ids,
        "missingEvidence": missing_evidence,
        "promotionStatus": "ready-for-review" if proof_found else "blocked",
        "evidence": evidence,
        "remainingProofs": remaining_proofs,
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Save Selector Predecessor Fill Execution Order Gap",
        "",
        summary["conclusion"],
        "",
        f"- route: `{summary['source']} -> {summary['target']}`",
        f"- predecessor: `{summary['predecessorSelector']}` root `{summary['predecessorRootHex']}`",
        f"- current: `{summary['currentSelector']}` root `{summary['currentRootHex']}` reader `{summary['currentReaderHex']}`",
        f"- fill sites: `{list_text(summary.get('fillSites'))}`",
        f"- local fill trace start: `{summary['localFillTraceStartHex']}`",
        f"- local fill trace stop: `{summary['localFillTraceStopHex']}` reason `{summary['localFillTraceStopReason']}` handler `{summary['localFillTraceStopHandlerHex']}`",
        f"- local fill trace reaches current reader: {summary['localFillTraceReachesCurrentReader']}",
        f"- root-entry fixed traversal reaches fill sites: {summary['rootEntryFixedTraversalFillSitesReachable']}",
        f"- direct fill-site dword refs: {summary['directFillSiteRefCounts']}",
        f"- fill fragment entry candidate scan: {summary.get('fillEntryCandidateScan')}",
        f"- encoded fill-entry candidate scan: {summary.get('encodedFillEntryCandidateScan')}",
        f"- encoded raw scalar rejection: `{summary.get('encodedRawScalarRejectionClassification')}`",
        (
            "- encoded raw scalar no-fixed/no-branch/branch-attached/scalar-only: "
            f"{summary.get('encodedRawScalarNoFixedAdvanceCount')} / "
            f"{summary.get('encodedRawScalarNoBranchJumpCount')} / "
            f"{summary.get('encodedRawScalarBranchAttachedCount')} / "
            f"{summary.get('encodedRawScalarScalarOnlyCount')}"
        ),
        f"- encoded raw scalar kinds: `{summary.get('encodedRawScalarKindCounts')}`",
        f"- encoded raw scalar handler sections: `{summary.get('encodedRawScalarHandlerSectionCounts')}`",
        f"- root-tail isolation scan: {summary.get('rootTailIsolationScan')}",
        (
            "- root-tail branch closure outside successors: "
            f"{summary.get('rootTailBranchClosureOutsideSuccessorCount')} "
            f"classes `{summary.get('rootTailBranchClosureOutsideSuccessorClassCounts')}` "
            f"sections `{summary.get('rootTailBranchClosureOutsideSuccessorSectionCounts')}`"
        ),
        f"- predecessor root stop descriptor: `{summary.get('predecessorRootStopDescriptorHex')}` opcodes `{list_text(summary.get('predecessorRootStopDescriptorSharedOpcodes'))}`",
        f"- predecessor fill stop descriptor: `{summary.get('predecessorFillStopDescriptorHex')}` opcodes `{list_text(summary.get('predecessorFillStopDescriptorSharedOpcodes'))}`",
        f"- predecessor data descriptor boundaries proven: {summary.get('predecessorDataDescriptorBoundariesProven')}",
        f"- predecessor data descriptor boundary promotes: {summary.get('predecessorDataDescriptorBoundaryPromotes')}",
        f"- predecessor dispatch slice runtime proof found: {summary.get('predecessorDispatchSliceRuntimeProofFound')}",
        f"- predecessor dispatch table proof found: {summary.get('predecessorDispatchTableProofFound')}",
        (
            "- predecessor dispatch table failed gates: "
            f"`{list_text(summary.get('predecessorDispatchTableFailedGateIds'))}`"
        ),
        (
            "- predecessor dispatch table missing evidence count / refs: "
            f"{len(summary.get('predecessorDispatchTableMissingEvidence') or [])} / "
            f"{summary.get('predecessorDispatchTableEvidenceRefCount')}"
        ),
        f"- predecessor descriptor depends on save-selector slice model: {summary.get('predecessorDescriptorDependsOnSaveSelectorSliceModel')}",
        f"- predecessor raw generic handlers differ from slice: {summary.get('predecessorDispatchRawGeneralDiffersFromSliceCount')}",
        (
            "- predecessor slice generic-byte reachable / requires table-base switch: "
            f"{summary.get('predecessorDispatchSliceGenericByteReachableCount')} / "
            f"{summary.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')}"
        ),
        (
            "- predecessor dynamic dispatch rows / SEH scope callbacks / save-selector table-base immediate candidates: "
            f"{summary.get('predecessorDispatchDynamicIndexedDispatchRowCount')} / "
            f"{summary.get('predecessorDispatchDynamicScopeTableCallbackCount')} / "
            f"{summary.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')}"
        ),
        (
            "- predecessor dynamic SEH scope-table callback sites: "
            f"`{list_text(summary.get('predecessorDispatchDynamicScopeTableCallbackSites'))}`"
        ),
        (
            "- predecessor dispatch table-base rejection: "
            f"`{summary.get('predecessorDispatchTableBaseRejectionClassification')}`"
        ),
        (
            "- predecessor dispatch table-base dynamic candidates: "
            f"{summary.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')} "
            "static "
            f"{summary.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}"
        ),
        (
            "- predecessor dispatch table-base arithmetic rows/candidates: "
            f"{summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')} / "
            f"{summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')}"
        ),
        (
            "- predecessor dynamic save-selector table-base candidate sites: "
            f"`{list_text(summary.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites'))}`"
        ),
        (
            "- predecessor dynamic save-selector table-base static candidate found: "
            f"{summary.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}"
        ),
        (
            "- raw generic handler contrast: "
            f"`{summary.get('rawGenericClassification')}` "
            f"handlers `{summary.get('rawGenericHandlerCount')}`, "
            f"route/fill/current immediates "
            f"`{summary.get('rawGenericRouteImmediateHitCount')}/"
            f"{summary.get('rawGenericFillImmediateHitCount')}/"
            f"{summary.get('rawGenericCurrentImmediateHitCount')}`, "
            f"selected/branch-state immediates "
            f"`{summary.get('rawGenericSelectedPointerImmediateHitCount')}/"
            f"{summary.get('rawGenericBranchStateImmediateHitCount')}`, "
            f"mapped calls `{summary.get('rawGenericMappedDirectCallCount')}` "
            f"targets `{list_text(summary.get('rawGenericMappedDirectCallTargets'))}`, "
            f"one-hop route/fill/current immediates "
            f"`{summary.get('rawGenericOneHopRouteImmediateHitCount')}/"
            f"{summary.get('rawGenericOneHopFillImmediateHitCount')}/"
            f"{summary.get('rawGenericOneHopCurrentImmediateHitCount')}`, "
            f"route/fill direct transfers "
            f"`{summary.get('rawGenericRouteDirectTransferHitCount')}/"
            f"{summary.get('rawGenericFillDirectTransferHitCount')}`, "
            f"one-hop route/fill transfers "
            f"`{summary.get('rawGenericOneHopRouteDirectTransferHitCount')}/"
            f"{summary.get('rawGenericOneHopFillDirectTransferHitCount')}`, "
            "call graph "
            f"`{summary.get('rawGenericCallGraphClassification')}` depth "
            f"`{summary.get('rawGenericCallGraphMaxDepth')}` functions/edges "
            f"`{summary.get('rawGenericCallGraphReachableFunctionCount')}/"
            f"{summary.get('rawGenericCallGraphDirectCallEdgeCount')}`, "
            "call graph route/fill/current immediates "
            f"`{summary.get('rawGenericCallGraphRouteImmediateHitCount')}/"
            f"{summary.get('rawGenericCallGraphFillImmediateHitCount')}/"
            f"{summary.get('rawGenericCallGraphCurrentImmediateHitCount')}`, "
            "call graph selected/branch-state immediates "
            f"`{summary.get('rawGenericCallGraphSelectedPointerImmediateHitCount')}/"
            f"{summary.get('rawGenericCallGraphBranchStateImmediateHitCount')}`, "
            "call graph route/fill transfers "
            f"`{summary.get('rawGenericCallGraphRouteDirectTransferHitCount')}/"
            f"{summary.get('rawGenericCallGraphFillDirectTransferHitCount')}`, "
            "depth sensitivity max/no-proof/stable "
            f"`{summary.get('rawGenericCallGraphDepthSensitivityMaxDepthChecked')}/"
            f"{summary.get('rawGenericCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths')}/"
            f"{summary.get('rawGenericCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth')}`, "
            f"route proof `{summary.get('rawGenericRouteProofFound')}`"
        ),
        f"- runtime observed fill: {summary['runtimeObservedFill']}",
        (
            "- runtime field-entry input: "
            f"`{summary['fieldEntryInputStatus']}` seq `{summary['fieldEntrySequenceCount']}` "
            f"candidates `{summary['fieldEntryCandidateCount']}` snapshots "
            f"`{summary['fieldEntrySnapshotCount']}` route snapshots "
            f"`{summary['fieldEntrySnapshotRouteCandidateCount']}`"
        ),
        (
            "- runtime field-entry proof: "
            f"proof `{summary.get('fieldEntryProofFound')}` "
            f"candidateProof `{summary.get('predecessorFieldEntryProofFound')}` "
            f"failed `{list_text(summary.get('fieldEntryFailedGateIds'))}` "
            f"evidenceRefs `{summary.get('fieldEntryEvidenceRefCount')}`"
        ),
        (
            "- runtime field-entry selectors/cameras: "
            f"`{summary['fieldEntryFinalSelectorCounts']}` / "
            f"`{summary['fieldEntryFinalCameraTileCounts']}`"
        ),
        (
            "- runtime coordinate source: "
            f"`{summary.get('coordinateSourceClassification')}` / "
            f"`{summary.get('coordinateSourceRejectionClassification')}` "
            "public-start ptr/static/trail/image "
            f"`{summary.get('coordinateSourcePublicStartPointerTableTileHitCount')}/"
            f"{summary.get('coordinateSourcePublicStartStaticBaseHitCount')}/"
            f"{summary.get('coordinateSourcePublicStartTrailRingHitCount')}/"
            f"{summary.get('coordinateSourcePublicStartImageHitCount')}` "
            "observed-trail ptr/static/trail/image "
            f"`{summary.get('coordinateSourceObservedTrailPointerTableTileHitCount')}/"
            f"{summary.get('coordinateSourceObservedTrailStaticBaseHitCount')}/"
            f"{summary.get('coordinateSourceObservedTrailTrailRingHitCount')}/"
            f"{summary.get('coordinateSourceObservedTrailImageHitCount')}` "
            "reciprocal ptr/static/trail/image "
            f"`{summary.get('coordinateSourceReciprocalPointerTableTileHitCount')}/"
            f"{summary.get('coordinateSourceReciprocalStaticBaseHitCount')}/"
            f"{summary.get('coordinateSourceReciprocalTrailRingHitCount')}/"
            f"{summary.get('coordinateSourceReciprocalImageHitCount')}` "
            f"promotion `{summary.get('coordinateSourcePromotionStatus')}`"
        ),
        f"- predecessor to current forward bridge found: {summary['predecessorToCurrentForwardBridgeFound']}",
        f"- route order proven: {summary['routeOrderProven']}",
        f"- selector merge gap open: {summary['selectorMergeGapOpen']}",
        (
            "- selector merge runtime/closure: "
            f"shapeOnly `{summary.get('selectorMergeShapeOnly')}`, "
            f"forwardAbsent `{summary.get('selectorMergeForwardBridgeAbsent')}`, "
            f"reverseBeforeFillOnly `{summary.get('selectorMergeReverseReuseBeforeFillOnly')}`, "
            f"runtimeProof `{summary.get('selectorMergeRuntimeProofFound')}`, "
            f"closureProof `{summary.get('selectorMergeClosureProofFound')}`, "
            f"persistenceUsable `{summary.get('predecessorPersistenceUsableForCurrent')}`"
        ),
        (
            "- predecessor fill proof gates blocked/pass/all-blocked: "
            f"{summary.get('predecessorFillProofGateBlockedCount')}/"
            f"{summary.get('predecessorFillProofGatePassCount')}/"
            f"{summary.get('predecessorFillAllProofGatesBlocked')}"
        ),
        (
            "- predecessor fill proof gate blocked ids: "
            f"`{list_text(summary.get('predecessorFillProofGateBlockedIds'))}`"
        ),
        f"- proof found: {summary['proofFound']}",
        f"- failed predecessor fill-order gates: `{list_text(summary.get('failedPredecessorFillOrderGateIds'))}`",
        f"- missing evidence count: {len(summary.get('missingEvidence') or [])}",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        "## Proof Gates",
        "",
        "| id | pass | status | detail |",
        "| --- | --- | --- | --- |",
    ]
    for row in summary.get("predecessorFillProofGateRows") or []:
        lines.append(
            f"| {row.get('id')} | {row.get('pass')} | {row.get('status')} | {row.get('detail')} |"
        )
    lines.extend([
        "",
        "## Dispatch Table-Base Audit",
        "",
        "| kind | site/instruction | status | detail |",
        "| --- | --- | --- | --- |",
    ])
    for row in summary.get("predecessorDispatchTableBaseAuditRows") or []:
        lines.append(
            f"| {row.get('kind')} | `{row.get('siteVaHex')}` | {row.get('status')} | {row.get('detail')} |"
        )
    lines.extend([
        "",
        "## Evidence Refs",
        "",
        "| path | fields |",
        "| --- | --- |",
    ])
    for ref in summary.get("evidenceRefs") or []:
        lines.append(
            f"| `{ref.get('path')}` | `{list_text(ref.get('fields'))}` |"
        )
    lines.extend(["", "## Missing Evidence", ""])
    lines.extend(f"- {item}" for item in summary.get("missingEvidence") or [])
    lines.extend([
        "",
        "## Evidence",
        "",
        "| kind | status | detail |",
        "| --- | --- | --- |",
    ])
    for row in summary["evidence"]:
        lines.append(f"| {row['kind']} | {row['status']} | {row['detail']} |")
    lines.extend([
        "",
        "## Local Fill Trace",
        "",
        "| step | va | value | opcode | handler | advance | stop |",
        "| ---: | --- | --- | --- | --- | --- | --- |",
    ])
    for row in summary.get("localFillTrace") or []:
        advances = "/".join(f"+{value}" for value in row.get("fixedAdvances") or []) or "-"
        lines.append(
            f"| {row.get('step')} | `{row.get('vaHex')}` | `{row.get('valueHex')}` | "
            f"`{row.get('opcodeHex')}` | `{row.get('handlerVaHex')}` | {advances} | "
            f"{row.get('stopReason') or '-'} |"
        )
    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:
    proof_gate_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(str(row.get('id')))}</td>"
        f"<td>{html.escape(str(row.get('pass')))}</td>"
        f"<td>{html.escape(str(row.get('status')))}</td>"
        f"<td>{html.escape(str(row.get('detail')))}</td>"
        "</tr>"
        for row in summary.get("predecessorFillProofGateRows") or []
    )
    table_base_audit_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(str(row.get('kind')))}</td>"
        f"<td><code>{html.escape(str(row.get('siteVaHex')))}</code></td>"
        f"<td>{html.escape(str(row.get('status')))}</td>"
        f"<td>{html.escape(str(row.get('detail')))}</td>"
        "</tr>"
        for row in summary.get("predecessorDispatchTableBaseAuditRows") or []
    )
    evidence_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['kind'])}</td>"
        f"<td>{html.escape(row['status'])}</td>"
        f"<td>{html.escape(row['detail'])}</td>"
        "</tr>"
        for row in summary["evidence"]
    )
    evidence_ref_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(ref.get('path')))}</code></td>"
        f"<td>{html.escape(list_text(ref.get('fields')))}</td>"
        "</tr>"
        for ref in summary.get("evidenceRefs") or []
    )
    missing_items = "\n".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or []
    )
    trace_rows = "\n".join(
        "<tr>"
        f"<td>{row.get('step')}</td>"
        f"<td><code>{html.escape(str(row.get('vaHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('valueHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('opcodeHex')))}</code></td>"
        f"<td><code>{html.escape(str(row.get('handlerVaHex')))}</code></td>"
        f"<td>{html.escape('/'.join(f'+{value}' for value in row.get('fixedAdvances') or []) or '-')}</td>"
        f"<td>{html.escape(str(row.get('stopReason') or '-'))}</td>"
        "</tr>"
        for row in summary.get("localFillTrace") or []
    )
    proof_items = "\n".join(f"<li>{html.escape(item)}</li>" for item in summary["remainingProofs"])
    return "\n".join([
        "<!doctype html>",
        '<html lang="en">',
        "<head>",
        '  <meta charset="utf-8">',
        "  <title>Save Selector Predecessor Fill Execution Order Gap</title>",
        "  <style>body{font-family:system-ui,sans-serif;margin:24px;line-height:1.45;max-width:1200px}table{border-collapse:collapse;width:100%;margin:16px 0}td,th{border:1px solid #ddd;padding:6px 8px;text-align:left;vertical-align:top}th{background:#f5f5f5}code{white-space:nowrap}</style>",
        "</head>",
        "<body>",
        "  <h1>Save Selector Predecessor Fill Execution Order Gap</h1>",
        f"  <p>{html.escape(summary['conclusion'])}</p>",
        (
            "  <p><b>Route:</b> "
            f"<code>{html.escape(summary['source'])} -> {html.escape(summary['target'])}</code>; "
            f"predecessor <code>{html.escape(str(summary['predecessorSelector']))}</code> "
            f"root <code>{html.escape(str(summary['predecessorRootHex']))}</code>; "
            f"current <code>{html.escape(str(summary['currentSelector']))}</code> "
            f"reader <code>{html.escape(str(summary['currentReaderHex']))}</code>.</p>"
        ),
        (
            "  <p><b>Fill trace:</b> "
            f"start <code>{html.escape(str(summary['localFillTraceStartHex']))}</code>; "
            f"stop <code>{html.escape(str(summary['localFillTraceStopHex']))}</code> "
            f"reason <code>{html.escape(str(summary['localFillTraceStopReason']))}</code>; "
            f"reaches reader {bool_text(summary['localFillTraceReachesCurrentReader'])}; "
            f"root-entry reaches fills {bool_text(summary['rootEntryFixedTraversalFillSitesReachable'])}; "
            "encoded entry "
            f"{html.escape(str(summary.get('encodedFillEntryClassification')))} "
            f"raw {html.escape(str(summary.get('encodedFillEntryRawScalarCandidateCount')))} "
            f"promoting {html.escape(str(summary.get('encodedFillEntryPromotingCandidateCount')))}; "
            "raw scalar rejection "
            f"<code>{html.escape(str(summary.get('encodedRawScalarRejectionClassification')))}</code> "
            "no-fixed/no-branch/branch-attached/scalar-only "
            f"{html.escape(str(summary.get('encodedRawScalarNoFixedAdvanceCount')))}/"
            f"{html.escape(str(summary.get('encodedRawScalarNoBranchJumpCount')))}/"
            f"{html.escape(str(summary.get('encodedRawScalarBranchAttachedCount')))}/"
            f"{html.escape(str(summary.get('encodedRawScalarScalarOnlyCount')))}; "
            "root/fill descriptor boundaries "
            f"{bool_text(summary.get('predecessorDataDescriptorBoundariesProven'))}; "
            "slice dispatch proof "
            f"{bool_text(summary.get('predecessorDispatchSliceRuntimeProofFound'))}; "
            "descriptor depends on slice "
            f"{bool_text(summary.get('predecessorDescriptorDependsOnSaveSelectorSliceModel'))}; "
            "slice byte-reachable/requires-table-base "
            f"{html.escape(str(summary.get('predecessorDispatchSliceGenericByteReachableCount')))}/"
            f"{html.escape(str(summary.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')))}; "
            "dynamic dispatches/SEH-scope/table-base-immediates "
            f"{html.escape(str(summary.get('predecessorDispatchDynamicIndexedDispatchRowCount')))}/"
            f"{html.escape(str(summary.get('predecessorDispatchDynamicScopeTableCallbackCount')))}/"
            f"{html.escape(str(summary.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')))}; "
            "table-base rejection "
            f"<code>{html.escape(str(summary.get('predecessorDispatchTableBaseRejectionClassification')))}</code>; "
            "table-base candidates "
            f"{html.escape(str(summary.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')))}; "
            "table-base arithmetic rows/candidates "
            f"{html.escape(str(summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')))}/"
            f"{html.escape(str(summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')))}; "
            "dynamic table-base candidate "
            f"{bool_text(summary.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound'))}; "
            "raw generic contrast "
            f"<code>{html.escape(str(summary.get('rawGenericClassification')))}</code> "
            "handlers "
            f"{html.escape(str(summary.get('rawGenericHandlerCount')))} "
            "route/fill/current immediates "
            f"{html.escape(str(summary.get('rawGenericRouteImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericFillImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericCurrentImmediateHitCount')))}; "
            "selected/branch-state immediates "
            f"{html.escape(str(summary.get('rawGenericSelectedPointerImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericBranchStateImmediateHitCount')))}; "
            "mapped calls "
            f"{html.escape(str(summary.get('rawGenericMappedDirectCallCount')))} "
            f"targets {html.escape(list_text(summary.get('rawGenericMappedDirectCallTargets')))}; "
            "one-hop route/fill/current immediates "
            f"{html.escape(str(summary.get('rawGenericOneHopRouteImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericOneHopFillImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericOneHopCurrentImmediateHitCount')))}; "
            "route/fill transfers "
            f"{html.escape(str(summary.get('rawGenericRouteDirectTransferHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericFillDirectTransferHitCount')))}; "
            "one-hop route/fill transfers "
            f"{html.escape(str(summary.get('rawGenericOneHopRouteDirectTransferHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericOneHopFillDirectTransferHitCount')))}; "
            "call graph "
            f"<code>{html.escape(str(summary.get('rawGenericCallGraphClassification')))}</code> "
            "depth "
            f"{html.escape(str(summary.get('rawGenericCallGraphMaxDepth')))} "
            "functions/edges "
            f"{html.escape(str(summary.get('rawGenericCallGraphReachableFunctionCount')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphDirectCallEdgeCount')))}; "
            "call graph route/fill/current immediates "
            f"{html.escape(str(summary.get('rawGenericCallGraphRouteImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphFillImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphCurrentImmediateHitCount')))}; "
            "call graph selected/branch-state immediates "
            f"{html.escape(str(summary.get('rawGenericCallGraphSelectedPointerImmediateHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphBranchStateImmediateHitCount')))}; "
            "call graph route/fill transfers "
            f"{html.escape(str(summary.get('rawGenericCallGraphRouteDirectTransferHitCount')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphFillDirectTransferHitCount')))}; "
            "depth sensitivity max/no-proof/stable "
            f"{html.escape(str(summary.get('rawGenericCallGraphDepthSensitivityMaxDepthChecked')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth')))}; "
            f"raw route proof {bool_text(summary.get('rawGenericRouteProofFound'))}; "
            f"runtime fill {bool_text(summary['runtimeObservedFill'])}; "
            "field-entry input "
            f"<code>{html.escape(str(summary.get('fieldEntryInputStatus')))}</code> "
            "seq/candidates/snapshots/routeSnapshots "
            f"{html.escape(str(summary.get('fieldEntrySequenceCount')))}/"
            f"{html.escape(str(summary.get('fieldEntryCandidateCount')))}/"
            f"{html.escape(str(summary.get('fieldEntrySnapshotCount')))}/"
            f"{html.escape(str(summary.get('fieldEntrySnapshotRouteCandidateCount')))}; "
            "runtime field-entry proof "
            f"proof {bool_text(summary.get('fieldEntryProofFound'))} "
            f"candidateProof {bool_text(summary.get('predecessorFieldEntryProofFound'))} "
            f"failed {html.escape(list_text(summary.get('fieldEntryFailedGateIds')))} "
            f"evidenceRefs {html.escape(str(summary.get('fieldEntryEvidenceRefCount')))}; "
            "coordinate source "
            f"<code>{html.escape(str(summary.get('coordinateSourceClassification')))}</code>/"
            f"<code>{html.escape(str(summary.get('coordinateSourceRejectionClassification')))}</code> "
            "public-start ptr/static/trail/image "
            f"{html.escape(str(summary.get('coordinateSourcePublicStartPointerTableTileHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourcePublicStartStaticBaseHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourcePublicStartTrailRingHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourcePublicStartImageHitCount')))}; "
            "observed-trail ptr/static/trail/image "
            f"{html.escape(str(summary.get('coordinateSourceObservedTrailPointerTableTileHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourceObservedTrailStaticBaseHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourceObservedTrailTrailRingHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourceObservedTrailImageHitCount')))}; "
            "reciprocal ptr/static/trail/image "
            f"{html.escape(str(summary.get('coordinateSourceReciprocalPointerTableTileHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourceReciprocalStaticBaseHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourceReciprocalTrailRingHitCount')))}/"
            f"{html.escape(str(summary.get('coordinateSourceReciprocalImageHitCount')))}; "
            "selector merge runtime/closure "
            f"shapeOnly={bool_text(summary.get('selectorMergeShapeOnly'))} "
            f"forwardAbsent={bool_text(summary.get('selectorMergeForwardBridgeAbsent'))} "
            f"reverseBeforeFillOnly={bool_text(summary.get('selectorMergeReverseReuseBeforeFillOnly'))} "
            f"runtimeProof={bool_text(summary.get('selectorMergeRuntimeProofFound'))} "
            f"closureProof={bool_text(summary.get('selectorMergeClosureProofFound'))} "
            f"persistenceUsable={bool_text(summary.get('predecessorPersistenceUsableForCurrent'))}; "
            "proof gates blocked/pass/all-blocked "
            f"{html.escape(str(summary.get('predecessorFillProofGateBlockedCount')))}/"
            f"{html.escape(str(summary.get('predecessorFillProofGatePassCount')))}/"
            f"{bool_text(summary.get('predecessorFillAllProofGatesBlocked'))}; "
            "failed fill-order gates "
            f"<code>{html.escape(list_text(summary.get('failedPredecessorFillOrderGateIds')))}</code>; "
            f"missing evidence {len(summary.get('missingEvidence') or [])}; "
            f"proof found {bool_text(summary['proofFound'])}; "
            f"promotion status <code>{html.escape(summary['promotionStatus'])}</code>.</p>"
        ),
        "  <h2>Proof Gates</h2>",
        f"  <table><thead><tr><th>id</th><th>pass</th><th>status</th><th>detail</th></tr></thead><tbody>{proof_gate_rows}</tbody></table>",
        "  <h2>Dispatch Table-Base Audit</h2>",
        f"  <table><thead><tr><th>kind</th><th>site/instruction</th><th>status</th><th>detail</th></tr></thead><tbody>{table_base_audit_rows}</tbody></table>",
        "  <h2>Evidence Refs</h2>",
        f"  <table><thead><tr><th>path</th><th>fields</th></tr></thead><tbody>{evidence_ref_rows}</tbody></table>",
        "  <h2>Missing Evidence</h2>",
        f"  <ul>{missing_items}</ul>",
        "  <h2>Evidence</h2>",
        f"  <table><thead><tr><th>kind</th><th>status</th><th>detail</th></tr></thead><tbody>{evidence_rows}</tbody></table>",
        "  <h2>Local Fill Trace</h2>",
        f"  <table><thead><tr><th>step</th><th>va</th><th>value</th><th>opcode</th><th>handler</th><th>advance</th><th>stop</th></tr></thead><tbody>{trace_rows}</tbody></table>",
        "  <h2>Remaining Proofs</h2>",
        f"  <ul>{proof_items}</ul>",
        "</body>",
        "</html>",
        "",
    ])


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


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--exe", type=Path, default=ROOT / "Hwanse2.exe")
    parser.add_argument("--predecessor-branch-state-execution-gap", type=Path, default=OUT / "save_selector_predecessor_branch_state_execution_gap.json")
    parser.add_argument("--predecessor-tail-reset", type=Path, default=OUT / "save_selector_predecessor_tail_reset.json")
    parser.add_argument("--secondary-global-reset-gap", type=Path, default=OUT / "save_selector_secondary_global_reset_gap.json")
    parser.add_argument("--predecessor-persistence-gap", type=Path, default=OUT / "save_selector_predecessor_persistence_gap.json")
    parser.add_argument("--predecessor-route-order", type=Path, default=OUT / "save_selector_predecessor_route_order.json")
    parser.add_argument("--merge-execution-gap", type=Path, default=OUT / "save_selector_merge_execution_gap.json")
    parser.add_argument("--merge-runtime-context", type=Path, default=OUT / "save_selector_merge_runtime_context.json")
    parser.add_argument("--merge-closure-context", type=Path, default=OUT / "save_selector_merge_closure_context.json")
    parser.add_argument("--frontier-reader-branch-context", type=Path, default=OUT / "save_selector_frontier_reader_branch_context.json")
    parser.add_argument("--data-descriptor-opcode-map", type=Path, default=OUT / "save_selector_data_descriptor_opcode_map.json")
    parser.add_argument("--dispatch-table-context", type=Path, default=OUT / "save_selector_dispatch_table_context.json")
    parser.add_argument("--field-entry-sequence-scan", type=Path, default=OUT / "runtime_predecessor_field_entry_sequence_scan.json")
    parser.add_argument("--coordinate-source-scan", type=Path, default=OUT / "runtime_predecessor_coordinate_source_scan.json")
    parser.add_argument("--out-dir", type=Path, default=OUT)
    parser.add_argument("--max-steps", type=int, default=8)
    args = parser.parse_args()
    summary = build_summary(
        args.exe.read_bytes(),
        load_json(args.predecessor_branch_state_execution_gap),
        load_json(args.predecessor_tail_reset),
        load_json(args.secondary_global_reset_gap),
        load_json(args.predecessor_persistence_gap),
        load_json(args.predecessor_route_order),
        load_json(args.merge_execution_gap),
        load_json(args.merge_runtime_context, {}),
        load_json(args.merge_closure_context, {}),
        load_json(args.frontier_reader_branch_context, {}),
        load_json(args.data_descriptor_opcode_map, {}),
        load_json(args.dispatch_table_context, {}),
        args.max_steps,
        load_json(args.field_entry_sequence_scan, {}),
        load_json(args.coordinate_source_scan, {}),
    )
    write_outputs(summary, args.out_dir)
    print(
        "wrote predecessor fill execution/order gap -> "
        f"{args.out_dir / 'save_selector_predecessor_fill_execution_order_gap.html'}"
    )


if __name__ == "__main__":
    main()
