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

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


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

PRED_FILL_MISSING_EVIDENCE_BY_GATE = {
    "root-entry-to-fill": "root-entry execution path from 0x00478364 to 0x004844d0/0x004844d8",
    "descriptor-boundary-bridge": "descriptor-boundary bridge from predecessor root stop through fill to current reader",
    "dispatch-slice-runtime-proof": "runtime proof that predecessor fill stream executes through the save-selector dispatch slice",
    "runtime-fill-observed": "runtime branch-state observation matching the predecessor fill hypothesis",
    "route-order": "predecessor-to-current route order proof before the 0x00542b0c reader",
    "selector-merge-closed": "closed selector-merge proof connecting predecessor 1:0 and source 0:0 into current 2:0",
}


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 csv(values: list[Any] | None) -> str:
    return ",".join(str(value) for value in values or []) or "-"


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


def int_sum(values: list[Any]) -> int:
    total = 0
    for value in values:
        try:
            total += int(value or 0)
        except (TypeError, ValueError):
            pass
    return total


def target_hit_sum(hits: dict, labels: list[str]) -> int:
    return int_sum([hits.get(label) for label in labels])


def split_for(row_name: str, branch_state_execution_gap: dict) -> dict:
    key_by_name = {
        "direction-sweep": "runtimeBranchStateSplit",
        "left-overrun-activation": "leftOverrunActivationRuntimeBranchStateSplit",
        "nearest-exit": "nearestExitRuntimeBranchStateSplit",
        "reciprocal-exits": "reciprocalExitRuntimeBranchStateSplit",
        "coordinate": "coordinateRuntimeBranchStateSplit",
        "trail-start": "trailStartRuntimeBranchStateSplit",
        "trail-left-overrun": "trailLeftOverrunRuntimeBranchStateSplit",
        "high-frequency": "highFrequencyRuntimeBranchStateSplit",
    }
    return branch_state_execution_gap.get(key_by_name[row_name]) or {}


def compact_selector_poll(name: str, poll: dict | None) -> dict:
    poll = poll or {}
    return {
        "name": name,
        "available": poll.get("available") is True,
        "stagedSaveKind": poll.get("stagedSaveKind"),
        "sequenceCount": poll.get("sequenceCount"),
        "sampleCount": poll.get("sampleCount"),
        "observedSelectors": poll.get("observedSelectors") or [],
        "observedPublicSaveSelectors": poll.get("observedPublicSaveSelectors") or [],
        "publicPredecessorReached": poll.get("anyReachedPublicSaveSelector") is True,
        "currentRootReached": poll.get("anyReachedCurrentRoot") is True,
        "routeSelectorReached": poll.get("anyReachedRouteSelectorContext") is True,
        "promotionStatus": poll.get("promotionStatus"),
    }


def compact_branch_state_poll(name: str, poll: dict | None, split: dict | None) -> dict:
    poll = poll or {}
    split = split or {}
    return {
        "name": name,
        "available": poll.get("available") is True,
        "stagedSaveKind": poll.get("stagedSaveKind"),
        "sequenceCount": poll.get("sequenceCount"),
        "sampleCount": poll.get("sampleCount"),
        "observedSelectors": poll.get("observedSelectors") or [],
        "observedPublicSaveSelectors": poll.get("observedPublicSaveSelectors") or [],
        "publicPredecessorReached": poll.get("anyReachedPublicSaveSelector") is True,
        "currentRootReached": poll.get("anyReachedCurrentRoot") is True,
        "routeSelectorReached": poll.get("anyReachedRouteSelectorContext") is True,
        "activeSelectionFlagHex": poll.get("activeSelectionFlagHex"),
        "secondaryBranchStateHexes": poll.get("secondaryBranchStateHexes") or [],
        "secondaryBranchStateAllZero": poll.get("secondaryBranchStateAllZero") is True,
        "matchesPredecessorFillHypothesis": poll.get("matchesPredecessorFillHypothesis") is True,
        "splitClassification": split.get("classification"),
        "splitNextProofFocus": split.get("nextProofFocus"),
        "coordinateTargetObserved": split.get("coordinateAnyTargetTileObserved"),
        "trailStartTargetObserved": split.get("trailAnyTargetTileObserved"),
        "trailStartMovementObserved": split.get("trailAnyTrailMovementObserved"),
        "trailLeftOverrunCameraTargetObserved": split.get("cameraTargetObserved"),
        "trailLeftOverrunActorTargetObserved": split.get("actorTargetObserved"),
        "trailLeftOverrunTrailTargetObserved": split.get("trailTargetObserved"),
    }


def branch_row_target_observed(row: dict) -> bool:
    return any(
        row.get(key) is True
        for key in (
            "coordinateTargetObserved",
            "trailStartTargetObserved",
            "trailLeftOverrunCameraTargetObserved",
            "trailLeftOverrunActorTargetObserved",
            "trailLeftOverrunTrailTargetObserved",
        )
    )


def branch_row_actor_or_trail_target_observed(row: dict) -> bool:
    return any(
        row.get(key) is True
        for key in (
            "coordinateTargetObserved",
            "trailStartTargetObserved",
            "trailLeftOverrunActorTargetObserved",
            "trailLeftOverrunTrailTargetObserved",
        )
    )


def branch_row_camera_only_target_observed(row: dict) -> bool:
    return (
        row.get("trailLeftOverrunCameraTargetObserved") is True
        and row.get("trailLeftOverrunActorTargetObserved") is not True
        and row.get("trailLeftOverrunTrailTargetObserved") is not True
    )


def branch_row_movement_or_target_observed(row: dict) -> bool:
    return row.get("trailStartMovementObserved") is True or branch_row_target_observed(row)


def sum_samples(rows: list[dict]) -> int:
    return int_sum([row.get("sampleCount") for row in rows])


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 computed_field_entry_snapshot_context(scan: dict | None) -> dict:
    scan = scan or {}
    selector_counts: dict[str, int] = {}
    camera_counts: dict[str, int] = {}
    snapshot_count = 0
    route_candidate_names = []
    for sequence_row in scan.get("rows") or []:
        sequence_has_route = False
        row_selector_counts: dict[str, int] = {}
        row_camera_counts: dict[str, int] = {}
        for snapshot in (sequence_row.get("scan") or {}).get("snapshots") or []:
            snapshot_count += 1
            selector = (snapshot.get("selectedPointerContext") or {}).get("selector") or "-"
            selector_counts[selector] = selector_counts.get(selector, 0) + 1
            row_selector_counts[selector] = row_selector_counts.get(selector, 0) + 1
            camera = snapshot.get("cameraTile") or {}
            camera_key = f"{camera.get('x')},{camera.get('y')}"
            camera_counts[camera_key] = camera_counts.get(camera_key, 0) + 1
            row_camera_counts[camera_key] = row_camera_counts.get(camera_key, 0) + 1
            if selector == "2:0":
                sequence_has_route = True
        if sequence_has_route:
            route_candidate_names.append(sequence_row.get("name"))
        sequence_row.setdefault("snapshotSelectorCounts", row_selector_counts)
        sequence_row.setdefault("snapshotCameraTileCounts", row_camera_counts)
        sequence_row.setdefault("snapshotCount", sum(row_selector_counts.values()))
        sequence_row.setdefault("snapshotRouteCandidate", sequence_has_route)
    return {
        "snapshotCount": scan.get("snapshotCount", snapshot_count),
        "snapshotRouteCandidateCount": scan.get(
            "snapshotRouteCandidateCount",
            len(route_candidate_names),
        ),
        "snapshotRouteCandidateNames": scan.get("snapshotRouteCandidateNames") or route_candidate_names,
        "snapshotSelectorCounts": scan.get("snapshotSelectorCounts") or selector_counts,
        "snapshotCameraTileCounts": scan.get("snapshotCameraTileCounts") or camera_counts,
    }


def build_summary(
    fill_execution_order_gap: dict,
    branch_state_execution_gap: dict,
    descriptor_bridge_gap: dict,
    coordinate_source_scan: dict | None = None,
    field_entry_sequence_scan: dict | None = None,
    branch_gate_consistency: dict | None = None,
) -> dict:
    source = fill_execution_order_gap.get("source") or branch_state_execution_gap.get("source")
    target = fill_execution_order_gap.get("target") or branch_state_execution_gap.get("target")
    coordinate_source_scan = coordinate_source_scan or {}
    field_entry_sequence_scan = field_entry_sequence_scan or {}
    branch_gate_consistency = branch_gate_consistency or {}
    if (
        branch_gate_consistency.get("source") != source
        or branch_gate_consistency.get("target") != target
    ):
        branch_gate_consistency = {}
    branch_gate_other_write_offsets = (
        branch_gate_consistency.get("postWriterOtherOffsetWriteOffsetsHex") or []
    )
    branch_gate_invalid_fill_offsets = (
        branch_gate_consistency.get("invalidSecondaryFillOffsetsHex") or []
    )
    selector_poll_rows = [
        compact_selector_poll(
            "progress",
            branch_state_execution_gap.get("predecessorProgressPoll"),
        ),
        compact_selector_poll(
            "direction-sweep",
            branch_state_execution_gap.get("predecessorDirectionSweepPoll"),
        ),
    ]
    branch_state_poll_rows = [
        compact_branch_state_poll(
            "direction-sweep",
            branch_state_execution_gap.get("predecessorBranchStatePoll"),
            split_for("direction-sweep", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "left-overrun-activation",
            branch_state_execution_gap.get("predecessorLeftOverrunActivationBranchStatePoll"),
            split_for("left-overrun-activation", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "nearest-exit",
            branch_state_execution_gap.get("predecessorNearestExitBranchStatePoll"),
            split_for("nearest-exit", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "reciprocal-exits",
            branch_state_execution_gap.get("predecessorReciprocalExitBranchStatePoll"),
            split_for("reciprocal-exits", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "coordinate",
            branch_state_execution_gap.get("predecessorCoordinateBranchStatePoll"),
            split_for("coordinate", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "trail-start",
            branch_state_execution_gap.get("predecessorTrailStartBranchStatePoll"),
            split_for("trail-start", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "trail-left-overrun",
            branch_state_execution_gap.get("predecessorTrailLeftOverrunBranchStatePoll"),
            split_for("trail-left-overrun", branch_state_execution_gap),
        ),
        compact_branch_state_poll(
            "high-frequency",
            branch_state_execution_gap.get("predecessorHighFrequencyBranchStatePoll"),
            split_for("high-frequency", branch_state_execution_gap),
        ),
    ]
    available_branch_rows = [row for row in branch_state_poll_rows if row["available"]]
    selector_progress_sample_count = sum(
        int(row.get("sampleCount") or 0) for row in selector_poll_rows if row["available"]
    )
    branch_state_sample_count = sum(
        int(row.get("sampleCount") or 0) for row in available_branch_rows
    )
    branch_state_sequence_count = sum(
        int(row.get("sequenceCount") or 0) for row in available_branch_rows
    )
    branch_state_all_zero_count = sum(
        1 for row in available_branch_rows if row["secondaryBranchStateAllZero"]
    )
    branch_state_fill_match_count = sum(
        1 for row in available_branch_rows if row["matchesPredecessorFillHypothesis"]
    )
    branch_state_public_hit_count = sum(
        1 for row in available_branch_rows if row["publicPredecessorReached"]
    )
    branch_state_route_hit_count = sum(
        1 for row in available_branch_rows if row["routeSelectorReached"]
    )
    branch_state_current_root_hit_count = sum(
        1 for row in available_branch_rows if row["currentRootReached"]
    )
    branch_state_target_observation_rows = [
        row for row in available_branch_rows if branch_row_target_observed(row)
    ]
    branch_state_actor_or_trail_target_rows = [
        row for row in available_branch_rows if branch_row_actor_or_trail_target_observed(row)
    ]
    branch_state_camera_only_target_rows = [
        row for row in available_branch_rows if branch_row_camera_only_target_observed(row)
    ]
    branch_state_movement_or_target_rows = [
        row for row in available_branch_rows if branch_row_movement_or_target_observed(row)
    ]
    branch_state_target_observation_status = (
        "camera-target-only-fill-not-observed"
        if (
            branch_state_camera_only_target_rows
            and not branch_state_actor_or_trail_target_rows
            and not any(row["matchesPredecessorFillHypothesis"] for row in branch_state_target_observation_rows)
            and not any(row["routeSelectorReached"] for row in branch_state_target_observation_rows)
            and not any(row["currentRootReached"] for row in branch_state_target_observation_rows)
        )
        else "actor-or-trail-target-observed"
        if branch_state_actor_or_trail_target_rows
        else "target-not-observed"
    )
    final_coordinate_snapshot = final_snapshot(coordinate_source_scan)
    coordinate_context = {
        "classification": coordinate_source_scan.get("classification"),
        "coordinateSourceRejectionClassification": coordinate_source_scan.get(
            "coordinateSourceRejectionClassification"
        ),
        "promotionStatus": coordinate_source_scan.get("promotionStatus"),
        "finalSelector": (final_coordinate_snapshot.get("selectedPointerContext") or {}).get("selector"),
        "finalCameraTile": final_coordinate_snapshot.get("cameraTile") or {},
        "pairHitSummaryRows": coordinate_source_scan.get("pairHitSummaryRows") or [],
        "publicSaveStartPointerTableTileHitCount": coordinate_source_scan.get(
            "publicSaveStartPointerTableTileHitCount"
        ),
        "publicSaveStartStaticBaseHitCount": coordinate_source_scan.get(
            "publicSaveStartStaticBaseHitCount"
        ),
        "publicSaveStartTrailRingHitCount": coordinate_source_scan.get(
            "publicSaveStartTrailRingHitCount"
        ),
        "publicSaveStartImageHitCount": coordinate_source_scan.get(
            "publicSaveStartImageHitCount",
            image_hit_count(coordinate_source_scan, "public-save-start"),
        ),
        "publicSaveStartKnownGlobalImageHitCount": coordinate_source_scan.get(
            "publicSaveStartKnownGlobalImageHitCount"
        ),
        "observedTrailPointerTableTileHitCount": coordinate_source_scan.get(
            "observedTrailPointerTableTileHitCount"
        ),
        "observedTrailStaticBaseHitCount": coordinate_source_scan.get(
            "observedTrailStaticBaseHitCount"
        ),
        "observedTrailTrailRingHitCount": coordinate_source_scan.get(
            "observedTrailTrailRingHitCount"
        ),
        "observedTrailImageHitCount": coordinate_source_scan.get(
            "observedTrailImageHitCount",
            image_hit_count(coordinate_source_scan, "observed-trail"),
        ),
        "observedTrailKnownGlobalImageHitCount": coordinate_source_scan.get(
            "observedTrailKnownGlobalImageHitCount"
        ),
        "reciprocalPointerTableTileHitCount": coordinate_source_scan.get(
            "reciprocalPointerTableTileHitCount"
        ),
        "reciprocalStaticBaseHitCount": coordinate_source_scan.get("reciprocalStaticBaseHitCount"),
        "reciprocalTrailRingHitCount": coordinate_source_scan.get("reciprocalTrailRingHitCount"),
        "reciprocalImageHitCount": coordinate_source_scan.get("reciprocalImageHitCount"),
        "remainingProofs": coordinate_source_scan.get("remainingProofs") or [],
        "conclusion": coordinate_source_scan.get("conclusion"),
    }
    field_entry_context = {
        "sequenceCount": field_entry_sequence_scan.get("sequenceCount"),
        "fieldEntryCandidateCount": field_entry_sequence_scan.get("fieldEntryCandidateCount"),
        "fieldEntryCandidateNames": field_entry_sequence_scan.get("fieldEntryCandidateNames") or [],
        "finalSelectorCounts": field_entry_sequence_scan.get("finalSelectorCounts") or {},
        "finalCameraTileCounts": field_entry_sequence_scan.get("finalCameraTileCounts") or {},
        "classificationCounts": field_entry_sequence_scan.get("classificationCounts") or {},
        "activeOrderPatternCounts": field_entry_sequence_scan.get("activeOrderPatternCounts") or {},
        "promotionStatus": field_entry_sequence_scan.get("promotionStatus"),
        "proofFound": field_entry_sequence_scan.get("proofFound"),
        "predecessorFieldEntryProofFound": field_entry_sequence_scan.get(
            "predecessorFieldEntryProofFound"
        ),
        "fieldEntryRouteCandidateFound": field_entry_sequence_scan.get(
            "fieldEntryRouteCandidateFound"
        ),
        "selector2FinalObserved": field_entry_sequence_scan.get("selector2FinalObserved"),
        "selector2SnapshotObserved": field_entry_sequence_scan.get("selector2SnapshotObserved"),
        "routeRelevantRuntimeObjectTileFound": field_entry_sequence_scan.get(
            "routeRelevantRuntimeObjectTileFound"
        ),
        "selectedRootExecutionProofFound": field_entry_sequence_scan.get(
            "selectedRootExecutionProofFound"
        ),
        "failedPredecessorFieldEntryGateIds": field_entry_sequence_scan.get(
            "failedPredecessorFieldEntryGateIds"
        )
        or [],
        "missingEvidence": field_entry_sequence_scan.get("missingEvidence") or [],
        "remainingProofs": field_entry_sequence_scan.get("remainingProofs") or [],
        "evidenceRefs": field_entry_sequence_scan.get("evidenceRefs") or [],
        "evidenceRefCount": field_entry_sequence_scan.get("evidenceRefCount"),
        "conclusion": field_entry_sequence_scan.get("conclusion"),
    }
    field_entry_context.update(computed_field_entry_snapshot_context(field_entry_sequence_scan))
    root_entry_traversal = fill_execution_order_gap.get("rootEntryFixedTraversal") or {}
    root_entry_stop_rows = root_entry_traversal.get("stopRows") or []
    root_entry_stop = root_entry_stop_rows[0] if root_entry_stop_rows else {}
    encoded_fill_entry = fill_execution_order_gap.get("encodedFillEntryCandidateScan") or {}
    encoded_raw_scalar_rejection = fill_execution_order_gap.get("encodedRawScalarRejection") or {}
    root_tail_isolation = fill_execution_order_gap.get("rootTailIsolationScan") or {}
    root_tail_immediate_predecessor = root_tail_isolation.get("immediatePredecessorRow") or {}
    descriptor_root_closure = descriptor_bridge_gap.get("rootStopDescriptorClosure") or {}
    descriptor_fill_closure = descriptor_bridge_gap.get("fillStopDescriptorClosure") or {}
    descriptor_edge_rejection = descriptor_bridge_gap.get("descriptorEdgeRejection") or {}
    descriptor_encoded_target_scan = descriptor_bridge_gap.get("descriptorEncodedTargetScan") or {}
    descriptor_root_edge_hits = descriptor_root_closure.get("targetEdgeHits") or {}
    descriptor_fill_edge_hits = descriptor_fill_closure.get("targetEdgeHits") or {}
    fill_site_target_labels = ["predecessor-fill-site-0", "predecessor-fill-site-1"]
    descriptor_root_fill_site_edge_hit_count = target_hit_sum(
        descriptor_root_edge_hits,
        fill_site_target_labels,
    )
    descriptor_fill_fill_site_edge_hit_count = target_hit_sum(
        descriptor_fill_edge_hits,
        fill_site_target_labels,
    )
    root_entry_reaches_fill = fill_execution_order_gap.get("rootEntryFixedTraversalFillSitesReachable") is True
    descriptor_bridge_proof = descriptor_bridge_gap.get("descriptorBridgeProofFound") is True
    dispatch_slice_runtime_proof = (
        fill_execution_order_gap.get("predecessorDispatchSliceRuntimeProofFound") is True
    )
    runtime_fill_observed = (
        fill_execution_order_gap.get("runtimeObservedFill") is True
        or branch_state_execution_gap.get("runtimePredecessorFillObserved") is True
        or branch_state_fill_match_count > 0
    )
    route_order_proven = fill_execution_order_gap.get("routeOrderProven") is True
    selector_merge_closed = fill_execution_order_gap.get("selectorMergeGapOpen") is False
    dispatch_table_base_rejection = (
        fill_execution_order_gap.get("predecessorDispatchTableBaseRejection") or {}
    )
    dispatch_table_base_audit_rows = (
        fill_execution_order_gap.get("predecessorDispatchTableBaseAuditRows")
        or dispatch_table_base_rejection.get("predecessorDispatchTableBaseAuditRows")
        or []
    )
    raw_generic_call_graph = fill_execution_order_gap.get("rawGenericCallGraphContrast") or {}
    raw_generic_call_graph_depth = (
        fill_execution_order_gap.get("rawGenericCallGraphDepthSensitivity") or {}
    )
    fill_site_execution_context_proven = (
        root_entry_reaches_fill
        and descriptor_bridge_proof
        and dispatch_slice_runtime_proof
        and runtime_fill_observed
        and route_order_proven
        and selector_merge_closed
    )
    required_proof_gates = [
        {
            "gate": "root-entry-to-fill",
            "passed": root_entry_reaches_fill,
            "status": "passed" if root_entry_reaches_fill else "blocked",
            "detail": (
                f"visited={root_entry_traversal.get('visitedNodeCount')}; "
                f"targets={csv(root_entry_traversal.get('targetHexes') or [])}; "
                f"reached={csv(root_entry_traversal.get('reachableTargetHexes') or [])}; "
                f"stop={root_entry_stop.get('vaHex')}:{root_entry_stop.get('reason')}"
            ),
        },
        {
            "gate": "descriptor-boundary-bridge",
            "passed": descriptor_bridge_proof,
            "status": "passed" if descriptor_bridge_proof else "blocked",
            "detail": (
                f"rootNodes={descriptor_root_closure.get('visitedNodeCount')}; "
                f"rootFillEdges={descriptor_root_fill_site_edge_hit_count}; "
                f"rootReaderEdges={descriptor_root_edge_hits.get('current-reader')}; "
                f"fillNodes={descriptor_fill_closure.get('visitedNodeCount')}; "
                f"fillReaderEdges={descriptor_fill_edge_hits.get('current-reader')}; "
                f"edgeReject={descriptor_edge_rejection.get('classification')}; "
                "descriptorEdges="
                f"{descriptor_edge_rejection.get('rootDescriptorTargetEdgeCount')}/"
                f"{descriptor_edge_rejection.get('fillDescriptorTargetEdgeCount')}; "
                "routeEdges="
                f"{descriptor_edge_rejection.get('rootRouteExecutionTargetEdgeCount')}/"
                f"{descriptor_edge_rejection.get('fillRouteExecutionTargetEdgeCount')}; "
                "encodedRouteTargets="
                f"{descriptor_encoded_target_scan.get('rawScalarCandidateCount')}/"
                f"{descriptor_encoded_target_scan.get('promotingCandidateCount')}; "
                f"encodedClass={descriptor_encoded_target_scan.get('classification')}; "
                f"bridgeProof={descriptor_bridge_gap.get('proofFound')}; "
                "bridgeFailedGates="
                f"{csv(descriptor_bridge_gap.get('failedDescriptorBridgeGateIds'))}; "
                "bridgeMissingEvidenceCount="
                f"{len(descriptor_bridge_gap.get('missingEvidence') or [])}; "
                f"bridgeEvidenceRefs={descriptor_bridge_gap.get('evidenceRefCount')}"
            ),
        },
        {
            "gate": "dispatch-slice-runtime-proof",
            "passed": dispatch_slice_runtime_proof,
            "status": "passed" if dispatch_slice_runtime_proof else "blocked",
            "detail": (
                f"sliceRuntimeProof={fill_execution_order_gap.get('predecessorDispatchSliceRuntimeProofFound')}; "
                f"dispatchTableProof={fill_execution_order_gap.get('predecessorDispatchTableProofFound')}; "
                "dispatchFailedGates="
                f"{csv(fill_execution_order_gap.get('predecessorDispatchTableFailedGateIds'))}; "
                "dispatchMissingEvidenceCount="
                f"{len(fill_execution_order_gap.get('predecessorDispatchTableMissingEvidence') or [])}; "
                f"dispatchEvidenceRefs={fill_execution_order_gap.get('predecessorDispatchTableEvidenceRefCount')}; "
                f"descriptorDependsOnSlice={fill_execution_order_gap.get('predecessorDescriptorDependsOnSaveSelectorSliceModel')}; "
                f"rawDiffers={fill_execution_order_gap.get('predecessorDispatchRawGeneralDiffersFromSliceCount')}; "
                f"byteReachable={fill_execution_order_gap.get('predecessorDispatchSliceGenericByteReachableCount')}; "
                f"requiresTableBase={fill_execution_order_gap.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')}; "
                f"dynamicDispatches={fill_execution_order_gap.get('predecessorDispatchDynamicIndexedDispatchRowCount')}/"
                f"{fill_execution_order_gap.get('predecessorDispatchDynamicScopeTableCallbackCount')}/"
                f"{fill_execution_order_gap.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')}; "
                f"dynamicTableBaseCandidate="
                f"{fill_execution_order_gap.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}; "
                f"tableBaseArithmetic={fill_execution_order_gap.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')}/"
                f"{fill_execution_order_gap.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')}; "
                f"tableBaseReject={dispatch_table_base_rejection.get('classification')}"
            ),
        },
        {
            "gate": "runtime-fill-observed",
            "passed": runtime_fill_observed,
            "status": "passed" if runtime_fill_observed else "blocked",
            "detail": (
                f"polls={len(available_branch_rows)}; seq={branch_state_sequence_count}; "
                f"samples={branch_state_sample_count}; publicHits={branch_state_public_hit_count}; "
                f"fillMatches={branch_state_fill_match_count}; allZero={branch_state_all_zero_count}"
            ),
        },
        {
            "gate": "route-order",
            "passed": route_order_proven,
            "status": "passed" if route_order_proven else "blocked",
            "detail": f"routeOrderProven={route_order_proven}",
        },
        {
            "gate": "selector-merge-closed",
            "passed": selector_merge_closed,
            "status": "passed" if selector_merge_closed else "blocked",
            "detail": f"selectorMergeGapOpen={not selector_merge_closed}",
        },
    ]
    required_proof_gate_pass_count = sum(1 for row in required_proof_gates if row["passed"])
    required_proof_gate_fail_count = len(required_proof_gates) - required_proof_gate_pass_count
    required_proof_gate_status_order = [row["gate"] for row in required_proof_gates]
    required_proof_gate_statuses = {
        row["gate"]: row["status"] for row in required_proof_gates
    }
    required_proof_gate_fail_ids = [
        row["gate"] for row in required_proof_gates if row["passed"] is not True
    ]
    missing_evidence = [
        PRED_FILL_MISSING_EVIDENCE_BY_GATE.get(gate_id, gate_id)
        for gate_id in required_proof_gate_fail_ids
    ]
    evidence_refs = [
        {
            "path": "out/save_selector_predecessor_fill_execution_order_gap.json",
            "fields": [
                "localFillTraceContainsAllFillSites",
                "localFillTraceReachesCurrentReader",
                "rootEntryFixedTraversalFillSitesReachable",
                "predecessorDispatchSliceRuntimeProofFound",
                "predecessorDispatchTableBaseAuditRows",
                "predecessorFillProofGateRows",
                "proofFound",
            ],
        },
        {
            "path": "out/save_selector_predecessor_branch_state_execution_gap.json",
            "fields": [
                "predecessorBranchStatePoll",
                "runtimeBranchStateSplit",
                "publicPredecessorBranchStateAllZero",
                "branchStateExecutionProofFound",
                "runtimePredecessorFillObserved",
            ],
        },
        {
            "path": "out/save_selector_predecessor_descriptor_bridge_gap.json",
            "fields": [
                "proofFound",
                "failedDescriptorBridgeGateIds",
                "missingEvidence",
                "evidenceRefCount",
                "descriptorEdgeRejectionClassification",
                "rootStopToFillBridgeFound",
                "fillStopToCurrentBridgeFound",
                "descriptorBridgeProofFound",
            ],
        },
        {
            "path": "out/runtime_predecessor_coordinate_source_scan.json",
            "fields": [
                "classification",
                "coordinateSourceRejectionClassification",
                "publicSaveStartPointerTableTileHitCount",
                "publicSaveStartStaticBaseHitCount",
                "publicSaveStartTrailRingHitCount",
                "publicSaveStartImageHitCount",
                "reciprocalPointerTableTileHitCount",
                "reciprocalStaticBaseHitCount",
                "reciprocalTrailRingHitCount",
                "reciprocalImageHitCount",
            ],
        },
        {
            "path": "out/runtime_predecessor_field_entry_sequence_scan.json",
            "fields": [
                "sequenceCount",
                "snapshotCount",
                "snapshotRouteCandidateCount",
                "snapshotSelectorCounts",
                "classificationCounts",
                "proofFound",
                "predecessorFieldEntryProofFound",
                "failedPredecessorFieldEntryGateIds",
                "missingEvidence",
                "evidenceRefs",
                "evidenceRefCount",
                "promotionStatus",
            ],
        },
        {
            "path": "out/save_selector_branch_gate_consistency.json",
            "fields": [
                "knownOpcodeStatePreservationStatus",
                "sameTableAndOffset",
                "sameSelectionBufferOffsetHex",
                "postWriterSameOffsetWriteCount",
                "postWriterSameOffsetReadCount",
                "postWriterOtherOffsetWriteCount",
                "invalidSecondaryFillOffsetsHex",
            ],
        },
    ]
    evidence_rows = [
        {
            "kind": "local-fill-fragment",
            "status": "local-fragment-only"
            if fill_execution_order_gap.get("localFillTraceContainsAllFillSites") is True
            else "fill-fragment-missing",
            "detail": (
                f"start={fill_execution_order_gap.get('localFillTraceStartHex')}; "
                f"fills={csv(fill_execution_order_gap.get('fillSites') or [])}; "
                f"stop={fill_execution_order_gap.get('localFillTraceStopHex')} "
                f"reason={fill_execution_order_gap.get('localFillTraceStopReason')}; "
                f"reachesReader={fill_execution_order_gap.get('localFillTraceReachesCurrentReader')}"
            ),
        },
        {
            "kind": "root-entry-to-fill",
            "status": "fill-sites-not-reached" if not root_entry_reaches_fill else "fill-sites-reached",
            "detail": (
                f"root={fill_execution_order_gap.get('predecessorRootHex')}; "
                f"rootEntryReachable={root_entry_reaches_fill}; "
                f"directFillRefs={fill_execution_order_gap.get('directFillSiteRefCounts')}"
            ),
        },
        {
            "kind": "encoded-fill-entry-candidates",
            "status": encoded_fill_entry.get("classification") or "not-available",
            "detail": (
                f"range={encoded_fill_entry.get('scanRangeHex')}; "
                f"rawScalars={encoded_fill_entry.get('rawScalarCandidateCount')}; "
                f"rootTailRawScalars={encoded_fill_entry.get('rootTailRawScalarCandidateCount')}; "
                f"branchAttached={encoded_fill_entry.get('branchAttachedEncodedFieldCount')}; "
                f"modeledControlFlow={encoded_fill_entry.get('modeledControlFlowCandidateCount')}; "
                f"promoting={encoded_fill_entry.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"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_immediate_predecessor.get('handlerSection')}/"
                f"{root_tail_immediate_predecessor.get('handlerVaHex')}"
            ),
        },
        {
            "kind": "descriptor-boundary-bridge",
            "status": "no-execution-bridge" if not descriptor_bridge_proof else "bridge-found",
            "detail": (
                f"rootStopBridge={descriptor_bridge_gap.get('rootStopToFillBridgeFound')}; "
                f"fillStopBridge={descriptor_bridge_gap.get('fillStopToCurrentBridgeFound')}; "
                f"rootClosureNodes={descriptor_root_closure.get('visitedNodeCount')}; "
                f"fillClosureNodes={descriptor_fill_closure.get('visitedNodeCount')}; "
                f"edgeReject={descriptor_edge_rejection.get('classification')}"
            ),
        },
        {
            "kind": "descriptor-edge-rejection",
            "status": descriptor_edge_rejection.get("classification") or "not-available",
            "detail": (
                "descriptorEdges="
                f"{descriptor_edge_rejection.get('rootDescriptorTargetEdgeCount')}/"
                f"{descriptor_edge_rejection.get('fillDescriptorTargetEdgeCount')}; "
                "routeEdges="
                f"{descriptor_edge_rejection.get('rootRouteExecutionTargetEdgeCount')}/"
                f"{descriptor_edge_rejection.get('fillRouteExecutionTargetEdgeCount')}; "
                f"allTargetSectionsData={descriptor_edge_rejection.get('allTargetSectionsData')}; "
                f"rootLabels={descriptor_edge_rejection.get('rootDescriptorOnlyTargetLabels')}; "
                f"fillLabels={descriptor_edge_rejection.get('fillDescriptorOnlyTargetLabels')}"
            ),
        },
        {
            "kind": "descriptor-encoded-target-scan",
            "status": descriptor_encoded_target_scan.get("classification") or "not-available",
            "detail": (
                f"raw={descriptor_encoded_target_scan.get('rawScalarCandidateCount')}; "
                f"root/fill={descriptor_encoded_target_scan.get('rootRawScalarCandidateCount')}/"
                f"{descriptor_encoded_target_scan.get('fillRawScalarCandidateCount')}; "
                f"promoting={descriptor_encoded_target_scan.get('promotingCandidateCount')}; "
                f"targets={descriptor_encoded_target_scan.get('targetLabelCounts')}; "
                f"kinds={descriptor_encoded_target_scan.get('kindCounts')}"
            ),
        },
        {
            "kind": "dispatch-slice-runtime-proof",
            "status": (
                "slice-runtime-proof-missing"
                if fill_execution_order_gap.get("predecessorDispatchSliceRuntimeProofFound") is False
                and fill_execution_order_gap.get("predecessorDescriptorDependsOnSaveSelectorSliceModel") is True
                else "review-required"
            ),
            "detail": (
                f"sliceRuntimeProof={fill_execution_order_gap.get('predecessorDispatchSliceRuntimeProofFound')}; "
                f"dispatchTableProof={fill_execution_order_gap.get('predecessorDispatchTableProofFound')}; "
                "dispatchFailedGates="
                f"{csv(fill_execution_order_gap.get('predecessorDispatchTableFailedGateIds'))}; "
                "dispatchMissingEvidenceCount="
                f"{len(fill_execution_order_gap.get('predecessorDispatchTableMissingEvidence') or [])}; "
                f"dispatchEvidenceRefs={fill_execution_order_gap.get('predecessorDispatchTableEvidenceRefCount')}; "
                f"descriptorDependsOnSlice={fill_execution_order_gap.get('predecessorDescriptorDependsOnSaveSelectorSliceModel')}; "
                f"rows={fill_execution_order_gap.get('predecessorDispatchSliceRowCount')}; "
                f"sliceData={fill_execution_order_gap.get('predecessorDispatchSliceDataDescriptorCount')}; "
                f"rawCode={fill_execution_order_gap.get('predecessorDispatchRawGeneralCodeCount')}; "
                f"rawDiffers={fill_execution_order_gap.get('predecessorDispatchRawGeneralDiffersFromSliceCount')}; "
                f"byteReachable={fill_execution_order_gap.get('predecessorDispatchSliceGenericByteReachableCount')}; "
                f"requiresTableBase={fill_execution_order_gap.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')}; "
                f"dynamicDispatches={fill_execution_order_gap.get('predecessorDispatchDynamicIndexedDispatchRowCount')}/"
                f"{fill_execution_order_gap.get('predecessorDispatchDynamicScopeTableCallbackCount')}/"
                f"{fill_execution_order_gap.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')}; "
                "scopeSites="
                f"{csv(fill_execution_order_gap.get('predecessorDispatchDynamicScopeTableCallbackSites'))}; "
                f"dynamicTableBaseCandidate="
                f"{fill_execution_order_gap.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}; "
                f"tableBaseArithmetic={fill_execution_order_gap.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')}/"
                f"{fill_execution_order_gap.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')}; "
                f"tableBaseReject={dispatch_table_base_rejection.get('classification')}; "
                f"tableBaseCandidates={dispatch_table_base_rejection.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')}; "
                "tableBaseCandidateSites="
                f"{csv(dispatch_table_base_rejection.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites'))}"
            ),
        },
        {
            "kind": "dispatch-table-base-rejection",
            "status": dispatch_table_base_rejection.get("classification") or "not-available",
            "detail": (
                "requiresTableBase="
                f"{dispatch_table_base_rejection.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')}; "
                "byteReachable="
                f"{dispatch_table_base_rejection.get('predecessorDispatchSliceGenericByteReachableCount')}; "
                "dynamicDispatches="
                f"{dispatch_table_base_rejection.get('predecessorDispatchDynamicIndexedDispatchRowCount')}/"
                f"{dispatch_table_base_rejection.get('predecessorDispatchDynamicScopeTableCallbackCount')}/"
                f"{dispatch_table_base_rejection.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')}; "
                "dwordScaled="
                f"{dispatch_table_base_rejection.get('predecessorDispatchDynamicDwordScaledDispatchRowCount')}; "
                "tableBaseCandidates="
                f"{dispatch_table_base_rejection.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount')}; "
                "scopeSites="
                f"{csv(dispatch_table_base_rejection.get('predecessorDispatchDynamicScopeTableCallbackSites'))}; "
                "tableBaseCandidateSites="
                f"{csv(dispatch_table_base_rejection.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites'))}; "
                "tableBaseStaticCandidate="
                f"{dispatch_table_base_rejection.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')}"
            ),
        },
        {
            "kind": "raw-generic-callgraph-contrast",
            "status": raw_generic_call_graph.get("classification") or "not-available",
            "detail": (
                f"depth={raw_generic_call_graph.get('maxDepth')}; "
                f"functions={raw_generic_call_graph.get('reachableFunctionCount')}; "
                f"edges={raw_generic_call_graph.get('directCallEdgeCount')}; "
                "route/fill/currentImm="
                f"{raw_generic_call_graph.get('routeImmediateHitCount')}/"
                f"{raw_generic_call_graph.get('fillImmediateHitCount')}/"
                f"{raw_generic_call_graph.get('currentImmediateHitCount')}; "
                "selected/branchImm="
                f"{raw_generic_call_graph.get('selectedPointerImmediateHitCount')}/"
                f"{raw_generic_call_graph.get('branchStateImmediateHitCount')}; "
                "route/fillTransfers="
                f"{raw_generic_call_graph.get('routeDirectTransferHitCount')}/"
                f"{raw_generic_call_graph.get('fillDirectTransferHitCount')}; "
                f"proof={raw_generic_call_graph.get('proofFound')}; "
                "depthSensitivity="
                f"{raw_generic_call_graph_depth.get('maxDepthChecked')}/"
                f"{raw_generic_call_graph_depth.get('proofAbsentAcrossCheckedDepths')}/"
                f"{raw_generic_call_graph_depth.get('countsStableAtAndBeyondDefaultDepth')}"
            ),
        },
        {
            "kind": "runtime-branch-state-polls",
            "status": "public-predecessor-fill-not-observed"
            if branch_state_public_hit_count and not branch_state_fill_match_count
            else "not-classified",
            "detail": (
                f"polls={len(available_branch_rows)}; seq={branch_state_sequence_count}; "
                f"samples={branch_state_sample_count}; publicHits={branch_state_public_hit_count}; "
                f"routeHits={branch_state_route_hit_count}; currentRootHits={branch_state_current_root_hit_count}; "
                f"fillMatches={branch_state_fill_match_count}; allZero={branch_state_all_zero_count}"
            ),
        },
        {
            "kind": "runtime-target-observation",
            "status": branch_state_target_observation_status,
            "detail": (
                f"movementOrTargetPolls={len(branch_state_movement_or_target_rows)}; "
                f"movementOrTargetSamples={sum_samples(branch_state_movement_or_target_rows)}; "
                f"targetPolls={len(branch_state_target_observation_rows)}; "
                f"targetSamples={sum_samples(branch_state_target_observation_rows)}; "
                f"cameraOnly={len(branch_state_camera_only_target_rows)}; "
                f"actorOrTrailTarget={len(branch_state_actor_or_trail_target_rows)}; "
                "targetFillMatches="
                f"{sum(1 for row in branch_state_target_observation_rows if row['matchesPredecessorFillHypothesis'])}; "
                f"targetAllZero={sum(1 for row in branch_state_target_observation_rows if row['secondaryBranchStateAllZero'])}; "
                f"targetRouteHits={sum(1 for row in branch_state_target_observation_rows if row['routeSelectorReached'])}; "
                f"targetCurrentHits={sum(1 for row in branch_state_target_observation_rows if row['currentRootReached'])}"
            ),
        },
        {
            "kind": "runtime-field-entry-input",
            "status": "field-entry-not-found"
            if field_entry_context.get("fieldEntryCandidateCount") == 0
            else "field-entry-candidate-found",
            "detail": (
                f"coordinateClass={coordinate_context.get('classification')}; "
                f"finalSelector={coordinate_context.get('finalSelector')}; "
                f"sequenceCount={field_entry_context.get('sequenceCount')}; "
                f"fieldEntryCandidates={field_entry_context.get('fieldEntryCandidateCount')}; "
                f"finalSelectors={field_entry_context.get('finalSelectorCounts')}; "
                f"finalCameras={field_entry_context.get('finalCameraTileCounts')}; "
                f"snapshots={field_entry_context.get('snapshotCount')}; "
                f"snapshotRouteCandidates={field_entry_context.get('snapshotRouteCandidateCount')}; "
                f"snapshotSelectors={field_entry_context.get('snapshotSelectorCounts')}; "
                f"snapshotCameras={field_entry_context.get('snapshotCameraTileCounts')}; "
                f"classes={field_entry_context.get('classificationCounts')}; "
                f"proofFound={field_entry_context.get('proofFound')}; "
                f"candidateProof={field_entry_context.get('predecessorFieldEntryProofFound')}; "
                f"failedGates={csv(field_entry_context.get('failedPredecessorFieldEntryGateIds'))}; "
                f"evidenceRefs={field_entry_context.get('evidenceRefCount')}; "
                f"trailLeftOverrunCameraTarget="
                f"{next((row.get('trailLeftOverrunCameraTargetObserved') for row in branch_state_poll_rows if row['name'] == 'trail-left-overrun'), None)}"
            ),
        },
        {
            "kind": "state-preservation-vs-execution",
            "status": "preservation-narrowed-execution-unproven",
            "detail": (
                f"staticNoLocalTailReset={fill_execution_order_gap.get('staticNoLocalTailReset')}; "
                f"staticResetScopeClosed={fill_execution_order_gap.get('staticResetScopeClosed')}; "
                f"selectorOrderResetGapClosed={fill_execution_order_gap.get('selectorOrderResetGapClosed')}; "
                "branchGatePreserve="
                f"{branch_gate_consistency.get('knownOpcodeStatePreservationStatus')}; "
                "branchGateSameOffset="
                f"{branch_gate_consistency.get('sameTableAndOffset')}/"
                f"{branch_gate_consistency.get('sameSelectionBufferOffsetHex')}; "
                "branchGateSameOffsetWriteRead="
                f"{branch_gate_consistency.get('postWriterSameOffsetWriteCount')}/"
                f"{branch_gate_consistency.get('postWriterSameOffsetReadCount')}; "
                "branchGateOtherWrites="
                f"{branch_gate_consistency.get('postWriterOtherOffsetWriteCount')}@"
                f"{csv(branch_gate_other_write_offsets)}; "
                "branchGateInvalidFillOffsets="
                f"{csv(branch_gate_invalid_fill_offsets)}; "
                f"routeOrder={route_order_proven}; mergeClosed={selector_merge_closed}"
            ),
        },
    ]
    conclusion = (
        "The predecessor 1:0 fill fragment is a real local fragment, but it is still not proven to execute "
        "on the normal path before the current 0x00542b0c reader. Root-entry fixed traversal does not reach "
        "0x004844d0/0x004844d8, descriptor-boundary closure does not bridge into the fill/current path, and "
        f"{len(available_branch_rows)} branch-state runtime poll families reach the public predecessor without "
        "observing the expected secondaryBranchState fill."
    )
    return {
        "source": source,
        "target": target,
        "predecessorSelector": fill_execution_order_gap.get("predecessorSelector"),
        "predecessorRootHex": fill_execution_order_gap.get("predecessorRootHex"),
        "currentSelector": fill_execution_order_gap.get("currentSelector"),
        "currentRootHex": fill_execution_order_gap.get("currentRootHex"),
        "currentReaderHex": fill_execution_order_gap.get("currentReaderHex"),
        "fillSites": fill_execution_order_gap.get("fillSites") or [],
        "expectedBranchStateHexes": (branch_state_execution_gap.get("runtimeBranchStateSplit") or {}).get(
            "expectedFillHexes"
        )
        or [],
        "selectorProgressPolls": selector_poll_rows,
        "selectorProgressSampleCount": selector_progress_sample_count,
        "branchStatePolls": branch_state_poll_rows,
        "branchStatePollCount": len(available_branch_rows),
        "branchStatePollSequenceCount": branch_state_sequence_count,
        "branchStatePollSampleCount": branch_state_sample_count,
        "branchStatePollPublicPredecessorHitCount": branch_state_public_hit_count,
        "branchStatePollCurrentRootHitCount": branch_state_current_root_hit_count,
        "branchStatePollRouteSelectorHitCount": branch_state_route_hit_count,
        "branchStatePollAllZeroCount": branch_state_all_zero_count,
        "branchStatePollFillMatchCount": branch_state_fill_match_count,
        "branchStatePollMovementOrTargetCount": len(branch_state_movement_or_target_rows),
        "branchStatePollMovementOrTargetSampleCount": sum_samples(branch_state_movement_or_target_rows),
        "branchStatePollMovementOrTargetFillMatchCount": sum(
            1 for row in branch_state_movement_or_target_rows if row["matchesPredecessorFillHypothesis"]
        ),
        "branchStatePollMovementOrTargetAllZeroCount": sum(
            1 for row in branch_state_movement_or_target_rows if row["secondaryBranchStateAllZero"]
        ),
        "branchStatePollTargetObservationCount": len(branch_state_target_observation_rows),
        "branchStatePollTargetObservationSampleCount": sum_samples(branch_state_target_observation_rows),
        "branchStatePollTargetObservationFillMatchCount": sum(
            1 for row in branch_state_target_observation_rows if row["matchesPredecessorFillHypothesis"]
        ),
        "branchStatePollTargetObservationAllZeroCount": sum(
            1 for row in branch_state_target_observation_rows if row["secondaryBranchStateAllZero"]
        ),
        "branchStatePollTargetObservationRouteSelectorHitCount": sum(
            1 for row in branch_state_target_observation_rows if row["routeSelectorReached"]
        ),
        "branchStatePollTargetObservationCurrentRootHitCount": sum(
            1 for row in branch_state_target_observation_rows if row["currentRootReached"]
        ),
        "branchStatePollCameraOnlyTargetCount": len(branch_state_camera_only_target_rows),
        "branchStatePollActorOrTrailTargetCount": len(branch_state_actor_or_trail_target_rows),
        "branchStatePollTargetObservationStatus": branch_state_target_observation_status,
        "localFillTraceStartHex": fill_execution_order_gap.get("localFillTraceStartHex"),
        "localFillTraceStopHex": fill_execution_order_gap.get("localFillTraceStopHex"),
        "localFillTraceStopReason": fill_execution_order_gap.get("localFillTraceStopReason"),
        "localFillTraceStopHandlerHex": fill_execution_order_gap.get("localFillTraceStopHandlerHex"),
        "localFillTraceContainsAllFillSites": fill_execution_order_gap.get(
            "localFillTraceContainsAllFillSites"
        ),
        "localFillTraceReachesCurrentReader": fill_execution_order_gap.get(
            "localFillTraceReachesCurrentReader"
        ),
        "rootEntryFixedTraversalVisitedNodeCount": root_entry_traversal.get("visitedNodeCount"),
        "rootEntryFixedTraversalStopRows": root_entry_stop_rows,
        "rootEntryFixedTraversalFillSitesReachable": fill_execution_order_gap.get(
            "rootEntryFixedTraversalFillSitesReachable"
        ),
        "directFillSiteRefCounts": fill_execution_order_gap.get("directFillSiteRefCounts") or {},
        "encodedFillEntryCandidateScan": encoded_fill_entry,
        "encodedFillEntryRawScalarCandidateCount": encoded_fill_entry.get("rawScalarCandidateCount"),
        "encodedFillEntryRootTailRawScalarCandidateCount": encoded_fill_entry.get(
            "rootTailRawScalarCandidateCount"
        ),
        "encodedFillEntryBranchAttachedEncodedFieldCount": encoded_fill_entry.get(
            "branchAttachedEncodedFieldCount"
        ),
        "encodedFillEntryModeledControlFlowCandidateCount": encoded_fill_entry.get(
            "modeledControlFlowCandidateCount"
        ),
        "encodedFillEntryPromotingCandidateCount": encoded_fill_entry.get("promotingCandidateCount"),
        "encodedFillEntryClassification": encoded_fill_entry.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": fill_execution_order_gap.get("rootTailDescriptorIsolated"),
        "rootTailDistanceHex": root_tail_isolation.get("distanceHex"),
        "rootTailDwordCount": root_tail_isolation.get("dwordCount"),
        "rootTailTextHandlerRowCount": root_tail_isolation.get("textHandlerRowCount"),
        "rootTailDataHandlerRowCount": root_tail_isolation.get("dataHandlerRowCount"),
        "rootTailOtherHandlerRowCount": root_tail_isolation.get("otherHandlerRowCount"),
        "rootTailBranchCapableRowCount": root_tail_isolation.get("branchCapableRowCount"),
        "rootTailBranchTargetClassCounts": root_tail_isolation.get("branchTargetClassCounts"),
        "rootTailBranchTargetSectionCounts": root_tail_isolation.get("branchTargetSectionCounts"),
        "rootTailBranchToFillFragmentCount": fill_execution_order_gap.get(
            "rootTailBranchToFillFragmentCount"
        ),
        "rootTailBranchToCurrentReaderCount": fill_execution_order_gap.get(
            "rootTailBranchToCurrentReaderCount"
        ),
        "rootTailFixedFallthroughToFillCount": fill_execution_order_gap.get(
            "rootTailFixedFallthroughToFillCount"
        ),
        "rootTailBranchClosureClassification": fill_execution_order_gap.get(
            "rootTailBranchClosureClassification"
        ),
        "rootTailBranchClosureNodeCount": fill_execution_order_gap.get(
            "rootTailBranchClosureNodeCount"
        ),
        "rootTailBranchClosureBranchSeedCount": fill_execution_order_gap.get(
            "rootTailBranchClosureBranchSeedCount"
        ),
        "rootTailBranchClosureEdgeCount": fill_execution_order_gap.get(
            "rootTailBranchClosureEdgeCount"
        ),
        "rootTailBranchClosureTailNodeReachFillCount": fill_execution_order_gap.get(
            "rootTailBranchClosureTailNodeReachFillCount"
        ),
        "rootTailBranchClosureTailNodeReachCurrentReaderCount": fill_execution_order_gap.get(
            "rootTailBranchClosureTailNodeReachCurrentReaderCount"
        ),
        "rootTailBranchClosureBranchSeedReachFillCount": fill_execution_order_gap.get(
            "rootTailBranchClosureBranchSeedReachFillCount"
        ),
        "rootTailBranchClosureBranchSeedReachCurrentReaderCount": fill_execution_order_gap.get(
            "rootTailBranchClosureBranchSeedReachCurrentReaderCount"
        ),
        "rootTailBranchClosureProofFound": fill_execution_order_gap.get(
            "rootTailBranchClosureProofFound"
        ),
        "rootTailBranchClosureOutsideSuccessorCount": fill_execution_order_gap.get(
            "rootTailBranchClosureOutsideSuccessorCount"
        ),
        "rootTailBranchClosureOutsideSuccessorClassCounts": fill_execution_order_gap.get(
            "rootTailBranchClosureOutsideSuccessorClassCounts"
        ),
        "rootTailBranchClosureOutsideSuccessorSectionCounts": fill_execution_order_gap.get(
            "rootTailBranchClosureOutsideSuccessorSectionCounts"
        ),
        "rootTailBranchClosureOutsideSuccessorSampleRows": fill_execution_order_gap.get(
            "rootTailBranchClosureOutsideSuccessorSampleRows"
        ),
        "rootTailImmediatePredecessorHandlerSection": root_tail_immediate_predecessor.get(
            "handlerSection"
        ),
        "rootTailImmediatePredecessorHandlerHex": root_tail_immediate_predecessor.get(
            "handlerVaHex"
        ),
        "rootStopToFillBridgeFound": descriptor_bridge_gap.get("rootStopToFillBridgeFound"),
        "fillStopToCurrentBridgeFound": descriptor_bridge_gap.get("fillStopToCurrentBridgeFound"),
        "descriptorBridgeProofFound": descriptor_bridge_proof,
        "descriptorBridgeFailedGateIds": descriptor_bridge_gap.get(
            "failedDescriptorBridgeGateIds"
        )
        or [],
        "descriptorBridgeMissingEvidence": descriptor_bridge_gap.get("missingEvidence") or [],
        "descriptorBridgeEvidenceRefCount": descriptor_bridge_gap.get("evidenceRefCount"),
        "descriptorEdgeRejection": descriptor_edge_rejection,
        "descriptorEdgeRejectionClassification": descriptor_edge_rejection.get("classification"),
        "descriptorEdgeAllTargetSectionsData": descriptor_edge_rejection.get(
            "allTargetSectionsData"
        ),
        "descriptorEdgeDescriptorTargetEdgeCount": descriptor_edge_rejection.get(
            "descriptorTargetEdgeCount"
        ),
        "descriptorEdgeRouteExecutionTargetEdgeCount": descriptor_edge_rejection.get(
            "routeExecutionTargetEdgeCount"
        ),
        "descriptorEdgeRootDescriptorTargetEdgeCount": descriptor_edge_rejection.get(
            "rootDescriptorTargetEdgeCount"
        ),
        "descriptorEdgeFillDescriptorTargetEdgeCount": descriptor_edge_rejection.get(
            "fillDescriptorTargetEdgeCount"
        ),
        "descriptorEdgeRootRouteExecutionTargetEdgeCount": descriptor_edge_rejection.get(
            "rootRouteExecutionTargetEdgeCount"
        ),
        "descriptorEdgeFillRouteExecutionTargetEdgeCount": descriptor_edge_rejection.get(
            "fillRouteExecutionTargetEdgeCount"
        ),
        "descriptorEdgeRootDescriptorOnlyTargetLabels": descriptor_edge_rejection.get(
            "rootDescriptorOnlyTargetLabels"
        )
        or [],
        "descriptorEdgeFillDescriptorOnlyTargetLabels": descriptor_edge_rejection.get(
            "fillDescriptorOnlyTargetLabels"
        )
        or [],
        "descriptorEncodedTargetScan": descriptor_encoded_target_scan,
        "descriptorEncodedTargetClassification": descriptor_encoded_target_scan.get(
            "classification"
        ),
        "descriptorEncodedTargetRawScalarCandidateCount": descriptor_encoded_target_scan.get(
            "rawScalarCandidateCount"
        ),
        "descriptorEncodedTargetRootRawScalarCandidateCount": descriptor_encoded_target_scan.get(
            "rootRawScalarCandidateCount"
        ),
        "descriptorEncodedTargetFillRawScalarCandidateCount": descriptor_encoded_target_scan.get(
            "fillRawScalarCandidateCount"
        ),
        "descriptorEncodedTargetPromotingCandidateCount": descriptor_encoded_target_scan.get(
            "promotingCandidateCount"
        ),
        "descriptorEncodedTargetLabelCounts": descriptor_encoded_target_scan.get("targetLabelCounts")
        or {},
        "descriptorEncodedTargetKindCounts": descriptor_encoded_target_scan.get("kindCounts")
        or {},
        "predecessorDispatchSliceRuntimeProofFound": fill_execution_order_gap.get(
            "predecessorDispatchSliceRuntimeProofFound"
        ),
        "predecessorDispatchTableProofFound": fill_execution_order_gap.get(
            "predecessorDispatchTableProofFound"
        ),
        "predecessorDispatchTableFailedGateIds": fill_execution_order_gap.get(
            "predecessorDispatchTableFailedGateIds"
        )
        or [],
        "predecessorDispatchTableMissingEvidence": fill_execution_order_gap.get(
            "predecessorDispatchTableMissingEvidence"
        )
        or [],
        "predecessorDispatchTableEvidenceRefCount": fill_execution_order_gap.get(
            "predecessorDispatchTableEvidenceRefCount"
        ),
        "predecessorDescriptorDependsOnSaveSelectorSliceModel": fill_execution_order_gap.get(
            "predecessorDescriptorDependsOnSaveSelectorSliceModel"
        ),
        "predecessorDispatchSliceRowCount": fill_execution_order_gap.get(
            "predecessorDispatchSliceRowCount"
        ),
        "predecessorDispatchSliceDataDescriptorCount": fill_execution_order_gap.get(
            "predecessorDispatchSliceDataDescriptorCount"
        ),
        "predecessorDispatchRawGeneralCodeCount": fill_execution_order_gap.get(
            "predecessorDispatchRawGeneralCodeCount"
        ),
        "predecessorDispatchRawGeneralDiffersFromSliceCount": fill_execution_order_gap.get(
            "predecessorDispatchRawGeneralDiffersFromSliceCount"
        ),
        "predecessorDispatchSliceGenericByteReachableCount": fill_execution_order_gap.get(
            "predecessorDispatchSliceGenericByteReachableCount"
        ),
        "predecessorDispatchSliceRequiresTableBaseSwitchCount": fill_execution_order_gap.get(
            "predecessorDispatchSliceRequiresTableBaseSwitchCount"
        ),
        "predecessorDispatchDynamicIndexedDispatchRowCount": fill_execution_order_gap.get(
            "predecessorDispatchDynamicIndexedDispatchRowCount"
        ),
        "predecessorDispatchDynamicDwordScaledDispatchRowCount": fill_execution_order_gap.get(
            "predecessorDispatchDynamicDwordScaledDispatchRowCount"
        ),
        "predecessorDispatchDynamicScopeTableCallbackCount": fill_execution_order_gap.get(
            "predecessorDispatchDynamicScopeTableCallbackCount"
        ),
        "predecessorDispatchDynamicScopeTableCallbackSites": fill_execution_order_gap.get(
            "predecessorDispatchDynamicScopeTableCallbackSites"
        ) or [],
        "predecessorDispatchDynamicScopeTableCallbackRows": fill_execution_order_gap.get(
            "predecessorDispatchDynamicScopeTableCallbackRows"
        ) or [],
        "predecessorDispatchDynamicSaveSelectorTableImmediateNearCount": fill_execution_order_gap.get(
            "predecessorDispatchDynamicSaveSelectorTableImmediateNearCount"
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount": (
            fill_execution_order_gap.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseCandidateCount"
            )
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites": (
            fill_execution_order_gap.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites"
            )
            or []
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseCandidateRows": (
            fill_execution_order_gap.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseCandidateRows"
            )
            or []
        ),
        "predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound": (
            fill_execution_order_gap.get(
                "predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticRowCount": (
            fill_execution_order_gap.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticRowCount"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount": (
            fill_execution_order_gap.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateFound": (
            fill_execution_order_gap.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateFound"
            )
        ),
        "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateRows": (
            fill_execution_order_gap.get(
                "predecessorDispatchSaveSelectorTableBaseArithmeticCandidateRows"
            )
            or []
        ),
        "predecessorDispatchTableBaseRejection": dispatch_table_base_rejection,
        "predecessorDispatchTableBaseRejectionClassification": (
            dispatch_table_base_rejection.get("classification")
        ),
        "predecessorDispatchTableBaseAuditRowCount": len(dispatch_table_base_audit_rows),
        "rawGenericCallGraphContrast": raw_generic_call_graph,
        "rawGenericCallGraphDepthSensitivity": raw_generic_call_graph_depth,
        "rawGenericCallGraphClassification": raw_generic_call_graph.get("classification"),
        "rawGenericCallGraphProofFound": raw_generic_call_graph.get("proofFound"),
        "rawGenericCallGraphMaxDepth": raw_generic_call_graph.get("maxDepth"),
        "rawGenericCallGraphReachableFunctionCount": raw_generic_call_graph.get(
            "reachableFunctionCount"
        ),
        "rawGenericCallGraphDirectCallEdgeCount": raw_generic_call_graph.get(
            "directCallEdgeCount"
        ),
        "rawGenericCallGraphRouteImmediateHitCount": raw_generic_call_graph.get(
            "routeImmediateHitCount"
        ),
        "rawGenericCallGraphFillImmediateHitCount": raw_generic_call_graph.get(
            "fillImmediateHitCount"
        ),
        "rawGenericCallGraphCurrentImmediateHitCount": raw_generic_call_graph.get(
            "currentImmediateHitCount"
        ),
        "rawGenericCallGraphSelectedPointerImmediateHitCount": raw_generic_call_graph.get(
            "selectedPointerImmediateHitCount"
        ),
        "rawGenericCallGraphBranchStateImmediateHitCount": raw_generic_call_graph.get(
            "branchStateImmediateHitCount"
        ),
        "rawGenericCallGraphRouteDirectTransferHitCount": raw_generic_call_graph.get(
            "routeDirectTransferHitCount"
        ),
        "rawGenericCallGraphFillDirectTransferHitCount": raw_generic_call_graph.get(
            "fillDirectTransferHitCount"
        ),
        "rawGenericCallGraphDepthSensitivityMaxDepthChecked": raw_generic_call_graph_depth.get(
            "maxDepthChecked"
        ),
        "rawGenericCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
            raw_generic_call_graph_depth.get("proofAbsentAcrossCheckedDepths")
        ),
        "rawGenericCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth": (
            raw_generic_call_graph_depth.get("countsStableAtAndBeyondDefaultDepth")
        ),
        "descriptorRootClosureVisitedNodeCount": descriptor_root_closure.get("visitedNodeCount"),
        "descriptorRootClosureEdgeCount": descriptor_root_closure.get("edgeCount"),
        "descriptorRootClosureFillSiteEdgeHitCount": descriptor_root_fill_site_edge_hit_count,
        "descriptorRootClosureCurrentReaderEdgeHitCount": descriptor_root_edge_hits.get(
            "current-reader"
        ),
        "descriptorFillClosureVisitedNodeCount": descriptor_fill_closure.get("visitedNodeCount"),
        "descriptorFillClosureEdgeCount": descriptor_fill_closure.get("edgeCount"),
        "descriptorFillClosureFillSiteEdgeHitCount": descriptor_fill_fill_site_edge_hit_count,
        "descriptorFillClosureCurrentReaderEdgeHitCount": descriptor_fill_edge_hits.get(
            "current-reader"
        ),
        "runtimeFillObserved": runtime_fill_observed,
        "runtimeBranchStateAllZero": fill_execution_order_gap.get("runtimeBranchStateAllZero"),
        "coordinateSourceContext": coordinate_context,
        "fieldEntrySequenceContext": field_entry_context,
        "staticNoLocalTailReset": fill_execution_order_gap.get("staticNoLocalTailReset"),
        "staticResetScopeClosed": fill_execution_order_gap.get("staticResetScopeClosed"),
        "selectorOrderResetGapClosed": fill_execution_order_gap.get("selectorOrderResetGapClosed"),
        "branchGateSameTableAndOffset": branch_gate_consistency.get("sameTableAndOffset"),
        "branchGateSameSelectionBufferOffsetHex": branch_gate_consistency.get(
            "sameSelectionBufferOffsetHex"
        ),
        "branchGatePostWriterSameOffsetWriteCount": branch_gate_consistency.get(
            "postWriterSameOffsetWriteCount"
        ),
        "branchGatePostWriterSameOffsetReadCount": branch_gate_consistency.get(
            "postWriterSameOffsetReadCount"
        ),
        "branchGatePostWriterOtherOffsetWriteCount": branch_gate_consistency.get(
            "postWriterOtherOffsetWriteCount"
        ),
        "branchGatePostWriterOtherOffsetWriteOffsetsHex": branch_gate_other_write_offsets,
        "branchGateInvalidSecondaryFillOffsetsHex": branch_gate_invalid_fill_offsets,
        "branchGateKnownOpcodeStatePreservationStatus": branch_gate_consistency.get(
            "knownOpcodeStatePreservationStatus"
        ),
        "branchGateSlotPreservedByKnownOpcodes": branch_gate_consistency.get(
            "statePreservedByKnownOpcodes"
        ),
        "branchGateBranchStateValueStillRuntimeDependent": branch_gate_consistency.get(
            "branchStateValueStillRuntimeDependent"
        ),
        "routeOrderProven": route_order_proven,
        "selectorMergeGapOpen": fill_execution_order_gap.get("selectorMergeGapOpen"),
        "requiredProofGates": required_proof_gates,
        "requiredProofGateCount": len(required_proof_gates),
        "requiredProofGatePassCount": required_proof_gate_pass_count,
        "requiredProofGateFailCount": required_proof_gate_fail_count,
        "requiredProofGateStatusOrder": required_proof_gate_status_order,
        "requiredProofGateStatuses": required_proof_gate_statuses,
        "requiredProofGateFailIds": required_proof_gate_fail_ids,
        "requiredProofGateAllBlocked": (
            len(required_proof_gates) > 0 and required_proof_gate_pass_count == 0
        ),
        "proofFound": fill_site_execution_context_proven,
        "failedPredecessorFillGateIds": required_proof_gate_fail_ids,
        "missingEvidence": missing_evidence,
        "evidenceRefs": evidence_refs,
        "evidenceRefCount": len(evidence_refs),
        "fillSiteExecutionContextProven": fill_site_execution_context_proven,
        "promotionStatus": "ready-for-review" if fill_site_execution_context_proven else "blocked",
        "evidence": evidence_rows,
        "remainingProofs": [
            "capture execution at 0x004844d0/0x004844d8 on the public route before 0x00542b0c",
            "decode the non-linear root-entry path from 0x00478364 to the fill fragment",
            "replace public-predecessor all-zero branch-state polls with a fill-observed runtime trace",
            "prove predecessor-to-current route order and close selector merge",
        ],
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    lines = [
        "# Save Selector Predecessor Fill Site Execution Context",
        "",
        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: `{csv(summary.get('fillSites'))}`",
        f"- proof found: {summary.get('proofFound')}",
        f"- failed predecessor fill gates: `{csv(summary.get('failedPredecessorFillGateIds'))}`",
        f"- missing evidence count: {len(summary.get('missingEvidence') or [])}",
        f"- branch-state poll coverage: {summary['branchStatePollCount']} polls, {summary['branchStatePollSequenceCount']} sequences, {summary['branchStatePollSampleCount']} samples",
        f"- public predecessor poll hits: {summary['branchStatePollPublicPredecessorHitCount']}",
        f"- current/root route hits in branch-state polls: {summary['branchStatePollCurrentRootHitCount']} / {summary['branchStatePollRouteSelectorHitCount']}",
        f"- fill matches / all-zero polls: {summary['branchStatePollFillMatchCount']} / {summary['branchStatePollAllZeroCount']}",
        f"- movement-or-target poll coverage: {summary['branchStatePollMovementOrTargetCount']} polls, {summary['branchStatePollMovementOrTargetSampleCount']} samples",
        f"- target-observation polls: {summary['branchStatePollTargetObservationCount']} polls, {summary['branchStatePollTargetObservationSampleCount']} samples",
        f"- target-observation fill/current/route hits: {summary['branchStatePollTargetObservationFillMatchCount']} / {summary['branchStatePollTargetObservationCurrentRootHitCount']} / {summary['branchStatePollTargetObservationRouteSelectorHitCount']}",
        f"- target-observation camera-only / actor-or-trail: {summary['branchStatePollCameraOnlyTargetCount']} / {summary['branchStatePollActorOrTrailTargetCount']}",
        f"- target-observation status: `{summary['branchStatePollTargetObservationStatus']}`",
        f"- root-entry reaches fill sites: {summary['rootEntryFixedTraversalFillSitesReachable']}",
        f"- root-entry traversal visited/stops: {summary['rootEntryFixedTraversalVisitedNodeCount']} / {len(summary.get('rootEntryFixedTraversalStopRows') or [])}",
        f"- encoded fill-entry candidates: {summary['encodedFillEntryClassification']} raw {summary['encodedFillEntryRawScalarCandidateCount']} / root-tail {summary['encodedFillEntryRootTailRawScalarCandidateCount']} / promoting {summary['encodedFillEntryPromotingCandidateCount']}",
        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"- root-tail isolation: {summary['rootTailDistanceHex']} / {summary['rootTailDwordCount']} rows; descriptor isolated {summary['rootTailDescriptorIsolated']}",
        f"- root-tail branch/fallthrough to fill: {summary['rootTailBranchToFillFragmentCount']} / {summary['rootTailFixedFallthroughToFillCount']}",
        (
            "- root-tail branch closure outside successors: "
            f"{summary.get('rootTailBranchClosureOutsideSuccessorCount')} "
            f"classes `{summary.get('rootTailBranchClosureOutsideSuccessorClassCounts')}` "
            f"sections `{summary.get('rootTailBranchClosureOutsideSuccessorSectionCounts')}`"
        ),
        f"- descriptor bridge proof found: {summary['descriptorBridgeProofFound']}",
        (
            "- descriptor bridge failed gates: "
            f"`{csv(summary.get('descriptorBridgeFailedGateIds'))}`"
        ),
        (
            "- descriptor bridge missing evidence count / refs: "
            f"{len(summary.get('descriptorBridgeMissingEvidence') or [])} / "
            f"{summary.get('descriptorBridgeEvidenceRefCount')}"
        ),
        f"- descriptor edge rejection: `{summary.get('descriptorEdgeRejectionClassification')}`",
        (
            "- descriptor / route execution edge counts: "
            f"{summary.get('descriptorEdgeDescriptorTargetEdgeCount')} / "
            f"{summary.get('descriptorEdgeRouteExecutionTargetEdgeCount')} "
            f"(root/fill route {summary.get('descriptorEdgeRootRouteExecutionTargetEdgeCount')} / "
            f"{summary.get('descriptorEdgeFillRouteExecutionTargetEdgeCount')})"
        ),
        (
            "- descriptor encoded target raw/root/fill/promoting: "
            f"{summary.get('descriptorEncodedTargetRawScalarCandidateCount')} / "
            f"{summary.get('descriptorEncodedTargetRootRawScalarCandidateCount')} / "
            f"{summary.get('descriptorEncodedTargetFillRawScalarCandidateCount')} / "
            f"{summary.get('descriptorEncodedTargetPromotingCandidateCount')}"
        ),
        f"- descriptor encoded target classification: `{summary.get('descriptorEncodedTargetClassification')}`",
        (
            "- predecessor dispatch slice dependency: "
            f"sliceRuntimeProof={summary.get('predecessorDispatchSliceRuntimeProofFound')} "
            f"dispatchTableProof={summary.get('predecessorDispatchTableProofFound')} "
            f"dispatchFailedGates={csv(summary.get('predecessorDispatchTableFailedGateIds'))} "
            f"dispatchMissingEvidenceCount={len(summary.get('predecessorDispatchTableMissingEvidence') or [])} "
            f"dispatchEvidenceRefs={summary.get('predecessorDispatchTableEvidenceRefCount')} "
            f"descriptorDependsOnSlice={summary.get('predecessorDescriptorDependsOnSaveSelectorSliceModel')} "
            f"rows={summary.get('predecessorDispatchSliceRowCount')} "
            f"sliceData={summary.get('predecessorDispatchSliceDataDescriptorCount')} "
            f"rawDiffers={summary.get('predecessorDispatchRawGeneralDiffersFromSliceCount')} "
            f"byteReachable={summary.get('predecessorDispatchSliceGenericByteReachableCount')} "
            f"requiresTableBase={summary.get('predecessorDispatchSliceRequiresTableBaseSwitchCount')} "
            f"dynamicDispatches={summary.get('predecessorDispatchDynamicIndexedDispatchRowCount')}/"
            f"{summary.get('predecessorDispatchDynamicScopeTableCallbackCount')}/"
            f"{summary.get('predecessorDispatchDynamicSaveSelectorTableImmediateNearCount')} "
            f"dynamicScopeSites={csv(summary.get('predecessorDispatchDynamicScopeTableCallbackSites'))} "
            f"dynamicTableBaseCandidate="
            f"{summary.get('predecessorDispatchDynamicSaveSelectorTableBaseSwitchStaticCandidateFound')} "
            f"dynamicTableBaseCandidateSites={csv(summary.get('predecessorDispatchDynamicSaveSelectorTableBaseCandidateSites'))} "
            f"tableBaseArithmetic={summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')}/"
            f"{summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')} "
            f"tableBaseReject={summary.get('predecessorDispatchTableBaseRejectionClassification')}"
        ),
        (
            "- raw generic call graph: "
            f"{summary.get('rawGenericCallGraphClassification')} "
            f"depth={summary.get('rawGenericCallGraphMaxDepth')} "
            f"functions/edges={summary.get('rawGenericCallGraphReachableFunctionCount')}/"
            f"{summary.get('rawGenericCallGraphDirectCallEdgeCount')} "
            "route/fill/currentImm="
            f"{summary.get('rawGenericCallGraphRouteImmediateHitCount')}/"
            f"{summary.get('rawGenericCallGraphFillImmediateHitCount')}/"
            f"{summary.get('rawGenericCallGraphCurrentImmediateHitCount')} "
            "selected/branchImm="
            f"{summary.get('rawGenericCallGraphSelectedPointerImmediateHitCount')}/"
            f"{summary.get('rawGenericCallGraphBranchStateImmediateHitCount')} "
            "route/fillTransfers="
            f"{summary.get('rawGenericCallGraphRouteDirectTransferHitCount')}/"
            f"{summary.get('rawGenericCallGraphFillDirectTransferHitCount')} "
            "depthSensitivity="
            f"{summary.get('rawGenericCallGraphDepthSensitivityMaxDepthChecked')}/"
            f"{summary.get('rawGenericCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths')}/"
            f"{summary.get('rawGenericCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth')} "
            f"proof={summary.get('rawGenericCallGraphProofFound')}"
        ),
        f"- descriptor closure nodes root/fill: {summary['descriptorRootClosureVisitedNodeCount']} / {summary['descriptorFillClosureVisitedNodeCount']}",
        f"- field-entry sequence snapshots: {(summary.get('fieldEntrySequenceContext') or {}).get('snapshotCount')} snapshots; route candidates {(summary.get('fieldEntrySequenceContext') or {}).get('snapshotRouteCandidateCount')}",
        (
            "- field-entry proof: "
            f"{(summary.get('fieldEntrySequenceContext') or {}).get('proofFound')} / "
            f"{(summary.get('fieldEntrySequenceContext') or {}).get('predecessorFieldEntryProofFound')} "
            "failed="
            f"`{csv((summary.get('fieldEntrySequenceContext') or {}).get('failedPredecessorFieldEntryGateIds'))}` "
            f"evidenceRefs={(summary.get('fieldEntrySequenceContext') or {}).get('evidenceRefCount')}"
        ),
        f"- field-entry snapshot selectors: `{(summary.get('fieldEntrySequenceContext') or {}).get('snapshotSelectorCounts')}`",
        (
            "- coordinate source: "
            f"class={((summary.get('coordinateSourceContext') or {}).get('classification'))} "
            f"reject={((summary.get('coordinateSourceContext') or {}).get('coordinateSourceRejectionClassification'))} "
            "startPointer/static/trail/image="
            f"{((summary.get('coordinateSourceContext') or {}).get('publicSaveStartPointerTableTileHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('publicSaveStartStaticBaseHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('publicSaveStartTrailRingHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('publicSaveStartImageHitCount'))} "
            "trailPointer/static/trail/image="
            f"{((summary.get('coordinateSourceContext') or {}).get('observedTrailPointerTableTileHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('observedTrailStaticBaseHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('observedTrailTrailRingHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('observedTrailImageHitCount'))} "
            "reciprocalPointer/static/trail/image="
            f"{((summary.get('coordinateSourceContext') or {}).get('reciprocalPointerTableTileHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('reciprocalStaticBaseHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('reciprocalTrailRingHitCount'))}/"
            f"{((summary.get('coordinateSourceContext') or {}).get('reciprocalImageHitCount'))}"
        ),
        f"- branch gate preservation: `{summary.get('branchGateKnownOpcodeStatePreservationStatus')}`",
        (
            "- branch gate same-slot / same-offset write-read / other writes / invalid fills: "
            f"{summary.get('branchGateSameTableAndOffset')}/"
            f"{summary.get('branchGateSameSelectionBufferOffsetHex')}; "
            f"{summary.get('branchGatePostWriterSameOffsetWriteCount')}/"
            f"{summary.get('branchGatePostWriterSameOffsetReadCount')}; "
            f"{summary.get('branchGatePostWriterOtherOffsetWriteCount')}@"
            f"{csv(summary.get('branchGatePostWriterOtherOffsetWriteOffsetsHex'))}; "
            f"invalid {csv(summary.get('branchGateInvalidSecondaryFillOffsetsHex'))}"
        ),
        f"- required proof gates passed/failed: {summary['requiredProofGatePassCount']} / {summary['requiredProofGateFailCount']}",
        f"- required proof gates all blocked: {summary.get('requiredProofGateAllBlocked')}",
        f"- required proof gate failed ids: `{csv(summary.get('requiredProofGateFailIds'))}`",
        f"- evidence refs: {summary.get('evidenceRefCount')}",
        f"- runtime fill observed: {summary['runtimeFillObserved']}",
        f"- fill-site execution context proven: {summary['fillSiteExecutionContextProven']}",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        "## Missing Evidence",
        "",
        *[f"- {item}" for item in summary.get("missingEvidence") or []],
        "",
        "## Evidence",
        "",
        "| kind | status | detail |",
        "| --- | --- | --- |",
    ]
    for row in summary.get("evidence") or []:
        lines.append(f"| {row['kind']} | {row['status']} | {row['detail']} |")
    lines.extend([
        "",
        "## Required Proof Gates",
        "",
        "| gate | passed | status | detail |",
        "| --- | --- | --- | --- |",
    ])
    for row in summary.get("requiredProofGates") or []:
        lines.append(
            f"| {row['gate']} | {row.get('passed')} | {row.get('status')} | {row.get('detail')} |"
        )
    lines.extend([
        "",
        "## Source Evidence Refs",
        "",
        "| path | fields |",
        "| --- | --- |",
    ])
    for ref in summary.get("evidenceRefs") or []:
        lines.append(f"| {ref.get('path')} | `{csv(ref.get('fields'))}` |")
    lines.extend([
        "",
        "## Branch-State Polls",
        "",
        "| poll | samples | selectors | public | route | fill match | all zero | split |",
        "| --- | ---: | --- | --- | --- | --- | --- | --- |",
    ])
    for row in summary.get("branchStatePolls") or []:
        lines.append(
            f"| {row['name']} | {row.get('sampleCount')} | `{csv(row.get('observedSelectors'))}` | "
            f"{row.get('publicPredecessorReached')} | {row.get('routeSelectorReached')} | "
            f"{row.get('matchesPredecessorFillHypothesis')} | {row.get('secondaryBranchStateAllZero')} | "
            f"{row.get('splitClassification') or '-'} |"
        )
    lines.extend(["", "## Remaining Proofs", ""])
    lines.extend(f"- {item}" for item in summary.get("remainingProofs") or [])
    lines.append("")
    return "\n".join(lines)


def html_page(summary: dict) -> str:
    evidence_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['kind'])}</td>"
        f"<td>{html.escape(row['status'])}</td>"
        f"<td>{html.escape(row['detail'])}</td>"
        "</tr>"
        for row in summary.get("evidence") or []
    )
    poll_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['name'])}</td>"
        f"<td>{html.escape(str(row.get('sampleCount')))}</td>"
        f"<td><code>{html.escape(csv(row.get('observedSelectors')))}</code></td>"
        f"<td>{bool_text(row.get('publicPredecessorReached'))}</td>"
        f"<td>{bool_text(row.get('routeSelectorReached'))}</td>"
        f"<td>{bool_text(row.get('matchesPredecessorFillHypothesis'))}</td>"
        f"<td>{bool_text(row.get('secondaryBranchStateAllZero'))}</td>"
        f"<td>{html.escape(str(row.get('splitClassification') or '-'))}</td>"
        "</tr>"
        for row in summary.get("branchStatePolls") or []
    )
    proof_gate_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['gate'])}</td>"
        f"<td>{bool_text(row.get('passed'))}</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("requiredProofGates") or []
    )
    proof_items = "\n".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("remainingProofs") or []
    )
    missing_evidence_items = "\n".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or []
    )
    evidence_ref_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(ref.get('path')))}</code></td>"
        f"<td><code>{html.escape(csv(ref.get('fields')))}</code></td>"
        "</tr>"
        for ref in summary.get("evidenceRefs") or []
    )
    return "\n".join([
        "<!doctype html>",
        '<html lang="en">',
        "<head>",
        '  <meta charset="utf-8">',
        "  <title>Save Selector Predecessor Fill Site Execution Context</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 Site Execution Context</h1>",
        f"  <p>{html.escape(summary['conclusion'])}</p>",
        (
            "  <p><b>Route:</b> "
            f"<code>{html.escape(summary['source'])} -&gt; {html.escape(summary['target'])}</code>; "
            f"predecessor <code>{html.escape(str(summary['predecessorSelector']))}</code> "
            f"root <code>{html.escape(str(summary['predecessorRootHex']))}</code>; "
            f"current reader <code>{html.escape(str(summary['currentReaderHex']))}</code>.</p>"
        ),
        (
            "  <p><b>Runtime coverage:</b> "
            f"{summary['branchStatePollCount']} branch-state polls, "
            f"{summary['branchStatePollSequenceCount']} sequences, "
            f"{summary['branchStatePollSampleCount']} samples; "
            f"public hits {summary['branchStatePollPublicPredecessorHitCount']}; "
            f"route hits {summary['branchStatePollRouteSelectorHitCount']}; "
            f"fill matches {summary['branchStatePollFillMatchCount']}; "
            f"all-zero polls {summary['branchStatePollAllZeroCount']}; "
            f"movement-or-target poll coverage {summary['branchStatePollMovementOrTargetCount']} polls "
            f"({summary['branchStatePollMovementOrTargetSampleCount']} samples); "
            f"target-observation polls {summary['branchStatePollTargetObservationCount']} "
            f"({summary['branchStatePollTargetObservationSampleCount']} samples); "
            f"target-observation fill/current/route hits "
            f"{summary['branchStatePollTargetObservationFillMatchCount']}/"
            f"{summary['branchStatePollTargetObservationCurrentRootHitCount']}/"
            f"{summary['branchStatePollTargetObservationRouteSelectorHitCount']}; "
            f"target-observation camera-only / actor-or-trail "
            f"{summary['branchStatePollCameraOnlyTargetCount']}/"
            f"{summary['branchStatePollActorOrTrailTargetCount']}; "
            f"target-observation status <code>{html.escape(summary['branchStatePollTargetObservationStatus'])}</code>; "
            "field-entry sequence snapshots "
            f"{(summary.get('fieldEntrySequenceContext') or {}).get('snapshotCount')} "
            "with route candidates "
            f"{(summary.get('fieldEntrySequenceContext') or {}).get('snapshotRouteCandidateCount')}; "
            "field-entry proof "
            f"{bool_text((summary.get('fieldEntrySequenceContext') or {}).get('proofFound'))}/"
            f"{bool_text((summary.get('fieldEntrySequenceContext') or {}).get('predecessorFieldEntryProofFound'))}; "
            "failed gates "
            f"{html.escape(csv((summary.get('fieldEntrySequenceContext') or {}).get('failedPredecessorFieldEntryGateIds')))}; "
            "evidenceRefs="
            f"{html.escape(str((summary.get('fieldEntrySequenceContext') or {}).get('evidenceRefCount')))}; "
            "coordinate source "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('classification')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('coordinateSourceRejectionClassification')))}; "
            "start pointer/static/trail/image "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('publicSaveStartPointerTableTileHitCount')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('publicSaveStartStaticBaseHitCount')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('publicSaveStartTrailRingHitCount')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('publicSaveStartImageHitCount')))}; "
            "reciprocal pointer/static/trail/image "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('reciprocalPointerTableTileHitCount')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('reciprocalStaticBaseHitCount')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('reciprocalTrailRingHitCount')))} / "
            f"{html.escape(str((summary.get('coordinateSourceContext') or {}).get('reciprocalImageHitCount')))}.</p>"
        ),
        (
            "  <p><b>Execution proof:</b> "
            f"root-entry reaches fills {bool_text(summary['rootEntryFixedTraversalFillSitesReachable'])}; "
            f"encoded entry {html.escape(str(summary['encodedFillEntryClassification']))} "
            f"raw {html.escape(str(summary['encodedFillEntryRawScalarCandidateCount']))} "
            f"promoting {html.escape(str(summary['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')))}; "
            f"root-tail {html.escape(str(summary['rootTailDistanceHex']))}/"
            f"{html.escape(str(summary['rootTailDwordCount']))} rows "
            f"isolated {bool_text(summary['rootTailDescriptorIsolated'])}; "
            f"descriptor bridge {bool_text(summary['descriptorBridgeProofFound'])}; "
            "descriptor bridge failed gates "
            f"{html.escape(csv(summary.get('descriptorBridgeFailedGateIds')))}; "
            "descriptor bridge missing evidence count "
            f"{html.escape(str(len(summary.get('descriptorBridgeMissingEvidence') or [])))}; "
            "descriptor bridge evidence refs "
            f"{html.escape(str(summary.get('descriptorBridgeEvidenceRefCount')))}; "
            f"descriptor edge rejection "
            f"<code>{html.escape(str(summary.get('descriptorEdgeRejectionClassification')))}</code>; "
            "descriptor / route execution edge counts "
            f"{html.escape(str(summary.get('descriptorEdgeDescriptorTargetEdgeCount')))}/"
            f"{html.escape(str(summary.get('descriptorEdgeRouteExecutionTargetEdgeCount')))}; "
            "descriptor encoded target raw/root/fill/promoting "
            f"{html.escape(str(summary.get('descriptorEncodedTargetRawScalarCandidateCount')))}/"
            f"{html.escape(str(summary.get('descriptorEncodedTargetRootRawScalarCandidateCount')))}/"
            f"{html.escape(str(summary.get('descriptorEncodedTargetFillRawScalarCandidateCount')))}/"
            f"{html.escape(str(summary.get('descriptorEncodedTargetPromotingCandidateCount')))}; "
            "descriptor encoded target classification "
            f"<code>{html.escape(str(summary.get('descriptorEncodedTargetClassification')))}</code>; "
            "dispatch table proof "
            f"{html.escape(str(summary.get('predecessorDispatchTableProofFound')))}; "
            "dispatch failed gates "
            f"{html.escape(csv(summary.get('predecessorDispatchTableFailedGateIds')))}; "
            "dispatch missing evidence count "
            f"{html.escape(str(len(summary.get('predecessorDispatchTableMissingEvidence') or [])))}; "
            "dispatch evidence refs "
            f"{html.escape(str(summary.get('predecessorDispatchTableEvidenceRefCount')))}; "
            "table-base rejection "
            f"<code>{html.escape(str(summary.get('predecessorDispatchTableBaseRejectionClassification')))}</code>; "
            "table-base arithmetic rows/candidates "
            f"{html.escape(str(summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticRowCount')))}/"
            f"{html.escape(str(summary.get('predecessorDispatchSaveSelectorTableBaseArithmeticCandidateCount')))}; "
            "raw generic 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')))} "
            "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')))}; "
            "depth sensitivity "
            f"{html.escape(str(summary.get('rawGenericCallGraphDepthSensitivityMaxDepthChecked')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths')))}/"
            f"{html.escape(str(summary.get('rawGenericCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth')))}; "
            "branch gate preservation "
            f"<code>{html.escape(str(summary.get('branchGateKnownOpcodeStatePreservationStatus')))}</code> "
            "same-slot/write-read/other/invalid "
            f"{html.escape(str(summary.get('branchGateSameTableAndOffset')))}/"
            f"{html.escape(str(summary.get('branchGateSameSelectionBufferOffsetHex')))} "
            f"{html.escape(str(summary.get('branchGatePostWriterSameOffsetWriteCount')))}/"
            f"{html.escape(str(summary.get('branchGatePostWriterSameOffsetReadCount')))} "
            f"{html.escape(str(summary.get('branchGatePostWriterOtherOffsetWriteCount')))}@"
            f"{html.escape(csv(summary.get('branchGatePostWriterOtherOffsetWriteOffsetsHex')))} "
            f"invalid {html.escape(csv(summary.get('branchGateInvalidSecondaryFillOffsetsHex')))}; "
            f"runtime fill {bool_text(summary['runtimeFillObserved'])}; "
            f"proof gates {summary['requiredProofGatePassCount']} passed / "
            f"{summary['requiredProofGateFailCount']} failed; "
            f"evidence refs {html.escape(str(summary.get('evidenceRefCount')))}; "
            f"all blocked {bool_text(summary.get('requiredProofGateAllBlocked'))}; "
            f"proof found {bool_text(summary.get('proofFound'))}; "
            "failed predecessor fill gates "
            f"<code>{html.escape(csv(summary.get('failedPredecessorFillGateIds')))}</code>; "
            f"missing evidence count {len(summary.get('missingEvidence') or [])}; "
            f"context proven {bool_text(summary['fillSiteExecutionContextProven'])}; "
            f"promotion status <code>{html.escape(summary['promotionStatus'])}</code>.</p>"
        ),
        "  <h2>Missing Evidence</h2>",
        f"  <ul>{missing_evidence_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>Required Proof Gates</h2>",
        f"  <table><thead><tr><th>gate</th><th>passed</th><th>status</th><th>detail</th></tr></thead><tbody>{proof_gate_rows}</tbody></table>",
        "  <h2>Source Evidence Refs</h2>",
        f"  <table><thead><tr><th>path</th><th>fields</th></tr></thead><tbody>{evidence_ref_rows}</tbody></table>",
        "  <h2>Branch-State Polls</h2>",
        f"  <table><thead><tr><th>poll</th><th>samples</th><th>selectors</th><th>public</th><th>route</th><th>fill match</th><th>all zero</th><th>split</th></tr></thead><tbody>{poll_rows}</tbody></table>",
        "  <h2>Remaining Proofs</h2>",
        f"  <ul>{proof_items}</ul>",
        "</body>",
        "</html>",
        "",
    ])


def write_outputs(summary: dict, out_dir: Path = OUT, html_out: Path | None = None) -> Path:
    out_dir.mkdir(parents=True, exist_ok=True)
    json_out = out_dir / "save_selector_predecessor_fill_site_execution_context.json"
    json_out.write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    if html_out is not None:
        html_out.parent.mkdir(parents=True, exist_ok=True)
        html_out.write_text(html_page(summary), encoding="utf-8")
    return json_out


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out-dir", type=Path, default=OUT)
    parser.add_argument(
        "--fill-execution-order-gap",
        type=Path,
        default=OUT / "save_selector_predecessor_fill_execution_order_gap.json",
    )
    parser.add_argument(
        "--branch-state-execution-gap",
        type=Path,
        default=OUT / "save_selector_predecessor_branch_state_execution_gap.json",
    )
    parser.add_argument(
        "--descriptor-bridge-gap",
        type=Path,
        default=OUT / "save_selector_predecessor_descriptor_bridge_gap.json",
    )
    parser.add_argument(
        "--coordinate-source-scan",
        type=Path,
        default=OUT / "runtime_predecessor_coordinate_source_scan.json",
    )
    parser.add_argument(
        "--field-entry-sequence-scan",
        type=Path,
        default=OUT / "runtime_predecessor_field_entry_sequence_scan.json",
    )
    parser.add_argument(
        "--branch-gate-consistency",
        type=Path,
        default=OUT / "save_selector_branch_gate_consistency.json",
    )
    parser.add_argument("--html-out", type=Path)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.fill_execution_order_gap),
        load_json(args.branch_state_execution_gap),
        load_json(args.descriptor_bridge_gap),
        load_json(args.coordinate_source_scan),
        load_json(args.field_entry_sequence_scan),
        load_json(args.branch_gate_consistency),
    )
    json_out = write_outputs(summary, args.out_dir, args.html_out)
    print(
        "wrote predecessor fill-site execution context -> "
        f"{json_out}"
    )


if __name__ == "__main__":
    main()
