#!/usr/bin/env python3
"""Consolidate strict source/hotspot proof context for map1_01a -> map2_02d."""
from __future__ import annotations

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


ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "out"
EVIDENCE_REFS = [
    {
        "path": "out/map1_01a_strict_hotspot_review_matrix.json",
        "fields": [
            "candidateRows",
            "candidateGateSummary",
            "transitionReviewRowCount",
            "eventTransitionCount",
            "strictSourceCoordinateFound",
            "tileHotspotConfirmed",
        ],
    },
    {
        "path": "out/map1_01a_strict_event_tile_signature_scan.json",
        "fields": [
            "candidateRows",
            "targetSpawnLow3x3OwnerPairs",
            "targetSpawnTargetMapStrictEventPointCount",
            "allCenterPairMatchesRejectedReview",
            "tileSignaturePromotes",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_hotspot_gap.json",
        "fields": [
            "evidence",
            "resourceRefScan",
            "targetContext",
            "strictHotspotFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_exit_coordinate_variant_scan.json",
        "fields": [
            "targetSpawnVariantScanCount",
            "targetSpawnCurrentRootClassificationCounts",
            "targetSpawnCharacterDescriptorClassificationCounts",
            "targetSpawnPromotableHitCount",
            "strictCoordinateEvidenceFound",
        ],
    },
    {
        "path": "out/map1_01a_exit_byte_coordinate_scan.json",
        "fields": [
            "bytePairScanCount",
            "strictSourceTargetByteHitCount",
            "currentSelectorRootByteHitCount",
            "targetSpawnStrictSourceTargetByteHitCount",
            "targetSpawnCurrentSelectorRootByteHitCount",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_exit_cns_payload_scan.json",
        "fields": [
            "sourceCns",
            "bytePairScanCount",
            "wordPairScanCount",
            "packedU32ScanCount",
            "strictCnsCoordinateEvidenceFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_resource_ref_scan.json",
        "fields": [
            "resourceReferenceCount",
            "pointCandidateCount",
            "pointCandidateClassCounts",
            "routeExitPointCandidateCount",
            "strictSourceTargetCandidateCount",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_scene_payload_context.json",
        "fields": [
            "sourceRecordVaHex",
            "targetRecordVaHex",
            "payloads",
            "strictHotspotFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_record_pattern_contrast.json",
        "fields": [
            "frontierHasOnlySelectorSceneList",
            "frontierHasStrictEventRecord",
            "frontierHasStrictSourceHotspot",
            "confirmedLikePatternFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_strict_target_link_gap.json",
        "fields": [
            "directStrictEventTransitions",
            "sourceStrictClusters",
            "targetStrictClusters",
            "targetSelectorOnlyClusters",
            "currentFrontierCluster",
            "strictTargetLinkFound",
        ],
    },
    {
        "path": "out/save_selector_frontier_reader_branch_context.json",
        "fields": [
            "classification",
            "passOutcome",
            "failOutcome",
            "runtimeSelectionProven",
            "strictHotspotFound",
        ],
    },
    {
        "path": "out/save_selector_frontier_payload_shape.json",
        "fields": [
            "allPayloadsFitPairedImages",
            "sourceInBoundsPointCount",
            "payloadTextRefCount",
            "promotionStatus",
        ],
    },
    {
        "path": "out/save_selector_scene_adjacency_index.json",
        "fields": [
            "currentPair",
            "currentPairOccurrenceCount",
            "currentPairStrictEventBacked",
            "currentPairConfirmedReviewBacked",
            "currentPairSelectorAdjacencyOnly",
        ],
    },
    {
        "path": "out/map1_01a_edge_trigger_gap.json",
        "fields": [
            "candidateRows",
            "directCallGraphEvidence",
            "sourceBoundaryCandidateCount",
            "transitionLikeDirectRelHitCountInHelperOrController",
            "directRouteImmediateCountInHelperOrController",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_manifest_point_scan.json",
        "fields": [
            "records",
            "incomingPointTableCount",
            "strictSourceHotspotFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_root_point_scan.json",
        "fields": [
            "pointerLikeCount",
            "reportedCandidateCount",
            "frontierClusterCandidateCount",
            "exactExitCandidateCount",
            "scriptLikeCandidateCount",
            "strictSourceHotspotFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_entry_context.json",
        "fields": [
            "confirmedEntryClusterHex",
            "frontierClusterHex",
            "frontierProvenFromConfirmedEntry",
            "remainingProofs",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_scene_record_cluster_context.json",
        "fields": [
            "sourceSceneRecordCount",
            "sourceStrictOutgoingClusterCount",
            "sourceTargetSharedStrictClusterCount",
            "sourceTargetSharedSelectorOnlyClusterCount",
            "currentFrontierEventRecordCount",
            "currentFrontierSaveSelectorRefCount",
            "strictTargetLinkFound",
            "promotionStatus",
        ],
    },
    {
        "path": "out/map1_01a_selector_bridge_refs.json",
        "fields": [
            "confirmedToFrontier",
            "frontierToConfirmed",
            "bridgeFound",
            "limitations",
            "promotionStatus",
        ],
    },
]


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 count_where(rows: list[dict], key: str, value: Any = True) -> int:
    return sum(1 for row in rows if row.get(key) == value)


def strict_hotspot_rejection(
    proof_found: bool,
    strict_hotspot_review_matrix: dict,
    gate: dict,
    center_pair_match_count: int,
    center_pair_target_linked_match_count: int,
    center_pair_rejected_review_match_count: int,
    all_center_pair_matches_rejected_review: bool,
    target_linked_match_count: int,
    direct_source_target_match_count: int,
    resource_ref_scan: dict,
    strict_target_link_gap: dict,
    scene_adjacency_index: dict,
    edge_trigger_gap: dict,
    edge_trigger_generic_boundary_transition_proven: bool,
) -> dict:
    edge_direct_call_graph = edge_trigger_gap.get("directCallGraphEvidence") or {}
    edge_call_graph_sensitivity = edge_trigger_gap.get("directCallGraphDepthSensitivity") or {}
    if proof_found:
        classification = "strict-source-hotspot-proof-present"
        reason = "strict source coordinate, tile hotspot, and strict target link are all present"
    elif (
        strict_hotspot_review_matrix.get("transitionReviewRowCount") == 0
        and strict_hotspot_review_matrix.get("eventTransitionCount") == 0
        and gate.get("allCoordinateRefsNonPromotable") is True
        and gate.get("allVariantScansNonPromotable") is True
        and center_pair_match_count > 0
        and center_pair_target_linked_match_count == 0
        and center_pair_rejected_review_match_count == center_pair_match_count
        and all_center_pair_matches_rejected_review is True
        and target_linked_match_count == 0
        and direct_source_target_match_count == 0
        and (resource_ref_scan.get("routeExitPointCandidateCount") or 0) == 0
        and strict_target_link_gap.get("strictTargetLinkFound") is False
        and scene_adjacency_index.get("currentPairSelectorAdjacencyOnly") is True
        and edge_trigger_generic_boundary_transition_proven is False
    ):
        classification = "selector-only-scene-list-no-strict-hotspot"
        reason = (
            "candidate tiles have no route review/event rows; the only tile-signature overlap is a rejected "
            "incoming map1_02b->map1_01a center match, resource scans have no route-exit point, and generic "
            "edge-trigger scans find no map-loader/selector-path hit"
        )
    else:
        classification = "strict-source-hotspot-proof-missing"
        reason = "one or more strict source/hotspot proof gates are still absent"
    return {
        "classification": classification,
        "proofFound": proof_found,
        "reason": reason,
        "candidateCount": strict_hotspot_review_matrix.get("candidateCount"),
        "transitionReviewRowCount": strict_hotspot_review_matrix.get("transitionReviewRowCount"),
        "eventTransitionCount": strict_hotspot_review_matrix.get("eventTransitionCount"),
        "strictSourceCoordinateFound": strict_hotspot_review_matrix.get("strictSourceCoordinateFound"),
        "tileHotspotConfirmed": strict_hotspot_review_matrix.get("tileHotspotConfirmed"),
        "allCoordinateRefsNonPromotable": gate.get("allCoordinateRefsNonPromotable"),
        "allVariantScansNonPromotable": gate.get("allVariantScansNonPromotable"),
        "centerPairStrictEventMatchCount": center_pair_match_count,
        "centerPairTargetLinkedMatchCount": center_pair_target_linked_match_count,
        "centerPairRejectedReviewMatchCount": center_pair_rejected_review_match_count,
        "allCenterPairMatchesRejectedReview": all_center_pair_matches_rejected_review,
        "targetLinkedStrictEventMatchCount": target_linked_match_count,
        "directSourceTargetStrictEventMatchCount": direct_source_target_match_count,
        "routeExitPointCandidateCount": resource_ref_scan.get("routeExitPointCandidateCount"),
        "strictTargetLinkFound": strict_target_link_gap.get("strictTargetLinkFound"),
        "currentPairSelectorAdjacencyOnly": scene_adjacency_index.get("currentPairSelectorAdjacencyOnly"),
        "edgeTriggerPromotionAllowed": edge_trigger_gap.get("promotionAllowed"),
        "edgeTriggerPromotionStatus": edge_trigger_gap.get("promotionStatus"),
        "edgeTriggerDirectCallGraphRejectionClassification": edge_direct_call_graph.get(
            "classification"
        ),
        "edgeTriggerDirectCallGraphProofFound": edge_direct_call_graph.get("proofFound"),
        "edgeTriggerDirectCallGraphReachableFunctionCount": edge_direct_call_graph.get(
            "reachableFunctionCount"
        ),
        "edgeTriggerDirectCallGraphTransitionTargetHitCount": edge_direct_call_graph.get(
            "transitionTargetHitCount"
        ),
        "edgeTriggerDirectCallGraphRouteImmediateHitCount": edge_direct_call_graph.get(
            "routeImmediateHitCount"
        ),
        "edgeTriggerDirectCallGraphIndirectRejectionClassification": edge_direct_call_graph.get(
            "indirectCallGraphRejectionClassification"
        ),
        "edgeTriggerDirectCallGraphIndirectProofFound": edge_direct_call_graph.get(
            "indirectCallGraphProofFound"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableCandidateCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableCandidateCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableEntryCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableEntryCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableTargetCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableTargetCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableUniqueTargetCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableUniqueTargetCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableTargetClassCounts": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableTargetClassCounts"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableAllTargetsLocalToEdgeHandlers": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableAllTargetsLocalToEdgeHandlers"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableOutsideEdgeHandlerTargetCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableOutsideEdgeHandlerTargetCount"
        ),
        "edgeTriggerDirectCallGraphIndirectTransitionTargetHitCount": edge_direct_call_graph.get(
            "indirectCallGraphTransitionTargetHitCount"
        ),
        "edgeTriggerDirectCallGraphIndirectRouteImmediateHitCount": edge_direct_call_graph.get(
            "indirectCallGraphRouteImmediateHitCount"
        ),
        "edgeTriggerDirectCallGraphDepthSensitivityMaxDepthChecked": (
            edge_call_graph_sensitivity.get("maxDepthChecked")
        ),
        "edgeTriggerDirectCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
            edge_call_graph_sensitivity.get("proofAbsentAcrossCheckedDepths")
        ),
        "edgeTriggerDirectCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth": (
            edge_call_graph_sensitivity.get("countsStableAtAndBeyondDefaultDepth")
        ),
    }


def build_summary(
    strict_hotspot_review_matrix: dict,
    strict_event_tile_signature_scan: dict,
    hotspot_gap: dict,
    exit_coordinate_variant_scan: dict,
    exit_byte_coordinate_scan: dict,
    exit_cns_payload_scan: dict,
    resource_ref_scan: dict,
    scene_payload_context: dict,
    record_pattern_contrast: dict,
    strict_target_link_gap: dict,
    frontier_reader_branch_context: dict,
    frontier_payload_shape: dict,
    scene_adjacency_index: dict,
    edge_trigger_gap: dict,
    manifest_point_scan: dict,
    root_point_scan: dict,
    entry_context: dict,
    scene_record_cluster_context: dict,
    selector_bridge_refs: dict,
) -> dict:
    candidate_rows = strict_hotspot_review_matrix.get("candidateRows") or []
    signature_rows = (
        strict_event_tile_signature_scan.get("candidateRows")
        or strict_event_tile_signature_scan.get("candidates")
        or []
    )
    gate = strict_hotspot_review_matrix.get("candidateGateSummary") or {}
    center_pair_match_count = sum(row.get("centerPairStrictEventMatchCount") or 0 for row in signature_rows)
    center_pair_same_source_match_count = sum(row.get("centerPairSameSourceMatchCount") or 0 for row in signature_rows)
    center_pair_target_linked_match_count = sum(row.get("centerPairTargetLinkedMatchCount") or 0 for row in signature_rows)
    center_pair_confirmed_review_match_count = sum(row.get("centerPairConfirmedReviewMatchCount") or 0 for row in signature_rows)
    center_pair_rejected_review_match_count = sum(row.get("centerPairRejectedReviewMatchCount") or 0 for row in signature_rows)
    all_center_pair_matches_rejected_review = (
        strict_event_tile_signature_scan.get("allCenterPairMatchesRejectedReview")
        if "allCenterPairMatchesRejectedReview" in strict_event_tile_signature_scan
        else center_pair_match_count > 0
        and center_pair_rejected_review_match_count == center_pair_match_count
    )
    center_pair_owner_counts: dict[str, int] = {}
    for row in signature_rows:
        for owner_row in row.get("centerPairOwnerPairs") or []:
            owner = owner_row.get("owner")
            if owner:
                center_pair_owner_counts[owner] = center_pair_owner_counts.get(owner, 0) + int(owner_row.get("count") or 0)
    center_pair_owner_pairs = [
        {"owner": owner, "count": count}
        for owner, count in sorted(center_pair_owner_counts.items(), key=lambda item: (-item[1], item[0]))
    ]
    center_pair_owner_text = csv(
        [f"{row.get('owner')}:{row.get('count')}" for row in center_pair_owner_pairs]
    )
    low3x3_match_count = sum(row.get("low3x3StrictEventMatchCount") or 0 for row in signature_rows)
    pair3x3_match_count = sum(row.get("pair3x3StrictEventMatchCount") or 0 for row in signature_rows)
    target_linked_match_count = sum(row.get("targetLinkedStrictEventMatchCount") or 0 for row in signature_rows)
    direct_source_target_match_count = sum(
        row.get("directSourceTargetStrictEventMatchCount") or 0 for row in signature_rows
    )
    confirmed_pair_match_count = sum(row.get("confirmedReviewPair3x3MatchCount") or 0 for row in signature_rows)
    target_spawn_strict_event_point_count = strict_event_tile_signature_scan.get(
        "targetSpawnTargetMapStrictEventPointCount",
        strict_event_tile_signature_scan.get("targetSpawnStrictEventPointCount"),
    )
    target_spawn_center_pair_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnCenterPairStrictEventMatchCount",
        sum(row.get("targetSpawnCenterPairStrictEventMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_low3x3_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnLow3x3StrictEventMatchCount",
        sum(row.get("targetSpawnLow3x3StrictEventMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_pair3x3_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnPair3x3StrictEventMatchCount",
        sum(row.get("targetSpawnPair3x3StrictEventMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_center_pair_target_map_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnCenterPairTargetMapMatchCount",
        sum(row.get("targetSpawnCenterPairTargetMapMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_low3x3_target_map_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnLow3x3TargetMapMatchCount",
        sum(row.get("targetSpawnLow3x3TargetMapMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_pair3x3_target_map_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnPair3x3TargetMapMatchCount",
        sum(row.get("targetSpawnPair3x3TargetMapMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_low3x3_target_linked_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnLow3x3TargetLinkedMatchCount",
        sum(row.get("targetSpawnLow3x3TargetLinkedMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_low3x3_confirmed_review_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnLow3x3ConfirmedReviewMatchCount",
        sum(row.get("targetSpawnLow3x3ConfirmedReviewMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_low3x3_rejected_review_match_count = strict_event_tile_signature_scan.get(
        "targetSpawnLow3x3RejectedReviewMatchCount",
        sum(row.get("targetSpawnLow3x3RejectedReviewMatchCount") or 0 for row in signature_rows),
    )
    target_spawn_low3x3_owner_pairs = (
        strict_event_tile_signature_scan.get("targetSpawnLow3x3OwnerPairs") or []
    )
    if not target_spawn_low3x3_owner_pairs:
        target_spawn_low3x3_owner_counts: dict[str, int] = {}
        for row in signature_rows:
            for owner_row in row.get("targetSpawnLow3x3OwnerPairs") or []:
                owner = owner_row.get("owner")
                if owner:
                    target_spawn_low3x3_owner_counts[owner] = (
                        target_spawn_low3x3_owner_counts.get(owner, 0)
                        + int(owner_row.get("count") or 0)
                    )
        target_spawn_low3x3_owner_pairs = [
            {"owner": owner, "count": count}
            for owner, count in sorted(
                target_spawn_low3x3_owner_counts.items(),
                key=lambda item: (-item[1], item[0]),
            )
        ]
    target_spawn_low3x3_owner_text = csv(
        [f"{row.get('owner')}:{row.get('count')}" for row in target_spawn_low3x3_owner_pairs]
    )
    target_spawn_low3x3_generic_only = strict_event_tile_signature_scan.get(
        "targetSpawnLow3x3GenericOnly"
    )
    if target_spawn_low3x3_generic_only is None:
        target_spawn_low3x3_generic_only = (
            (target_spawn_low3x3_match_count or 0) > 0
            and (target_spawn_low3x3_target_linked_match_count or 0) == 0
            and (target_spawn_low3x3_target_map_match_count or 0) == 0
            and (target_spawn_center_pair_match_count or 0) == 0
            and (target_spawn_pair3x3_match_count or 0) == 0
        )
    all_target_spawn_center_pair_matches_zero = strict_event_tile_signature_scan.get(
        "allTargetSpawnCenterPairMatchesZero"
    )
    if all_target_spawn_center_pair_matches_zero is None:
        all_target_spawn_center_pair_matches_zero = all(
            (row.get("targetSpawnCenterPairStrictEventMatchCount") or 0) == 0
            for row in signature_rows
        )
    all_target_spawn_pair3x3_matches_zero = strict_event_tile_signature_scan.get(
        "allTargetSpawnPair3x3MatchesZero"
    )
    if all_target_spawn_pair3x3_matches_zero is None:
        all_target_spawn_pair3x3_matches_zero = all(
            (row.get("targetSpawnPair3x3StrictEventMatchCount") or 0) == 0
            for row in signature_rows
        )
    all_target_spawn_target_map_strict_events_zero = strict_event_tile_signature_scan.get(
        "allTargetSpawnTargetMapStrictEventsZero"
    )
    if all_target_spawn_target_map_strict_events_zero is None:
        all_target_spawn_target_map_strict_events_zero = (
            target_spawn_strict_event_point_count == 0
            and target_spawn_center_pair_target_map_match_count == 0
            and target_spawn_low3x3_target_map_match_count == 0
            and target_spawn_pair3x3_target_map_match_count == 0
    )
    center_match_sides = [
        row.get("side")
        for row in signature_rows
        if (row.get("centerPairStrictEventMatchCount") or 0) > 0
    ]
    edge_candidates_by_side = {
        row.get("side"): row
        for row in edge_trigger_gap.get("candidateRows") or []
        if row.get("side")
    }
    candidate_summaries = []
    candidate_block_reason_counts: dict[str, int] = {}
    for row in candidate_rows:
        edge_candidate = edge_candidates_by_side.get(row.get("side")) or {}
        edge_target_spawn = edge_candidate.get("targetSpawn") or {}
        coordinate_ref = row.get("coordinateRef") or {}
        variant_scan = row.get("variantScan") or {}
        tile_evidence = row.get("tileEvidence") or {}
        target_spawn = tile_evidence.get("targetSpawn") or {}
        route_assist_url = row.get("routeAssistUrl") or edge_candidate.get("routeAssistUrl")
        target_review_url = (
            row.get("targetReviewUrl")
            or edge_candidate.get("targetReviewUrl")
            or edge_target_spawn.get("reviewUrl")
        )
        block_reasons = [str(reason) for reason in row.get("blockReasons") or []]
        for reason in block_reasons:
            candidate_block_reason_counts[reason] = candidate_block_reason_counts.get(reason, 0) + 1
        candidate_summaries.append(
            {
                "side": row.get("side"),
                "tile": row.get("tile") or {},
                "span": row.get("span") or {},
                "geometryStandable": row.get("geometryStandable"),
                "tileCount": row.get("tileCount"),
                "targetHint": row.get("targetHint") or {},
                "coordinateStatus": coordinate_ref.get("status"),
                "coordinatePromotable": coordinate_ref.get("promotable"),
                "coordinateXyHitCount": coordinate_ref.get("xyHitCount"),
                "coordinateXyAlignedHitCount": coordinate_ref.get("xyAlignedHitCount"),
                "coordinateYxHitCount": coordinate_ref.get("yxHitCount"),
                "coordinateYxAlignedHitCount": coordinate_ref.get("yxAlignedHitCount"),
                "variantInterestingHitCount": variant_scan.get("interestingHitCount"),
                "variantCurrentRootHitCount": variant_scan.get("currentRootHitCount"),
                "variantCharacterDescriptorHitCount": variant_scan.get(
                    "characterDescriptorHitCount"
                ),
                "variantSpanBoundHitCount": variant_scan.get("spanBoundHitCount"),
                "variantSpanBoundCurrentRootHitCount": variant_scan.get(
                    "spanBoundCurrentRootHitCount"
                ),
                "variantSpanSequenceHitCount": variant_scan.get("spanSequenceHitCount"),
                "variantXyRowSequenceHitCount": variant_scan.get("xyRowSequenceHitCount"),
                "variantYxAxisSequenceHitCount": variant_scan.get("yxAxisSequenceHitCount"),
                "variantYxOpcodeSequenceHitCount": variant_scan.get("yxOpcodeSequenceHitCount"),
                "variantStrictCoordinateEvidenceFound": variant_scan.get(
                    "strictCoordinateEvidenceFound"
                ),
                "routeReviewRowCount": row.get("routeReviewRowCount"),
                "eventTransitionCount": row.get("eventTransitionCount"),
                "sourceOriginalStandable": tile_evidence.get("sourceOriginalStandable"),
                "targetSpawnOriginalStandable": tile_evidence.get("targetSpawnOriginalStandable"),
                "targetSpawn": target_spawn,
                "lowNibbleMatch": tile_evidence.get("matchesConfirmedLowNibble"),
                "strictTransitionReviewRowsForRoute": tile_evidence.get(
                    "strictTransitionReviewRowsForRoute"
                ),
                "routeAssistUrl": route_assist_url,
                "targetReviewUrl": target_review_url,
                "targetSpawnReviewUrl": target_review_url,
                "promotionStatus": row.get("promotionStatus"),
                "blockReasons": block_reasons,
                "blockReasonSummary": "; ".join(block_reasons) or "-",
            }
        )
    strict_source_hotspot_proof_found = (
        strict_hotspot_review_matrix.get("strictSourceCoordinateFound") is True
        and strict_hotspot_review_matrix.get("tileHotspotConfirmed") is True
        and strict_target_link_gap.get("strictTargetLinkFound") is True
    )
    promotion_status = "ready-for-review" if strict_source_hotspot_proof_found else "blocked"
    failed_strict_hotspot_gate_ids = []
    if strict_hotspot_review_matrix.get("strictSourceCoordinateFound") is not True:
        failed_strict_hotspot_gate_ids.append("strict-source-coordinate")
    if strict_hotspot_review_matrix.get("tileHotspotConfirmed") is not True:
        failed_strict_hotspot_gate_ids.append("tile-hotspot-confirmation")
    if strict_target_link_gap.get("strictTargetLinkFound") is not True:
        failed_strict_hotspot_gate_ids.append("strict-target-link")
    if edge_trigger_gap.get("promotionAllowed") is not True:
        failed_strict_hotspot_gate_ids.append("equivalent-runtime-trigger-proof")
    missing_by_gate = {
        "strict-source-coordinate": "strict map1_01a event/coordinate source row for map2_02d",
        "tile-hotspot-confirmation": "route review or tile hotspot tied to map1_01a -> map2_02d",
        "strict-target-link": "strict source-target link for map1_01a -> map2_02d",
        "equivalent-runtime-trigger-proof": "equivalent runtime trigger proof replacing selector-only adjacency",
    }
    missing_evidence = [
        missing_by_gate[gate]
        for gate in failed_strict_hotspot_gate_ids
        if gate in missing_by_gate
    ]
    edge_direction_latch = edge_trigger_gap.get("directionLatchReferenceEvidence") or {}
    edge_global_refs = (edge_trigger_gap.get("globalTransitionReferenceEvidence") or {}).get(
        "directReferences"
    ) or {}
    edge_script_runner_context = edge_trigger_gap.get("scriptRunnerCallContextEvidence") or {}
    edge_selected_pointer_context = (
        edge_trigger_gap.get("selectedPointerImmediateContextEvidence") or {}
    )
    edge_direct_call_graph = edge_trigger_gap.get("directCallGraphEvidence") or {}
    edge_call_graph_sensitivity = edge_trigger_gap.get("directCallGraphDepthSensitivity") or {}
    edge_actor_controller_caller_windows = (
        edge_trigger_gap.get("actorControllerCallerWindowEvidence") or {}
    )
    edge_collision_helper_caller_windows = (
        edge_trigger_gap.get("collisionHelperCallerWindowEvidence") or {}
    )
    edge_handler_encoded = edge_trigger_gap.get("edgeHandlerEncodedTargetScan") or {}
    edge_local_window_encoded = edge_trigger_gap.get("edgeLocalWindowEncodedTargetScan") or {}
    edge_call_graph_encoded = edge_trigger_gap.get("edgeCallGraphEncodedTargetScan") or {}
    edge_global_contrast_encoded = (
        edge_trigger_gap.get("edgeGlobalContrastWindowEncodedTargetScan") or {}
    )
    edge_trigger_generic_boundary_transition_proven = (
        edge_trigger_gap.get("promotionAllowed") is True
    )
    byte_coordinate_sequence_hit_count = (
        (exit_byte_coordinate_scan.get("axisSequenceHitCount") or 0)
        + (exit_byte_coordinate_scan.get("spanSequenceHitCount") or 0)
    )
    cns_payload_sequence_hit_count = (
        (exit_cns_payload_scan.get("byteSequenceHitCount") or 0)
        + (exit_cns_payload_scan.get("wordSequenceHitCount") or 0)
    )
    evidence = [
        {
            "kind": "candidate-review-gate",
            "status": "no-route-review-or-event",
            "detail": (
                f"candidates={strict_hotspot_review_matrix.get('candidateCount')}; "
                f"routeReviews={strict_hotspot_review_matrix.get('transitionReviewRowCount')}; "
                f"routeEvents={strict_hotspot_review_matrix.get('eventTransitionCount')}; "
                f"incomingReviews={strict_hotspot_review_matrix.get('confirmedIncomingReviewCount')}/"
                f"{strict_hotspot_review_matrix.get('incomingReviewCount')}; "
                f"incomingRecords={csv(strict_hotspot_review_matrix.get('confirmedIncomingRecordHexes') or [])}"
            ),
        },
        {
            "kind": "coordinate-variant-gate",
            "status": "non-promotable",
            "detail": (
                f"coordRefsBlocked={gate.get('allCoordinateRefsNonPromotable')}; "
                f"variantsBlocked={gate.get('allVariantScansNonPromotable')}; "
                f"targetSpawnEncodings={exit_coordinate_variant_scan.get('targetSpawnVariantScanCount')}; "
                "targetSpawnCurrentRoot/Character="
                f"{exit_coordinate_variant_scan.get('targetSpawnCurrentRootHitCount')}/"
                f"{exit_coordinate_variant_scan.get('targetSpawnCharacterDescriptorHitCount')}; "
                "targetSpawnCurrentClasses="
                f"{json.dumps(exit_coordinate_variant_scan.get('targetSpawnCurrentRootClassificationCounts') or {}, sort_keys=True)}; "
                "targetSpawnCharacterClasses="
                f"{json.dumps(exit_coordinate_variant_scan.get('targetSpawnCharacterDescriptorClassificationCounts') or {}, sort_keys=True)}; "
                f"targetSpawnPromotable={exit_coordinate_variant_scan.get('targetSpawnPromotableHitCount')}; "
                "targetSpawnAllInterestingNonPromotable="
                f"{exit_coordinate_variant_scan.get('targetSpawnAllInterestingHitsNonPromotable')}; "
                f"spanSeqHits={exit_coordinate_variant_scan.get('spanSequenceHitCount')}; "
                f"xySeqHits={exit_coordinate_variant_scan.get('xyRowSequenceHitCount')}; "
                f"yxOpcodeHits={exit_coordinate_variant_scan.get('yxOpcodeSequenceHitCount')}"
            ),
        },
        {
            "kind": "byte-coordinate-gate",
            "status": "non-promotable",
            "detail": (
                f"bytePairScans={exit_byte_coordinate_scan.get('bytePairScanCount')}; "
                "sequenceScans="
                f"{(exit_byte_coordinate_scan.get('axisSequenceScanCount') or 0) + (exit_byte_coordinate_scan.get('spanSequenceScanCount') or 0)}; "
                f"byteHits={exit_byte_coordinate_scan.get('bytePairHitCount')}; "
                f"sequenceHits={byte_coordinate_sequence_hit_count}; "
                f"strictSourceTargetByteHits={exit_byte_coordinate_scan.get('strictSourceTargetByteHitCount')}; "
                f"strictEventOtherByteHits={exit_byte_coordinate_scan.get('strictEventOtherByteHitCount')}; "
                f"currentSelectorRootByteHits={exit_byte_coordinate_scan.get('currentSelectorRootByteHitCount')}; "
                f"textCodeByteHits={exit_byte_coordinate_scan.get('textCodeByteHitCount')}; "
                f"strictByteCoordinateEvidenceFound={exit_byte_coordinate_scan.get('strictByteCoordinateEvidenceFound')}; "
                f"targetSpawnBytePairScans={exit_byte_coordinate_scan.get('targetSpawnBytePairScanCount')}; "
                f"targetSpawnByteHits={exit_byte_coordinate_scan.get('targetSpawnBytePairHitCount')}; "
                f"targetSpawnStrictSourceTargetByteHits={exit_byte_coordinate_scan.get('targetSpawnStrictSourceTargetByteHitCount')}; "
                f"targetSpawnCurrentSelectorRootByteHits={exit_byte_coordinate_scan.get('targetSpawnCurrentSelectorRootByteHitCount')}; "
                f"targetSpawnStrictByteCoordinateEvidenceFound={exit_byte_coordinate_scan.get('targetSpawnStrictByteCoordinateEvidenceFound')}; "
                f"promotionStatus={exit_byte_coordinate_scan.get('promotionStatus')}"
            ),
        },
        {
            "kind": "cns-payload-gate",
            "status": "tilemap-only-nonpromoting",
            "detail": (
                f"sourceCns={(exit_cns_payload_scan.get('sourceCns') or {}).get('width')}x"
                f"{(exit_cns_payload_scan.get('sourceCns') or {}).get('height')}; "
                f"bytePairScans={exit_cns_payload_scan.get('bytePairScanCount')}; "
                f"wordPairScans={exit_cns_payload_scan.get('wordPairScanCount')}; "
                f"packedU32Scans={exit_cns_payload_scan.get('packedU32ScanCount')}; "
                "sequenceScans="
                f"{(exit_cns_payload_scan.get('byteSequenceScanCount') or 0) + (exit_cns_payload_scan.get('wordSequenceScanCount') or 0)}; "
                f"bytePairHits={exit_cns_payload_scan.get('bytePairHitCount')}; "
                f"wordPairHits={exit_cns_payload_scan.get('wordPairHitCount')}; "
                f"packedU32Hits={exit_cns_payload_scan.get('packedU32HitCount')}; "
                f"sequenceHits={cns_payload_sequence_hit_count}; "
                f"headerHits={exit_cns_payload_scan.get('headerHitCount')}; "
                f"layerHits={exit_cns_payload_scan.get('layerHitCount')}; "
                f"outsideStructuredHits={exit_cns_payload_scan.get('outsideStructuredHitCount')}; "
                f"strictCnsCoordinateEvidenceFound={exit_cns_payload_scan.get('strictCnsCoordinateEvidenceFound')}; "
                f"promotionStatus={exit_cns_payload_scan.get('promotionStatus')}"
            ),
        },
        {
            "kind": "tile-signature-gate",
            "status": "center-pair-only-nonpromoting"
            if center_pair_match_count and not (low3x3_match_count or pair3x3_match_count)
            else "no-promoting-signature",
            "detail": (
                f"centerPairMatches={center_pair_match_count}; "
                f"centerPairOwners={center_pair_owner_text}; "
                f"centerPairSameSource={center_pair_same_source_match_count}; "
                f"centerPairTargetLinked={center_pair_target_linked_match_count}; "
                f"centerPairConfirmedReview={center_pair_confirmed_review_match_count}; "
                f"centerPairRejectedReview={center_pair_rejected_review_match_count}; "
                f"allCenterPairRejectedReview={all_center_pair_matches_rejected_review}; "
                f"centerSides={csv(center_match_sides)}; "
                f"low3x3Matches={low3x3_match_count}; "
                f"pair3x3Matches={pair3x3_match_count}; "
                "targetSpawnStrictEvents="
                f"{target_spawn_strict_event_point_count}; "
                "targetSpawnMatches="
                f"{target_spawn_center_pair_match_count}/"
                f"{target_spawn_low3x3_match_count}/"
                f"{target_spawn_pair3x3_match_count}; "
                "targetSpawnTargetMapMatches="
                f"{target_spawn_center_pair_target_map_match_count}/"
                f"{target_spawn_low3x3_target_map_match_count}/"
                f"{target_spawn_pair3x3_target_map_match_count}; "
                "targetSpawnLow3x3Owners="
                f"{target_spawn_low3x3_owner_text}; "
                "targetSpawnLow3x3TargetLinked/Confirmed/Rejected="
                f"{target_spawn_low3x3_target_linked_match_count}/"
                f"{target_spawn_low3x3_confirmed_review_match_count}/"
                f"{target_spawn_low3x3_rejected_review_match_count}; "
                "targetSpawnLow3x3GenericOnly="
                f"{target_spawn_low3x3_generic_only}; "
                "targetSpawnAllCenterPair/Pair3x3/TargetMapZero="
                f"{all_target_spawn_center_pair_matches_zero}/"
                f"{all_target_spawn_pair3x3_matches_zero}/"
                f"{all_target_spawn_target_map_strict_events_zero}; "
                f"targetLinkedMatches={target_linked_match_count}; "
                f"directSourceTargetMatches={direct_source_target_match_count}; "
                f"confirmedPairMatches={confirmed_pair_match_count}; "
                f"tileSignaturePromotes={strict_event_tile_signature_scan.get('tileSignaturePromotes')}"
            ),
        },
        {
            "kind": "resource-window-gate",
            "status": "scene-list-no-point-hit",
            "detail": (
                f"resourceRefs={resource_ref_scan.get('resourceReferenceCount')}; "
                f"frontierRef={resource_ref_scan.get('currentFrontierReferenceFound')}; "
                f"pointCandidates={resource_ref_scan.get('pointCandidateCount')}; "
                f"routeExitPointCandidates={resource_ref_scan.get('routeExitPointCandidateCount')}; "
                f"strictSourceTargetCandidates={resource_ref_scan.get('strictSourceTargetCandidateCount')}; "
                "classes="
                f"{resource_ref_scan.get('pointCandidateClassCounts')}; "
                "frontierClasses="
                f"{resource_ref_scan.get('currentFrontierPointCandidateClassCounts')}; "
                "frontierRouteHits="
                f"{resource_ref_scan.get('currentFrontierRouteExitPointHitCount')}"
            ),
        },
        {
            "kind": "frontier-branch-gate",
            "status": frontier_reader_branch_context.get("classification") or "unknown",
            "detail": (
                f"reader={frontier_reader_branch_context.get('readerVaHex')}; "
                f"failResource={(frontier_reader_branch_context.get('failOutcome') or {}).get('targetIsResource')}; "
                f"passPayload={(frontier_reader_branch_context.get('passOutcome') or {}).get('payloadClassification')}; "
                f"passInBounds={(frontier_reader_branch_context.get('passOutcome') or {}).get('payloadInBoundsPointCount')}; "
                f"siblingFieldMaps={frontier_reader_branch_context.get('siblingFieldMapTargetCount')}; "
                f"runtimeSelection={frontier_reader_branch_context.get('runtimeSelectionProven')}"
            ),
        },
        {
            "kind": "payload-shape-gate",
            "status": "resource-rect-payload",
            "detail": (
                f"rectLike={frontier_payload_shape.get('rectLikePayloadGateCount')}/"
                f"{frontier_payload_shape.get('gateCount')}; "
                f"fitImages={frontier_payload_shape.get('allPayloadsFitPairedImages')}; "
                f"inBoundsPoints={frontier_payload_shape.get('sourceInBoundsPointCount')}; "
                f"textRefs={frontier_payload_shape.get('payloadTextRefCount')}"
            ),
        },
        {
            "kind": "strict-target-link-gate",
            "status": "absent",
            "detail": (
                f"directStrict={strict_target_link_gap.get('directStrictEventTransitionCount')}; "
                f"sourceIncomingOnly={strict_target_link_gap.get('sourceIncomingOnlyStrictClusterCount')}; "
                f"sourceOutgoing={strict_target_link_gap.get('sourceOutgoingStrictClusterCount')}; "
                f"targetStrict={strict_target_link_gap.get('targetStrictClusterCount')}; "
                f"targetSelectorOnly={strict_target_link_gap.get('targetSelectorOnlyClusterCount')}; "
                f"targetSelectorSourceOverlap={strict_target_link_gap.get('targetSelectorOnlySourceOverlapCount')}; "
                f"targetSelectorSourceTargetPairs={strict_target_link_gap.get('targetSelectorOnlySourceTargetRoutePairClusterCount')}; "
                f"currentFrontierPairs={strict_target_link_gap.get('currentFrontierRoutePairCount')}; "
                f"currentSourceOutgoing={strict_target_link_gap.get('currentFrontierSourceOutgoingRoutePairCount')}; "
                f"currentTargetIncoming={strict_target_link_gap.get('currentFrontierTargetIncomingRoutePairCount')}; "
                f"frontierSelectorOnly={strict_target_link_gap.get('currentFrontierClusterIsSelectorOnly')}; "
                f"strictTargetLinkFound={strict_target_link_gap.get('strictTargetLinkFound')}"
            ),
        },
        {
            "kind": "scene-adjacency-gate",
            "status": "selector-only",
            "detail": (
                f"currentOcc={scene_adjacency_index.get('currentPairOccurrenceCount')}; "
                f"selectors={csv((scene_adjacency_index.get('currentPair') or {}).get('selectors') or [])}; "
                f"strictBacked={scene_adjacency_index.get('currentPairStrictEventBacked')}; "
                f"confirmedBacked={scene_adjacency_index.get('currentPairConfirmedReviewBacked')}; "
                f"selectorOnly={scene_adjacency_index.get('currentPairSelectorAdjacencyOnly')}"
            ),
        },
        {
            "kind": "generic-edge-trigger-gate",
            "status": edge_trigger_gap.get("promotionStatus") or "unknown",
            "detail": (
                f"sourceBoundaryCandidates={edge_trigger_gap.get('sourceBoundaryCandidateCount')}; "
                f"autoBoundaryCandidates={edge_trigger_gap.get('autoBoundaryCandidateCount')}; "
                "transitionRelHits="
                f"{edge_trigger_gap.get('transitionLikeDirectRelHitCountInHelperOrController')}; "
                f"routeImmediateHits={edge_trigger_gap.get('directRouteImmediateCountInHelperOrController')}; "
                f"directionLatchRefs={edge_direction_latch.get('directRefCount')}; "
                "routeWindowHits="
                f"{edge_direction_latch.get('transitionLikeWindowRelHitCount')}/"
                f"{edge_direction_latch.get('routeImmediateWindowHitCount')}; "
                "globalTextRefs="
                f"{edge_global_refs.get('mapLoaderDirectRelHitCount')}/"
                f"{edge_global_refs.get('scriptRunnerDirectRelHitCount')}/"
                f"{edge_global_refs.get('selectorTableDirectRelHitCount')}; "
                "scriptRunnerWindows="
                f"{edge_script_runner_context.get('callerCount')}/"
                f"{edge_script_runner_context.get('routeImmediateWindowHitCount')}/"
                f"{edge_script_runner_context.get('mapLoaderWindowRelHitCount')}/"
                f"{edge_script_runner_context.get('selectorTableWindowRelHitCount')}; "
                "selectedPointerWindows="
                f"{edge_selected_pointer_context.get('immediateRefCount')}/"
                f"{edge_selected_pointer_context.get('routeSpecificWindowHitCount')}; "
                "callerWindows="
                f"actor:{edge_actor_controller_caller_windows.get('callerCount')}/"
                f"{edge_actor_controller_caller_windows.get('transitionLikeWindowRelHitCount')}/"
                f"{edge_actor_controller_caller_windows.get('routeImmediateWindowHitCount')};"
                f"helper:{edge_collision_helper_caller_windows.get('callerCount')}/"
                f"{edge_collision_helper_caller_windows.get('transitionLikeWindowRelHitCount')}/"
                f"{edge_collision_helper_caller_windows.get('routeImmediateWindowHitCount')}; "
                "encodedHandler="
                f"{edge_handler_encoded.get('rawScalarCandidateCount')}/"
                f"{edge_handler_encoded.get('transitionRawScalarCandidateCount')}/"
                f"{edge_handler_encoded.get('routeProofRawScalarCandidateCount')}/"
                f"{edge_handler_encoded.get('selectedPointerRawScalarCandidateCount')}/"
                f"{edge_handler_encoded.get('promotingCandidateCount')}; "
                "encodedLocal="
                f"{edge_local_window_encoded.get('rawScalarCandidateCount')}/"
                f"{edge_local_window_encoded.get('transitionRawScalarCandidateCount')}/"
                f"{edge_local_window_encoded.get('routeProofRawScalarCandidateCount')}/"
                f"{edge_local_window_encoded.get('selectedPointerRawScalarCandidateCount')}/"
                f"{edge_local_window_encoded.get('promotingCandidateCount')}; "
                "encodedCallGraph="
                f"{edge_call_graph_encoded.get('rawScalarCandidateCount')}/"
                f"{edge_call_graph_encoded.get('transitionRawScalarCandidateCount')}/"
                f"{edge_call_graph_encoded.get('routeProofRawScalarCandidateCount')}/"
                f"{edge_call_graph_encoded.get('selectedPointerRawScalarCandidateCount')}/"
                f"{edge_call_graph_encoded.get('promotingCandidateCount')}; "
                "encodedContrast="
                f"{edge_global_contrast_encoded.get('rawScalarCandidateCount')}/"
                f"{edge_global_contrast_encoded.get('transitionRawScalarCandidateCount')}/"
                f"{edge_global_contrast_encoded.get('routeProofRawScalarCandidateCount')}/"
                f"{edge_global_contrast_encoded.get('selectedPointerRawScalarCandidateCount')}/"
                f"{edge_global_contrast_encoded.get('promotingCandidateCount')}; "
                "callGraph="
                f"{edge_direct_call_graph.get('classification')}/"
                f"{edge_direct_call_graph.get('reachableFunctionCount')}/"
                f"{edge_direct_call_graph.get('directCallEdgeCount')}/"
                f"{edge_direct_call_graph.get('transitionTargetReachableCount')}/"
                f"{edge_direct_call_graph.get('transitionTargetHitCount')}/"
                f"{edge_direct_call_graph.get('routeImmediateHitCount')}/"
                f"{edge_direct_call_graph.get('indirectCallLikeByteCount')}; "
                "indirectGraph="
                f"{edge_direct_call_graph.get('indirectCallGraphRejectionClassification')}/"
                f"{edge_direct_call_graph.get('indirectCallGraphIndexedJumpTableCandidateCount')}/"
                f"{edge_direct_call_graph.get('indirectCallGraphIndexedJumpTableEntryCount')}/"
                f"{edge_direct_call_graph.get('indirectCallGraphTransitionTargetHitCount')}/"
                f"{edge_direct_call_graph.get('indirectCallGraphRouteImmediateHitCount')}; "
                "callGraphSensitivity="
                f"{edge_call_graph_sensitivity.get('maxDepthChecked')}/"
                f"{edge_call_graph_sensitivity.get('proofAbsentAcrossCheckedDepths')}/"
                f"{edge_call_graph_sensitivity.get('countsStableAtAndBeyondDefaultDepth')}; "
                f"promotionAllowed={edge_trigger_gap.get('promotionAllowed')}; "
                f"promotionStatus={edge_trigger_gap.get('promotionStatus')}"
            ),
        },
        {
            "kind": "confirmed-pattern-contrast",
            "status": "not-confirmed-like",
            "detail": (
                f"confirmedRoute={record_pattern_contrast.get('confirmedReferenceRoute')}; "
                f"frontierStrictEvent={record_pattern_contrast.get('frontierHasStrictEventRecord')}; "
                f"frontierStrictHotspot={record_pattern_contrast.get('frontierHasStrictSourceHotspot')}; "
                f"frontierSelectorOnly={record_pattern_contrast.get('frontierHasOnlySelectorSceneList')}; "
                f"confirmedLike={record_pattern_contrast.get('confirmedLikePatternFound')}"
            ),
        },
        {
            "kind": "manifest-point-scan",
            "status": manifest_point_scan.get("promotionStatus") or "unknown",
            "detail": (
                f"records={len(manifest_point_scan.get('records') or [])}; "
                f"incomingPointTables={manifest_point_scan.get('incomingPointTableCount')}; "
                f"strictSourceHotspot={manifest_point_scan.get('strictSourceHotspotFound')}; "
                f"conclusion={manifest_point_scan.get('conclusion')}"
            ),
        },
        {
            "kind": "current-root-point-scan",
            "status": root_point_scan.get("promotionStatus") or "unknown",
            "detail": (
                f"root={root_point_scan.get('rootVaHex')}; "
                f"pointerLike={root_point_scan.get('pointerLikeCount')}; "
                f"reportedCandidates={root_point_scan.get('reportedCandidateCount')}; "
                f"frontierClusterCandidates={root_point_scan.get('frontierClusterCandidateCount')}; "
                f"exactExitCandidates={root_point_scan.get('exactExitCandidateCount')}; "
                f"scriptLikeCandidates={root_point_scan.get('scriptLikeCandidateCount')}; "
                f"strictSourceHotspot={root_point_scan.get('strictSourceHotspotFound')}"
            ),
        },
        {
            "kind": "confirmed-entry-vs-frontier-context",
            "status": entry_context.get("promotionStatus") or "unknown",
            "detail": (
                f"confirmedEntryCluster={entry_context.get('confirmedEntryClusterHex')}; "
                f"frontierCluster={entry_context.get('frontierClusterHex')}; "
                f"frontierSelectors={csv(entry_context.get('frontierSelectors') or [])}; "
                f"frontierProvenFromConfirmedEntry={entry_context.get('frontierProvenFromConfirmedEntry')}; "
                f"remainingProofs={len(entry_context.get('remainingProofs') or [])}"
            ),
        },
        {
            "kind": "scene-record-cluster-context",
            "status": scene_record_cluster_context.get("promotionStatus") or "unknown",
            "detail": (
                f"sourceRecords={scene_record_cluster_context.get('sourceSceneRecordCount')}; "
                f"sourceStrictOutgoing={scene_record_cluster_context.get('sourceStrictOutgoingClusterCount')}; "
                f"targetStrict={scene_record_cluster_context.get('targetStrictClusterCount')}; "
                f"targetSelectorOnly={scene_record_cluster_context.get('targetSelectorOnlyClusterCount')}; "
                f"sharedStrict={scene_record_cluster_context.get('sourceTargetSharedStrictClusterCount')}; "
                f"sharedSelectorOnly={scene_record_cluster_context.get('sourceTargetSharedSelectorOnlyClusterCount')}; "
                f"frontierEvents={scene_record_cluster_context.get('currentFrontierEventRecordCount')}; "
                f"frontierSelectorRefs={scene_record_cluster_context.get('currentFrontierSaveSelectorRefCount')}; "
                f"strictTargetLink={scene_record_cluster_context.get('strictTargetLinkFound')}"
            ),
        },
        {
            "kind": "selector-context-bridge-scan",
            "status": selector_bridge_refs.get("promotionStatus") or "unknown",
            "detail": (
                f"confirmedToFrontier={(selector_bridge_refs.get('confirmedToFrontier') or {}).get('directBridgeCount', (selector_bridge_refs.get('confirmedToFrontier') or {}).get('dwordHitCount'))}; "
                f"frontierToConfirmed={(selector_bridge_refs.get('frontierToConfirmed') or {}).get('directBridgeCount', (selector_bridge_refs.get('frontierToConfirmed') or {}).get('dwordHitCount'))}; "
                f"bridgeFound={selector_bridge_refs.get('bridgeFound')}; "
                f"limitations={len(selector_bridge_refs.get('limitations') or [])}"
            ),
        },
    ]
    conclusion = (
        "The map1_01a -> map2_02d geometry candidates remain non-promoting. "
        "They have selector-list adjacency and one center-tile signature overlap, "
        "but that overlap is rejected incoming-review-only and there is no route review row, strict event transition, source/target strict link, "
        "route-exit point table, byte-coordinate table, CNS tilemap payload coordinate table, resource payload that decodes to an in-bounds map1_01a hotspot, "
        "generic edge-trigger branch tied to the map loader/selector path, manifest/root point table hit, or bridge from the confirmed entry context to the selector frontier."
    )
    strict_rejection = strict_hotspot_rejection(
        strict_source_hotspot_proof_found,
        strict_hotspot_review_matrix,
        gate,
        center_pair_match_count,
        center_pair_target_linked_match_count,
        center_pair_rejected_review_match_count,
        all_center_pair_matches_rejected_review,
        target_linked_match_count,
        direct_source_target_match_count,
        resource_ref_scan,
        strict_target_link_gap,
        scene_adjacency_index,
        edge_trigger_gap,
        edge_trigger_generic_boundary_transition_proven,
    )
    return {
        "source": strict_hotspot_review_matrix.get("source") or hotspot_gap.get("map") or "map1_01a",
        "target": strict_hotspot_review_matrix.get("target") or hotspot_gap.get("target") or "map2_02d",
        "candidateCount": strict_hotspot_review_matrix.get("candidateCount"),
        "candidateSummaries": candidate_summaries,
        "candidateBlockReasonCounts": candidate_block_reason_counts,
        "candidateAllBlocked": bool(candidate_summaries)
        and all(row.get("promotionStatus") == "blocked" for row in candidate_summaries),
        "geometryStandableCandidateCount": count_where(
            [row.get("tileEvidence") or {} for row in candidate_rows],
            "sourceOriginalStandable",
            True,
        ),
        "targetSpawnStandableCandidateCount": count_where(
            [row.get("tileEvidence") or {} for row in candidate_rows],
            "targetSpawnOriginalStandable",
            True,
        ),
        "transitionReviewRowCount": strict_hotspot_review_matrix.get("transitionReviewRowCount"),
        "eventTransitionCount": strict_hotspot_review_matrix.get("eventTransitionCount"),
        "confirmedIncomingReviewCount": strict_hotspot_review_matrix.get("confirmedIncomingReviewCount"),
        "incomingReviewCount": strict_hotspot_review_matrix.get("incomingReviewCount"),
        "strictSourceCoordinateFound": strict_hotspot_review_matrix.get("strictSourceCoordinateFound"),
        "tileHotspotConfirmed": strict_hotspot_review_matrix.get("tileHotspotConfirmed"),
        "allCoordinateRefsNonPromotable": gate.get("allCoordinateRefsNonPromotable"),
        "allVariantScansNonPromotable": gate.get("allVariantScansNonPromotable"),
        "lowNibbleMatchCount": gate.get("lowNibbleMatchCount"),
        "tileSignatureOnly": gate.get("tileSignatureOnly"),
        "centerPairStrictEventMatchCount": center_pair_match_count,
        "centerPairSameSourceMatchCount": center_pair_same_source_match_count,
        "centerPairTargetLinkedMatchCount": center_pair_target_linked_match_count,
        "centerPairConfirmedReviewMatchCount": center_pair_confirmed_review_match_count,
        "centerPairRejectedReviewMatchCount": center_pair_rejected_review_match_count,
        "allCenterPairMatchesRejectedReview": all_center_pair_matches_rejected_review,
        "centerPairOwnerPairs": center_pair_owner_pairs,
        "centerPairOwnerText": center_pair_owner_text,
        "centerPairMatchSides": center_match_sides,
        "low3x3StrictEventMatchCount": low3x3_match_count,
        "pair3x3StrictEventMatchCount": pair3x3_match_count,
        "targetSpawnTargetMapStrictEventPointCount": target_spawn_strict_event_point_count,
        "targetSpawnCenterPairStrictEventMatchCount": target_spawn_center_pair_match_count,
        "targetSpawnLow3x3StrictEventMatchCount": target_spawn_low3x3_match_count,
        "targetSpawnPair3x3StrictEventMatchCount": target_spawn_pair3x3_match_count,
        "targetSpawnCenterPairTargetMapMatchCount": target_spawn_center_pair_target_map_match_count,
        "targetSpawnLow3x3TargetMapMatchCount": target_spawn_low3x3_target_map_match_count,
        "targetSpawnPair3x3TargetMapMatchCount": target_spawn_pair3x3_target_map_match_count,
        "targetSpawnLow3x3TargetLinkedMatchCount": target_spawn_low3x3_target_linked_match_count,
        "targetSpawnLow3x3ConfirmedReviewMatchCount": (
            target_spawn_low3x3_confirmed_review_match_count
        ),
        "targetSpawnLow3x3RejectedReviewMatchCount": (
            target_spawn_low3x3_rejected_review_match_count
        ),
        "targetSpawnLow3x3OwnerPairs": target_spawn_low3x3_owner_pairs,
        "targetSpawnLow3x3GenericOnly": target_spawn_low3x3_generic_only,
        "allTargetSpawnCenterPairMatchesZero": all_target_spawn_center_pair_matches_zero,
        "allTargetSpawnPair3x3MatchesZero": all_target_spawn_pair3x3_matches_zero,
        "allTargetSpawnTargetMapStrictEventsZero": all_target_spawn_target_map_strict_events_zero,
        "targetLinkedStrictEventMatchCount": target_linked_match_count,
        "directSourceTargetStrictEventMatchCount": direct_source_target_match_count,
        "confirmedReviewPair3x3MatchCount": confirmed_pair_match_count,
        "tileSignaturePromotes": strict_event_tile_signature_scan.get("tileSignaturePromotes"),
        "spanSequenceHitCount": exit_coordinate_variant_scan.get("spanSequenceHitCount"),
        "xyRowSequenceHitCount": exit_coordinate_variant_scan.get("xyRowSequenceHitCount"),
        "yxOpcodeSequenceHitCount": exit_coordinate_variant_scan.get("yxOpcodeSequenceHitCount"),
        "targetSpawnCoordinateScanCount": exit_coordinate_variant_scan.get(
            "targetSpawnVariantScanCount"
        ),
        "targetSpawnCoordinateHitCount": exit_coordinate_variant_scan.get(
            "targetSpawnHitCount"
        ),
        "targetSpawnCoordinateInterestingHitCount": exit_coordinate_variant_scan.get(
            "targetSpawnInterestingHitCount"
        ),
        "targetSpawnCoordinateCurrentRootHitCount": exit_coordinate_variant_scan.get(
            "targetSpawnCurrentRootHitCount"
        ),
        "targetSpawnCoordinateCharacterDescriptorHitCount": exit_coordinate_variant_scan.get(
            "targetSpawnCharacterDescriptorHitCount"
        ),
        "targetSpawnCoordinateCurrentRootClassificationCounts": exit_coordinate_variant_scan.get(
            "targetSpawnCurrentRootClassificationCounts"
        ),
        "targetSpawnCoordinateCharacterDescriptorClassificationCounts": exit_coordinate_variant_scan.get(
            "targetSpawnCharacterDescriptorClassificationCounts"
        ),
        "targetSpawnCoordinatePromotableHitCount": exit_coordinate_variant_scan.get(
            "targetSpawnPromotableHitCount"
        ),
        "targetSpawnCoordinateInterestingPromotableHitCount": exit_coordinate_variant_scan.get(
            "targetSpawnInterestingPromotableHitCount"
        ),
        "targetSpawnCoordinateAllInterestingHitsNonPromotable": exit_coordinate_variant_scan.get(
            "targetSpawnAllInterestingHitsNonPromotable"
        ),
        "targetSpawnStrictCoordinateEvidenceFound": exit_coordinate_variant_scan.get(
            "targetSpawnStrictCoordinateEvidenceFound"
        ),
        "byteCoordinateScanCount": exit_byte_coordinate_scan.get("bytePairScanCount"),
        "byteCoordinateSequenceScanCount": (
            (exit_byte_coordinate_scan.get("axisSequenceScanCount") or 0)
            + (exit_byte_coordinate_scan.get("spanSequenceScanCount") or 0)
        ),
        "byteCoordinateHitCount": exit_byte_coordinate_scan.get("bytePairHitCount"),
        "byteCoordinateSequenceHitCount": byte_coordinate_sequence_hit_count,
        "byteCoordinateStrictSourceTargetHitCount": exit_byte_coordinate_scan.get(
            "strictSourceTargetByteHitCount"
        ),
        "byteCoordinateStrictEventOtherHitCount": exit_byte_coordinate_scan.get(
            "strictEventOtherByteHitCount"
        ),
        "byteCoordinateCurrentSelectorRootHitCount": exit_byte_coordinate_scan.get(
            "currentSelectorRootByteHitCount"
        ),
        "byteCoordinateTextCodeHitCount": exit_byte_coordinate_scan.get("textCodeByteHitCount"),
        "strictByteCoordinateEvidenceFound": exit_byte_coordinate_scan.get(
            "strictByteCoordinateEvidenceFound"
        ),
        "targetSpawnByteCoordinateScanCount": exit_byte_coordinate_scan.get(
            "targetSpawnBytePairScanCount"
        ),
        "targetSpawnByteCoordinateHitCount": exit_byte_coordinate_scan.get(
            "targetSpawnBytePairHitCount"
        ),
        "targetSpawnByteCoordinateStrictSourceTargetHitCount": exit_byte_coordinate_scan.get(
            "targetSpawnStrictSourceTargetByteHitCount"
        ),
        "targetSpawnByteCoordinateStrictEventOtherHitCount": exit_byte_coordinate_scan.get(
            "targetSpawnStrictEventOtherByteHitCount"
        ),
        "targetSpawnByteCoordinateCurrentSelectorRootHitCount": exit_byte_coordinate_scan.get(
            "targetSpawnCurrentSelectorRootByteHitCount"
        ),
        "targetSpawnByteCoordinateTextCodeHitCount": exit_byte_coordinate_scan.get(
            "targetSpawnTextCodeByteHitCount"
        ),
        "targetSpawnStrictByteCoordinateEvidenceFound": exit_byte_coordinate_scan.get(
            "targetSpawnStrictByteCoordinateEvidenceFound"
        ),
        "byteCoordinatePromotionStatus": exit_byte_coordinate_scan.get("promotionStatus"),
        "cnsPayloadSourceWidth": (exit_cns_payload_scan.get("sourceCns") or {}).get("width"),
        "cnsPayloadSourceHeight": (exit_cns_payload_scan.get("sourceCns") or {}).get("height"),
        "cnsPayloadDecodedSize": (exit_cns_payload_scan.get("sourceCns") or {}).get(
            "decodedSize"
        ),
        "cnsPayloadBytePairScanCount": exit_cns_payload_scan.get("bytePairScanCount"),
        "cnsPayloadWordPairScanCount": exit_cns_payload_scan.get("wordPairScanCount"),
        "cnsPayloadPackedU32ScanCount": exit_cns_payload_scan.get("packedU32ScanCount"),
        "cnsPayloadSequenceScanCount": (
            (exit_cns_payload_scan.get("byteSequenceScanCount") or 0)
            + (exit_cns_payload_scan.get("wordSequenceScanCount") or 0)
        ),
        "cnsPayloadBytePairHitCount": exit_cns_payload_scan.get("bytePairHitCount"),
        "cnsPayloadWordPairHitCount": exit_cns_payload_scan.get("wordPairHitCount"),
        "cnsPayloadPackedU32HitCount": exit_cns_payload_scan.get("packedU32HitCount"),
        "cnsPayloadSequenceHitCount": cns_payload_sequence_hit_count,
        "cnsPayloadHeaderHitCount": exit_cns_payload_scan.get("headerHitCount"),
        "cnsPayloadLayerHitCount": exit_cns_payload_scan.get("layerHitCount"),
        "cnsPayloadOutsideStructuredHitCount": exit_cns_payload_scan.get(
            "outsideStructuredHitCount"
        ),
        "strictCnsCoordinateEvidenceFound": exit_cns_payload_scan.get(
            "strictCnsCoordinateEvidenceFound"
        ),
        "cnsPayloadPromotionStatus": exit_cns_payload_scan.get("promotionStatus"),
        "resourceReferenceCount": resource_ref_scan.get("resourceReferenceCount"),
        "resourcePointCandidateCount": resource_ref_scan.get("pointCandidateCount"),
        "resourcePointCandidateClassCounts": resource_ref_scan.get("pointCandidateClassCounts"),
        "routeExitPointCandidateCount": resource_ref_scan.get("routeExitPointCandidateCount"),
        "strictSourceTargetCandidateCount": resource_ref_scan.get("strictSourceTargetCandidateCount"),
        "currentFrontierPointCandidateClassCounts": resource_ref_scan.get(
            "currentFrontierPointCandidateClassCounts"
        ),
        "currentFrontierRouteExitPointHitCount": resource_ref_scan.get(
            "currentFrontierRouteExitPointHitCount"
        ),
        "currentFrontierNonRouteSingletonPointCandidateCount": resource_ref_scan.get(
            "currentFrontierNonRouteSingletonPointCandidateCount"
        ),
        "sourceRecordVaHex": scene_payload_context.get("sourceRecordVaHex"),
        "targetRecordVaHex": scene_payload_context.get("targetRecordVaHex"),
        "payloadCount": len(scene_payload_context.get("payloads") or []),
        "payloadSourceInBoundsPointCount": frontier_payload_shape.get("sourceInBoundsPointCount"),
        "payloadTextRefCount": frontier_payload_shape.get("payloadTextRefCount"),
        "payloadsFitPairedImages": frontier_payload_shape.get("allPayloadsFitPairedImages"),
        "readerBranchClassification": frontier_reader_branch_context.get("classification"),
        "readerBranchRuntimeSelectionProven": frontier_reader_branch_context.get("runtimeSelectionProven"),
        "readerBranchSiblingFieldMapTargetCount": frontier_reader_branch_context.get(
            "siblingFieldMapTargetCount"
        ),
        "directStrictEventTransitionCount": strict_target_link_gap.get("directStrictEventTransitionCount"),
        "sourceIncomingOnlyStrictClusterCount": strict_target_link_gap.get(
            "sourceIncomingOnlyStrictClusterCount"
        ),
        "sourceOutgoingStrictClusterCount": strict_target_link_gap.get("sourceOutgoingStrictClusterCount"),
        "targetStrictClusterCount": strict_target_link_gap.get("targetStrictClusterCount"),
        "targetSelectorOnlyClusterCount": strict_target_link_gap.get("targetSelectorOnlyClusterCount"),
        "targetSelectorOnlySourceOverlapCount": strict_target_link_gap.get(
            "targetSelectorOnlySourceOverlapCount"
        ),
        "targetSelectorOnlySourceTargetRoutePairClusterCount": strict_target_link_gap.get(
            "targetSelectorOnlySourceTargetRoutePairClusterCount"
        ),
        "targetSelectorOnlyCurrentFrontierClusterCount": strict_target_link_gap.get(
            "targetSelectorOnlyCurrentFrontierClusterCount"
        ),
        "currentFrontierManifestMapCount": strict_target_link_gap.get(
            "currentFrontierManifestMapCount"
        ),
        "currentFrontierRoutePairCount": strict_target_link_gap.get("currentFrontierRoutePairCount"),
        "currentFrontierSourceOutgoingRoutePairCount": strict_target_link_gap.get(
            "currentFrontierSourceOutgoingRoutePairCount"
        ),
        "currentFrontierTargetIncomingRoutePairCount": strict_target_link_gap.get(
            "currentFrontierTargetIncomingRoutePairCount"
        ),
        "currentFrontierSourceTargetRoutePairCount": strict_target_link_gap.get(
            "currentFrontierSourceTargetRoutePairCount"
        ),
        "currentFrontierClusterIsSelectorOnly": strict_target_link_gap.get(
            "currentFrontierClusterIsSelectorOnly"
        ),
        "strictTargetLinkFound": strict_target_link_gap.get("strictTargetLinkFound"),
        "currentPairOccurrenceCount": scene_adjacency_index.get("currentPairOccurrenceCount"),
        "currentPairSelectorAdjacencyOnly": scene_adjacency_index.get(
            "currentPairSelectorAdjacencyOnly"
        ),
        "currentPairStrictEventBacked": scene_adjacency_index.get("currentPairStrictEventBacked"),
        "currentPairConfirmedReviewBacked": scene_adjacency_index.get(
            "currentPairConfirmedReviewBacked"
        ),
        "edgeTriggerPromotionAllowed": edge_trigger_gap.get("promotionAllowed"),
        "edgeTriggerPromotionStatus": edge_trigger_gap.get("promotionStatus"),
        "edgeTriggerSourceBoundaryCandidateCount": edge_trigger_gap.get(
            "sourceBoundaryCandidateCount"
        ),
        "edgeTriggerAutoBoundaryCandidateCount": edge_trigger_gap.get(
            "autoBoundaryCandidateCount"
        ),
        "edgeTriggerRouteCandidateCount": edge_trigger_gap.get("routeCandidateCount"),
        "edgeTriggerTransitionLikeDirectRelHitCount": edge_trigger_gap.get(
            "transitionLikeDirectRelHitCountInHelperOrController"
        ),
        "edgeTriggerRouteImmediateHitCount": edge_trigger_gap.get(
            "directRouteImmediateCountInHelperOrController"
        ),
        "edgeTriggerDirectionLatchTextRefCount": edge_direction_latch.get("directRefCount"),
        "edgeTriggerDirectionLatchRouteWindowRelHitCount": edge_direction_latch.get(
            "transitionLikeWindowRelHitCount"
        ),
        "edgeTriggerDirectionLatchRouteWindowImmediateHitCount": edge_direction_latch.get(
            "routeImmediateWindowHitCount"
        ),
        "edgeTriggerGlobalMapLoaderRelHitCount": edge_global_refs.get(
            "mapLoaderDirectRelHitCount"
        ),
        "edgeTriggerGlobalScriptRunnerRelHitCount": edge_global_refs.get(
            "scriptRunnerDirectRelHitCount"
        ),
        "edgeTriggerGlobalSelectorTableRelHitCount": edge_global_refs.get(
            "selectorTableDirectRelHitCount"
        ),
        "edgeTriggerScriptRunnerCallerCount": edge_script_runner_context.get("callerCount"),
        "edgeTriggerScriptRunnerRouteWindowImmediateHitCount": edge_script_runner_context.get(
            "routeImmediateWindowHitCount"
        ),
        "edgeTriggerScriptRunnerMapLoaderWindowRelHitCount": edge_script_runner_context.get(
            "mapLoaderWindowRelHitCount"
        ),
        "edgeTriggerScriptRunnerSelectorTableWindowRelHitCount": edge_script_runner_context.get(
            "selectorTableWindowRelHitCount"
        ),
        "edgeTriggerScriptRunnerActorControllerRangeCallerCount": edge_script_runner_context.get(
            "actorControllerRangeCallerCount"
        ),
        "edgeTriggerScriptRunnerCollisionHelperRangeCallerCount": edge_script_runner_context.get(
            "collisionHelperRangeCallerCount"
        ),
        "edgeTriggerSelectedPointerImmediateRefCount": edge_selected_pointer_context.get(
            "immediateRefCount"
        ),
        "edgeTriggerSelectedPointerRouteSpecificWindowHitCount": edge_selected_pointer_context.get(
            "routeSpecificWindowHitCount"
        ),
        "edgeTriggerSelectedPointerCurrentRootWindowImmediateHitCount": edge_selected_pointer_context.get(
            "currentSelectorRootImmediateWindowHitCount"
        ),
        "edgeTriggerSelectedPointerSourceStringWindowImmediateHitCount": edge_selected_pointer_context.get(
            "sourceMapStringImmediateWindowHitCount"
        ),
        "edgeTriggerSelectedPointerTargetStringWindowImmediateHitCount": edge_selected_pointer_context.get(
            "targetMapStringImmediateWindowHitCount"
        ),
        "edgeTriggerSelectedPointerMapLoaderWindowRelHitCount": edge_selected_pointer_context.get(
            "mapLoaderWindowRelHitCount"
        ),
        "edgeTriggerSelectedPointerScriptRunnerWindowRelHitCount": edge_selected_pointer_context.get(
            "scriptRunnerWindowRelHitCount"
        ),
        "edgeTriggerSelectedPointerSelectorTableWindowRelHitCount": edge_selected_pointer_context.get(
            "selectorTableWindowRelHitCount"
        ),
        "edgeTriggerHandlerEncodedTargetClassification": edge_handler_encoded.get(
            "classification"
        ),
        "edgeTriggerHandlerEncodedTargetRawScalarCandidateCount": edge_handler_encoded.get(
            "rawScalarCandidateCount"
        ),
        "edgeTriggerHandlerEncodedTargetTransitionRawScalarCandidateCount": edge_handler_encoded.get(
            "transitionRawScalarCandidateCount"
        ),
        "edgeTriggerHandlerEncodedTargetRouteProofRawScalarCandidateCount": edge_handler_encoded.get(
            "routeProofRawScalarCandidateCount"
        ),
        "edgeTriggerHandlerEncodedTargetSelectedPointerRawScalarCandidateCount": edge_handler_encoded.get(
            "selectedPointerRawScalarCandidateCount"
        ),
        "edgeTriggerHandlerEncodedTargetPromotingCandidateCount": edge_handler_encoded.get(
            "promotingCandidateCount"
        ),
        "edgeTriggerLocalWindowEncodedTargetClassification": edge_local_window_encoded.get(
            "classification"
        ),
        "edgeTriggerLocalWindowEncodedTargetRawScalarCandidateCount": edge_local_window_encoded.get(
            "rawScalarCandidateCount"
        ),
        "edgeTriggerLocalWindowEncodedTargetTransitionRawScalarCandidateCount": edge_local_window_encoded.get(
            "transitionRawScalarCandidateCount"
        ),
        "edgeTriggerLocalWindowEncodedTargetRouteProofRawScalarCandidateCount": edge_local_window_encoded.get(
            "routeProofRawScalarCandidateCount"
        ),
        "edgeTriggerLocalWindowEncodedTargetSelectedPointerRawScalarCandidateCount": edge_local_window_encoded.get(
            "selectedPointerRawScalarCandidateCount"
        ),
        "edgeTriggerLocalWindowEncodedTargetPromotingCandidateCount": edge_local_window_encoded.get(
            "promotingCandidateCount"
        ),
        "edgeTriggerCallGraphEncodedTargetClassification": edge_call_graph_encoded.get(
            "classification"
        ),
        "edgeTriggerCallGraphEncodedTargetRawScalarCandidateCount": edge_call_graph_encoded.get(
            "rawScalarCandidateCount"
        ),
        "edgeTriggerCallGraphEncodedTargetTransitionRawScalarCandidateCount": edge_call_graph_encoded.get(
            "transitionRawScalarCandidateCount"
        ),
        "edgeTriggerCallGraphEncodedTargetRouteProofRawScalarCandidateCount": edge_call_graph_encoded.get(
            "routeProofRawScalarCandidateCount"
        ),
        "edgeTriggerCallGraphEncodedTargetSelectedPointerRawScalarCandidateCount": edge_call_graph_encoded.get(
            "selectedPointerRawScalarCandidateCount"
        ),
        "edgeTriggerCallGraphEncodedTargetPromotingCandidateCount": edge_call_graph_encoded.get(
            "promotingCandidateCount"
        ),
        "edgeTriggerGlobalContrastEncodedTargetClassification": edge_global_contrast_encoded.get(
            "classification"
        ),
        "edgeTriggerGlobalContrastEncodedTargetRawScalarCandidateCount": edge_global_contrast_encoded.get(
            "rawScalarCandidateCount"
        ),
        "edgeTriggerGlobalContrastEncodedTargetTransitionRawScalarCandidateCount": edge_global_contrast_encoded.get(
            "transitionRawScalarCandidateCount"
        ),
        "edgeTriggerGlobalContrastEncodedTargetRouteProofRawScalarCandidateCount": edge_global_contrast_encoded.get(
            "routeProofRawScalarCandidateCount"
        ),
        "edgeTriggerGlobalContrastEncodedTargetSelectedPointerRawScalarCandidateCount": edge_global_contrast_encoded.get(
            "selectedPointerRawScalarCandidateCount"
        ),
        "edgeTriggerGlobalContrastEncodedTargetPromotingCandidateCount": edge_global_contrast_encoded.get(
            "promotingCandidateCount"
        ),
        "edgeTriggerActorControllerCallerCount": edge_actor_controller_caller_windows.get(
            "callerCount"
        ),
        "edgeTriggerActorControllerCallerRouteWindowRelHitCount": (
            edge_actor_controller_caller_windows.get("transitionLikeWindowRelHitCount")
        ),
        "edgeTriggerActorControllerCallerRouteWindowImmediateHitCount": (
            edge_actor_controller_caller_windows.get("routeImmediateWindowHitCount")
        ),
        "edgeTriggerCollisionHelperCallerCount": edge_collision_helper_caller_windows.get(
            "callerCount"
        ),
        "edgeTriggerCollisionHelperCallerRouteWindowRelHitCount": (
            edge_collision_helper_caller_windows.get("transitionLikeWindowRelHitCount")
        ),
        "edgeTriggerCollisionHelperCallerRouteWindowImmediateHitCount": (
            edge_collision_helper_caller_windows.get("routeImmediateWindowHitCount")
        ),
        "edgeTriggerDirectCallGraphRejectionClassification": edge_direct_call_graph.get(
            "classification"
        ),
        "edgeTriggerDirectCallGraphProofFound": edge_direct_call_graph.get("proofFound"),
        "edgeTriggerDirectCallGraphReachableFunctionCount": edge_direct_call_graph.get(
            "reachableFunctionCount"
        ),
        "edgeTriggerDirectCallGraphDirectCallEdgeCount": edge_direct_call_graph.get(
            "directCallEdgeCount"
        ),
        "edgeTriggerDirectCallGraphTransitionTargetReachableCount": edge_direct_call_graph.get(
            "transitionTargetReachableCount"
        ),
        "edgeTriggerDirectCallGraphTransitionTargetHitCount": edge_direct_call_graph.get(
            "transitionTargetHitCount"
        ),
        "edgeTriggerDirectCallGraphRouteImmediateHitCount": edge_direct_call_graph.get(
            "routeImmediateHitCount"
        ),
        "edgeTriggerDirectCallGraphIndirectCallLikeByteCount": edge_direct_call_graph.get(
            "indirectCallLikeByteCount"
        ),
        "edgeTriggerDirectCallGraphIndirectRejectionClassification": edge_direct_call_graph.get(
            "indirectCallGraphRejectionClassification"
        ),
        "edgeTriggerDirectCallGraphIndirectProofFound": edge_direct_call_graph.get(
            "indirectCallGraphProofFound"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableCandidateCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableCandidateCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableEntryCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableEntryCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableTargetCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableTargetCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableUniqueTargetCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableUniqueTargetCount"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableTargetClassCounts": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableTargetClassCounts"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableAllTargetsLocalToEdgeHandlers": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableAllTargetsLocalToEdgeHandlers"
        ),
        "edgeTriggerDirectCallGraphIndirectIndexedJumpTableOutsideEdgeHandlerTargetCount": edge_direct_call_graph.get(
            "indirectCallGraphIndexedJumpTableOutsideEdgeHandlerTargetCount"
        ),
        "edgeTriggerDirectCallGraphIndirectTransitionTargetHitCount": edge_direct_call_graph.get(
            "indirectCallGraphTransitionTargetHitCount"
        ),
        "edgeTriggerDirectCallGraphIndirectRouteImmediateHitCount": edge_direct_call_graph.get(
            "indirectCallGraphRouteImmediateHitCount"
        ),
        "edgeTriggerDirectCallGraphDepthSensitivityMaxDepthChecked": edge_call_graph_sensitivity.get(
            "maxDepthChecked"
        ),
        "edgeTriggerDirectCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths": (
            edge_call_graph_sensitivity.get("proofAbsentAcrossCheckedDepths")
        ),
        "edgeTriggerDirectCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth": (
            edge_call_graph_sensitivity.get("countsStableAtAndBeyondDefaultDepth")
        ),
        "edgeTriggerGenericBoundaryTransitionProven": (
            edge_trigger_generic_boundary_transition_proven
        ),
        "frontierHasOnlySelectorSceneList": record_pattern_contrast.get(
            "frontierHasOnlySelectorSceneList"
        ),
        "frontierHasStrictEventRecord": record_pattern_contrast.get("frontierHasStrictEventRecord"),
        "frontierHasStrictSourceHotspot": record_pattern_contrast.get(
            "frontierHasStrictSourceHotspot"
        ),
        "confirmedLikePatternFound": record_pattern_contrast.get("confirmedLikePatternFound"),
        "manifestPointScanRecordCount": len(manifest_point_scan.get("records") or []),
        "manifestPointScanIncomingPointTableCount": manifest_point_scan.get(
            "incomingPointTableCount"
        ),
        "manifestPointScanStrictSourceHotspotFound": manifest_point_scan.get(
            "strictSourceHotspotFound"
        ),
        "manifestPointScanPromotionStatus": manifest_point_scan.get("promotionStatus"),
        "rootPointScanPointerLikeCount": root_point_scan.get("pointerLikeCount"),
        "rootPointScanReportedCandidateCount": root_point_scan.get("reportedCandidateCount"),
        "rootPointScanFrontierClusterCandidateCount": root_point_scan.get(
            "frontierClusterCandidateCount"
        ),
        "rootPointScanExactExitCandidateCount": root_point_scan.get("exactExitCandidateCount"),
        "rootPointScanScriptLikeCandidateCount": root_point_scan.get("scriptLikeCandidateCount"),
        "rootPointScanStrictSourceHotspotFound": root_point_scan.get("strictSourceHotspotFound"),
        "rootPointScanPromotionStatus": root_point_scan.get("promotionStatus"),
        "entryContextConfirmedEntryClusterHex": entry_context.get("confirmedEntryClusterHex"),
        "entryContextFrontierClusterHex": entry_context.get("frontierClusterHex"),
        "entryContextFrontierSelectors": entry_context.get("frontierSelectors") or [],
        "entryContextFrontierProvenFromConfirmedEntry": entry_context.get(
            "frontierProvenFromConfirmedEntry"
        ),
        "entryContextPromotionStatus": entry_context.get("promotionStatus"),
        "sceneRecordClusterSourceSceneRecordCount": scene_record_cluster_context.get(
            "sourceSceneRecordCount"
        ),
        "sceneRecordClusterSourceStrictOutgoingClusterCount": (
            scene_record_cluster_context.get("sourceStrictOutgoingClusterCount")
        ),
        "sceneRecordClusterTargetStrictClusterCount": scene_record_cluster_context.get(
            "targetStrictClusterCount"
        ),
        "sceneRecordClusterTargetSelectorOnlyClusterCount": scene_record_cluster_context.get(
            "targetSelectorOnlyClusterCount"
        ),
        "sceneRecordClusterSourceTargetSharedStrictClusterCount": (
            scene_record_cluster_context.get("sourceTargetSharedStrictClusterCount")
        ),
        "sceneRecordClusterSourceTargetSharedSelectorOnlyClusterCount": (
            scene_record_cluster_context.get("sourceTargetSharedSelectorOnlyClusterCount")
        ),
        "sceneRecordClusterCurrentFrontierEventRecordCount": scene_record_cluster_context.get(
            "currentFrontierEventRecordCount"
        ),
        "sceneRecordClusterCurrentFrontierSaveSelectorRefCount": (
            scene_record_cluster_context.get("currentFrontierSaveSelectorRefCount")
        ),
        "sceneRecordClusterStrictTargetLinkFound": scene_record_cluster_context.get(
            "strictTargetLinkFound"
        ),
        "sceneRecordClusterPromotionStatus": scene_record_cluster_context.get(
            "promotionStatus"
        ),
        "selectorBridgeConfirmedToFrontierDirectBridgeCount": (
            (selector_bridge_refs.get("confirmedToFrontier") or {}).get(
                "directBridgeCount",
                (selector_bridge_refs.get("confirmedToFrontier") or {}).get("dwordHitCount"),
            )
        ),
        "selectorBridgeFrontierToConfirmedDirectBridgeCount": (
            (selector_bridge_refs.get("frontierToConfirmed") or {}).get(
                "directBridgeCount",
                (selector_bridge_refs.get("frontierToConfirmed") or {}).get("dwordHitCount"),
            )
        ),
        "selectorBridgeFound": selector_bridge_refs.get("bridgeFound"),
        "selectorBridgeLimitationCount": len(selector_bridge_refs.get("limitations") or []),
        "selectorBridgePromotionStatus": selector_bridge_refs.get("promotionStatus"),
        "proofFound": strict_source_hotspot_proof_found,
        "strictSourceHotspotProofFound": strict_source_hotspot_proof_found,
        "failedStrictHotspotGateIds": failed_strict_hotspot_gate_ids,
        "missingEvidence": missing_evidence,
        "strictHotspotRejectionClassification": strict_rejection["classification"],
        "strictHotspotRejection": strict_rejection,
        "evidenceRefs": EVIDENCE_REFS,
        "evidenceRefCount": len(EVIDENCE_REFS),
        "promotionStatus": promotion_status,
        "evidence": evidence,
        "remainingProofs": [
            "find a strict map1_01a event/coordinate source row for map2_02d",
            "confirm a route review or tile hotspot tied to this source-target pair",
            "or replace selector-only adjacency with equivalent runtime trigger proof",
        ],
        "conclusion": conclusion,
    }


def markdown(summary: dict) -> str:
    target_spawn_low3x3_owner_text = csv(
        [
            f"{row.get('owner')}:{row.get('count')}"
            for row in summary.get("targetSpawnLow3x3OwnerPairs") or []
        ]
    )
    lines = [
        "# Map1_01a Strict Source Hotspot Context",
        "",
        summary["conclusion"],
        "",
        f"- route: `{summary['source']} -> {summary['target']}`",
        f"- candidates: {summary['candidateCount']}",
        f"- candidate all blocked / block reasons: {summary['candidateAllBlocked']} / {summary['candidateBlockReasonCounts']}",
        f"- route review rows / strict events: {summary['transitionReviewRowCount']} / {summary['eventTransitionCount']}",
        f"- strict source coordinate / tile hotspot: {summary['strictSourceCoordinateFound']} / {summary['tileHotspotConfirmed']}",
        f"- coordinate refs blocked / variants blocked: {summary['allCoordinateRefsNonPromotable']} / {summary['allVariantScansNonPromotable']}",
        f"- target-spawn coordinate scans / current-root / character-script / promotable: {summary['targetSpawnCoordinateScanCount']} / {summary['targetSpawnCoordinateCurrentRootHitCount']} / {summary['targetSpawnCoordinateCharacterDescriptorHitCount']} / {summary['targetSpawnCoordinatePromotableHitCount']}",
        f"- target-spawn coordinate current/character classes: {summary['targetSpawnCoordinateCurrentRootClassificationCounts']} / {summary['targetSpawnCoordinateCharacterDescriptorClassificationCounts']}",
        f"- target-spawn strict coordinate evidence found: {summary['targetSpawnStrictCoordinateEvidenceFound']}",
        f"- byte-coordinate scans / sequence hits / strict hits / current-root hits: {summary['byteCoordinateScanCount']} / {summary['byteCoordinateSequenceHitCount']} / {summary['byteCoordinateStrictSourceTargetHitCount']} / {summary['byteCoordinateCurrentSelectorRootHitCount']}",
        f"- target-spawn byte-coordinate scans / strict hits / current-root hits: {summary['targetSpawnByteCoordinateScanCount']} / {summary['targetSpawnByteCoordinateStrictSourceTargetHitCount']} / {summary['targetSpawnByteCoordinateCurrentSelectorRootHitCount']}",
        f"- strict byte-coordinate evidence found: {summary['strictByteCoordinateEvidenceFound']}",
        f"- target-spawn strict byte-coordinate evidence found: {summary['targetSpawnStrictByteCoordinateEvidenceFound']}",
        f"- CNS payload byte/word/packed scans / sequence hits / header-layer-outside hits: {summary['cnsPayloadBytePairScanCount']},{summary['cnsPayloadWordPairScanCount']},{summary['cnsPayloadPackedU32ScanCount']} / {summary['cnsPayloadSequenceHitCount']} / {summary['cnsPayloadHeaderHitCount']},{summary['cnsPayloadLayerHitCount']},{summary['cnsPayloadOutsideStructuredHitCount']}",
        f"- strict CNS coordinate evidence found: {summary['strictCnsCoordinateEvidenceFound']}",
        f"- tile signature center/low3x3/pair matches: {summary['centerPairStrictEventMatchCount']} / {summary['low3x3StrictEventMatchCount']} / {summary['pair3x3StrictEventMatchCount']}",
        f"- target-spawn signature strict-event points / center-low3x3-pair matches: {summary['targetSpawnTargetMapStrictEventPointCount']} / {summary['targetSpawnCenterPairStrictEventMatchCount']}-{summary['targetSpawnLow3x3StrictEventMatchCount']}-{summary['targetSpawnPair3x3StrictEventMatchCount']}",
        f"- target-spawn target-map center/low3x3/pair matches: {summary['targetSpawnCenterPairTargetMapMatchCount']} / {summary['targetSpawnLow3x3TargetMapMatchCount']} / {summary['targetSpawnPair3x3TargetMapMatchCount']}",
        f"- target-spawn low3x3 target-linked/confirmed/rejected matches: {summary['targetSpawnLow3x3TargetLinkedMatchCount']} / {summary['targetSpawnLow3x3ConfirmedReviewMatchCount']} / {summary['targetSpawnLow3x3RejectedReviewMatchCount']}",
        f"- target-spawn low3x3 owners: {target_spawn_low3x3_owner_text}",
        f"- target-spawn low3x3 generic-only: {summary['targetSpawnLow3x3GenericOnly']}",
        f"- all target-spawn center/pair3x3/target-map matches zero: {summary['allTargetSpawnCenterPairMatchesZero']} / {summary['allTargetSpawnPair3x3MatchesZero']} / {summary['allTargetSpawnTargetMapStrictEventsZero']}",
        f"- center-pair owners/same-source/target-linked/confirmed-review/rejected-review: {summary['centerPairOwnerText']} / {summary['centerPairSameSourceMatchCount']} / {summary['centerPairTargetLinkedMatchCount']} / {summary['centerPairConfirmedReviewMatchCount']} / {summary['centerPairRejectedReviewMatchCount']}",
        f"- all center-pair matches rejected-review only: {summary['allCenterPairMatchesRejectedReview']}",
        f"- target-linked/direct-source-target matches: {summary['targetLinkedStrictEventMatchCount']} / {summary['directSourceTargetStrictEventMatchCount']}",
        f"- resource refs / point candidates / route-exit point candidates: {summary['resourceReferenceCount']} / {summary['resourcePointCandidateCount']} / {summary['routeExitPointCandidateCount']}",
        f"- resource point classes: {summary.get('resourcePointCandidateClassCounts')}",
        f"- current frontier point classes / route hits: {summary.get('currentFrontierPointCandidateClassCounts')} / {summary.get('currentFrontierRouteExitPointHitCount')}",
        f"- reader branch: `{summary['readerBranchClassification']}`",
        f"- target selector-only source overlap/source-target pair clusters: {summary['targetSelectorOnlySourceOverlapCount']} / {summary['targetSelectorOnlySourceTargetRoutePairClusterCount']}",
        f"- current frontier maps/route pairs/source outgoing/target incoming: {summary['currentFrontierManifestMapCount']} / {summary['currentFrontierRoutePairCount']} / {summary['currentFrontierSourceOutgoingRoutePairCount']} / {summary['currentFrontierTargetIncomingRoutePairCount']}",
        f"- scene adjacency selector-only: {summary['currentPairSelectorAdjacencyOnly']}",
        f"- generic edge trigger source/auto/transition/route/latch/window/global/script-runner/selected-pointer: {summary['edgeTriggerSourceBoundaryCandidateCount']} / {summary['edgeTriggerAutoBoundaryCandidateCount']} / {summary['edgeTriggerTransitionLikeDirectRelHitCount']} / {summary['edgeTriggerRouteImmediateHitCount']} / {summary['edgeTriggerDirectionLatchTextRefCount']} / {summary['edgeTriggerDirectionLatchRouteWindowRelHitCount']},{summary['edgeTriggerDirectionLatchRouteWindowImmediateHitCount']} / {summary['edgeTriggerGlobalMapLoaderRelHitCount']},{summary['edgeTriggerGlobalScriptRunnerRelHitCount']},{summary['edgeTriggerGlobalSelectorTableRelHitCount']} / {summary['edgeTriggerScriptRunnerCallerCount']},{summary['edgeTriggerScriptRunnerRouteWindowImmediateHitCount']},{summary['edgeTriggerScriptRunnerMapLoaderWindowRelHitCount']},{summary['edgeTriggerScriptRunnerSelectorTableWindowRelHitCount']} / {summary['edgeTriggerSelectedPointerImmediateRefCount']},{summary['edgeTriggerSelectedPointerRouteSpecificWindowHitCount']}",
        f"- generic edge trigger encoded handler/local/callgraph/contrast: {summary['edgeTriggerHandlerEncodedTargetRawScalarCandidateCount']}/{summary['edgeTriggerHandlerEncodedTargetTransitionRawScalarCandidateCount']}/{summary['edgeTriggerHandlerEncodedTargetRouteProofRawScalarCandidateCount']}/{summary['edgeTriggerHandlerEncodedTargetSelectedPointerRawScalarCandidateCount']}/{summary['edgeTriggerHandlerEncodedTargetPromotingCandidateCount']} ({summary['edgeTriggerHandlerEncodedTargetClassification']}) / {summary['edgeTriggerLocalWindowEncodedTargetRawScalarCandidateCount']}/{summary['edgeTriggerLocalWindowEncodedTargetTransitionRawScalarCandidateCount']}/{summary['edgeTriggerLocalWindowEncodedTargetRouteProofRawScalarCandidateCount']}/{summary['edgeTriggerLocalWindowEncodedTargetSelectedPointerRawScalarCandidateCount']}/{summary['edgeTriggerLocalWindowEncodedTargetPromotingCandidateCount']} ({summary['edgeTriggerLocalWindowEncodedTargetClassification']}) / {summary['edgeTriggerCallGraphEncodedTargetRawScalarCandidateCount']}/{summary['edgeTriggerCallGraphEncodedTargetTransitionRawScalarCandidateCount']}/{summary['edgeTriggerCallGraphEncodedTargetRouteProofRawScalarCandidateCount']}/{summary['edgeTriggerCallGraphEncodedTargetSelectedPointerRawScalarCandidateCount']}/{summary['edgeTriggerCallGraphEncodedTargetPromotingCandidateCount']} ({summary['edgeTriggerCallGraphEncodedTargetClassification']}) / {summary['edgeTriggerGlobalContrastEncodedTargetRawScalarCandidateCount']}/{summary['edgeTriggerGlobalContrastEncodedTargetTransitionRawScalarCandidateCount']}/{summary['edgeTriggerGlobalContrastEncodedTargetRouteProofRawScalarCandidateCount']}/{summary['edgeTriggerGlobalContrastEncodedTargetSelectedPointerRawScalarCandidateCount']}/{summary['edgeTriggerGlobalContrastEncodedTargetPromotingCandidateCount']} ({summary['edgeTriggerGlobalContrastEncodedTargetClassification']})",
        f"- generic edge trigger direct call graph: `{summary['edgeTriggerDirectCallGraphRejectionClassification']}` / proof {summary['edgeTriggerDirectCallGraphProofFound']} / functions {summary['edgeTriggerDirectCallGraphReachableFunctionCount']} / edges {summary['edgeTriggerDirectCallGraphDirectCallEdgeCount']} / transition targets {summary['edgeTriggerDirectCallGraphTransitionTargetReachableCount']} / transition hits {summary['edgeTriggerDirectCallGraphTransitionTargetHitCount']} / route immediates {summary['edgeTriggerDirectCallGraphRouteImmediateHitCount']} / indirect-like bytes {summary['edgeTriggerDirectCallGraphIndirectCallLikeByteCount']}",
        f"- generic edge trigger direct call graph depth sensitivity: {summary['edgeTriggerDirectCallGraphDepthSensitivityMaxDepthChecked']} / {summary['edgeTriggerDirectCallGraphDepthSensitivityProofAbsentAcrossCheckedDepths']} / {summary['edgeTriggerDirectCallGraphDepthSensitivityCountsStableAtAndBeyondDefaultDepth']}",
        f"- generic edge trigger indirect graph: `{summary['edgeTriggerDirectCallGraphIndirectRejectionClassification']}` / proof {summary['edgeTriggerDirectCallGraphIndirectProofFound']} / jump tables {summary['edgeTriggerDirectCallGraphIndirectIndexedJumpTableCandidateCount']}/{summary['edgeTriggerDirectCallGraphIndirectIndexedJumpTableEntryCount']} / targets {summary['edgeTriggerDirectCallGraphIndirectIndexedJumpTableTargetCount']}/{summary['edgeTriggerDirectCallGraphIndirectIndexedJumpTableUniqueTargetCount']} / local {summary['edgeTriggerDirectCallGraphIndirectIndexedJumpTableAllTargetsLocalToEdgeHandlers']} / outside {summary['edgeTriggerDirectCallGraphIndirectIndexedJumpTableOutsideEdgeHandlerTargetCount']} / transition hits {summary['edgeTriggerDirectCallGraphIndirectTransitionTargetHitCount']} / route hits {summary['edgeTriggerDirectCallGraphIndirectRouteImmediateHitCount']}",
        f"- generic edge trigger status: `{summary['edgeTriggerPromotionStatus']}`",
        f"- manifest/root point scan: manifest records {summary['manifestPointScanRecordCount']} / incoming point tables {summary['manifestPointScanIncomingPointTableCount']} / manifest strict {summary['manifestPointScanStrictSourceHotspotFound']} / root pointer-like {summary['rootPointScanPointerLikeCount']} / reported {summary['rootPointScanReportedCandidateCount']} / frontier candidates {summary['rootPointScanFrontierClusterCandidateCount']} / exact exits {summary['rootPointScanExactExitCandidateCount']} / script-like {summary['rootPointScanScriptLikeCandidateCount']} / root strict {summary['rootPointScanStrictSourceHotspotFound']}",
        f"- confirmed entry vs frontier: entry `{summary['entryContextConfirmedEntryClusterHex']}` / frontier `{summary['entryContextFrontierClusterHex']}` / selectors `{csv(summary.get('entryContextFrontierSelectors'))}` / proven from entry {summary['entryContextFrontierProvenFromConfirmedEntry']}",
        f"- scene record clusters: source records {summary['sceneRecordClusterSourceSceneRecordCount']} / source outgoing strict {summary['sceneRecordClusterSourceStrictOutgoingClusterCount']} / target strict {summary['sceneRecordClusterTargetStrictClusterCount']} / target selector-only {summary['sceneRecordClusterTargetSelectorOnlyClusterCount']} / shared strict {summary['sceneRecordClusterSourceTargetSharedStrictClusterCount']} / shared selector-only {summary['sceneRecordClusterSourceTargetSharedSelectorOnlyClusterCount']} / frontier events {summary['sceneRecordClusterCurrentFrontierEventRecordCount']} / frontier selector refs {summary['sceneRecordClusterCurrentFrontierSaveSelectorRefCount']} / strict target link {summary['sceneRecordClusterStrictTargetLinkFound']}",
        f"- selector bridge scan: confirmed->frontier {summary['selectorBridgeConfirmedToFrontierDirectBridgeCount']} / frontier->confirmed {summary['selectorBridgeFrontierToConfirmedDirectBridgeCount']} / bridge found {summary['selectorBridgeFound']} / limitations {summary['selectorBridgeLimitationCount']}",
        f"- proof found: {summary['proofFound']}",
        f"- strict source hotspot proof found: {summary['strictSourceHotspotProofFound']}",
        f"- failed strict hotspot gates: `{csv(summary.get('failedStrictHotspotGateIds'))}`",
        f"- strict hotspot rejection classification: `{summary['strictHotspotRejectionClassification']}`",
        f"- evidence refs: {summary['evidenceRefCount']}",
        f"- promotion status: `{summary['promotionStatus']}`",
        "",
        "## Missing Evidence",
        "",
        *[f"- {item}" for item in summary.get("missingEvidence") or []],
        "",
        "## Evidence Refs",
        "",
        "| path | fields |",
        "| --- | --- |",
    ]
    for ref in summary.get("evidenceRefs") or []:
        lines.append(
            f"| `{ref.get('path')}` | {csv(ref.get('fields') or [])} |"
        )
    lines.extend([
        "",
        "## Evidence",
        "",
        "| kind | status | detail |",
        "| --- | --- | --- |",
    ])
    for row in summary.get("evidence") or []:
        lines.append(f"| {row['kind']} | {row['status']} | {row['detail']} |")
    lines.extend(["", "## Candidates", ""])
    lines.append("| side | tile | target | review links | coord status | coord xy/yx | variant hits/root/char | route reviews | strict events | source/target standable | low nibble | block reasons |")
    lines.append("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |")
    for row in summary.get("candidateSummaries") or []:
        tile = row.get("tile") or {}
        target = row.get("targetHint") or {}
        links = []
        if row.get("routeAssistUrl"):
            links.append(f"[route]({row.get('routeAssistUrl')})")
        if row.get("targetReviewUrl"):
            links.append(f"[target]({row.get('targetReviewUrl')})")
        lines.append(
            f"| {row.get('side')} | {tile.get('x')},{tile.get('y')} | "
            f"{target.get('side')}@{target.get('x')},{target.get('y')} | "
            f"{' / '.join(links) or '-'} | "
            f"{row.get('coordinateStatus')} | "
            f"{row.get('coordinateXyHitCount')}/{row.get('coordinateYxHitCount')} | "
            f"{row.get('variantInterestingHitCount')}/"
            f"{row.get('variantCurrentRootHitCount')}/"
            f"{row.get('variantCharacterDescriptorHitCount')} | "
            f"{row.get('routeReviewRowCount')} | {row.get('eventTransitionCount')} | "
            f"{row.get('sourceOriginalStandable')}/{row.get('targetSpawnOriginalStandable')} | "
            f"{row.get('lowNibbleMatch')} | {row.get('blockReasonSummary')} |"
        )
    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:
    def link(url: str | None, label: str) -> str:
        if not url:
            return "-"
        return f'<a href="{html.escape(url)}">{html.escape(label)}</a>'

    target_spawn_low3x3_owner_text = csv(
        [
            f"{row.get('owner')}:{row.get('count')}"
            for row in summary.get("targetSpawnLow3x3OwnerPairs") or []
        ]
    )
    evidence_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(row['kind'])}</td>"
        f"<td>{html.escape(row['status'])}</td>"
        f"<td>{html.escape(row['detail'])}</td>"
        "</tr>"
        for row in summary.get("evidence") or []
    )
    candidate_rows = "\n".join(
        "<tr>"
        f"<td>{html.escape(str(row.get('side')))}</td>"
        f"<td><code>{html.escape(str((row.get('tile') or {}).get('x')))},"
        f"{html.escape(str((row.get('tile') or {}).get('y')))}</code></td>"
        f"<td><code>{html.escape(str((row.get('targetHint') or {}).get('side')))}@"
        f"{html.escape(str((row.get('targetHint') or {}).get('x')))},"
        f"{html.escape(str((row.get('targetHint') or {}).get('y')))}</code></td>"
        f"<td>{link(row.get('routeAssistUrl'), 'route')} / "
        f"{link(row.get('targetReviewUrl'), 'target')}</td>"
        f"<td>{html.escape(str(row.get('coordinateStatus')))}</td>"
        f"<td>{html.escape(str(row.get('coordinateXyHitCount')))}/"
        f"{html.escape(str(row.get('coordinateYxHitCount')))}</td>"
        f"<td>{html.escape(str(row.get('variantInterestingHitCount')))}/"
        f"{html.escape(str(row.get('variantCurrentRootHitCount')))}/"
        f"{html.escape(str(row.get('variantCharacterDescriptorHitCount')))}</td>"
        f"<td>{html.escape(str(row.get('routeReviewRowCount')))}</td>"
        f"<td>{html.escape(str(row.get('eventTransitionCount')))}</td>"
        f"<td>{html.escape(str(row.get('sourceOriginalStandable')))}/"
        f"{html.escape(str(row.get('targetSpawnOriginalStandable')))}</td>"
        f"<td>{html.escape(str(row.get('lowNibbleMatch')))}</td>"
        f"<td>{html.escape(str(row.get('blockReasonSummary')))}</td>"
        "</tr>"
        for row in summary.get("candidateSummaries") or []
    )
    evidence_ref_rows = "\n".join(
        "<tr>"
        f"<td><code>{html.escape(str(ref.get('path')))}</code></td>"
        f"<td>{html.escape(csv(ref.get('fields') or []))}</td>"
        "</tr>"
        for ref in summary.get("evidenceRefs") or []
    )
    proof_items = "\n".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("remainingProofs") or []
    )
    missing_items = "\n".join(
        f"<li>{html.escape(item)}</li>" for item in summary.get("missingEvidence") or []
    )
    return "\n".join([
        "<!doctype html>",
        '<html lang="en">',
        "<head>",
        '  <meta charset="utf-8">',
        "  <title>Map1_01a Strict Source Hotspot 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>Map1_01a Strict Source Hotspot Context</h1>",
        f"  <p>{html.escape(summary['conclusion'])}</p>",
        (
            "  <p><b>Route:</b> "
            f"<code>{html.escape(str(summary['source']))}</code> -&gt; "
            f"<code>{html.escape(str(summary['target']))}</code>; "
            f"candidate all blocked {html.escape(str(summary.get('candidateAllBlocked')))}; "
            f"promotion status <code>{html.escape(str(summary['promotionStatus']))}</code>.</p>"
        ),
        (
            "  <p><b>Proof:</b> "
            f"strict source {html.escape(str(summary['strictSourceCoordinateFound']))}; "
            f"tile hotspot {html.escape(str(summary['tileHotspotConfirmed']))}; "
            "target-spawn coordinate current/character/promotable "
            f"{html.escape(str(summary['targetSpawnCoordinateCurrentRootHitCount']))}/"
            f"{html.escape(str(summary['targetSpawnCoordinateCharacterDescriptorHitCount']))}/"
            f"{html.escape(str(summary['targetSpawnCoordinatePromotableHitCount']))}; "
            "target-spawn classes "
            f"{html.escape(json.dumps(summary['targetSpawnCoordinateCurrentRootClassificationCounts'] or {}, sort_keys=True))}/"
            f"{html.escape(json.dumps(summary['targetSpawnCoordinateCharacterDescriptorClassificationCounts'] or {}, sort_keys=True))}; "
            f"byte-coordinate strict/current/sequence "
            f"{html.escape(str(summary['byteCoordinateStrictSourceTargetHitCount']))}/"
            f"{html.escape(str(summary['byteCoordinateCurrentSelectorRootHitCount']))}/"
            f"{html.escape(str(summary['byteCoordinateSequenceHitCount']))}; "
            "target byte-coordinate strict/current "
            f"{html.escape(str(summary['targetSpawnByteCoordinateStrictSourceTargetHitCount']))}/"
            f"{html.escape(str(summary['targetSpawnByteCoordinateCurrentSelectorRootHitCount']))}; "
            "CNS payload byte/word/packed/sequence/header-layer-outside "
            f"{html.escape(str(summary['cnsPayloadBytePairHitCount']))}/"
            f"{html.escape(str(summary['cnsPayloadWordPairHitCount']))}/"
            f"{html.escape(str(summary['cnsPayloadPackedU32HitCount']))}/"
            f"{html.escape(str(summary['cnsPayloadSequenceHitCount']))}/"
            f"{html.escape(str(summary['cnsPayloadHeaderHitCount']))},"
            f"{html.escape(str(summary['cnsPayloadLayerHitCount']))},"
            f"{html.escape(str(summary['cnsPayloadOutsideStructuredHitCount']))}; "
            f"center matches {html.escape(str(summary['centerPairStrictEventMatchCount']))}; "
            f"center owners {html.escape(str(summary['centerPairOwnerText']))}; "
            "target-spawn signature strict-events/center/low3x3/pair "
            f"{html.escape(str(summary['targetSpawnTargetMapStrictEventPointCount']))}/"
            f"{html.escape(str(summary['targetSpawnCenterPairStrictEventMatchCount']))}/"
            f"{html.escape(str(summary['targetSpawnLow3x3StrictEventMatchCount']))}/"
            f"{html.escape(str(summary['targetSpawnPair3x3StrictEventMatchCount']))}; "
            "target-spawn target-map center/low3x3/pair "
            f"{html.escape(str(summary['targetSpawnCenterPairTargetMapMatchCount']))}/"
            f"{html.escape(str(summary['targetSpawnLow3x3TargetMapMatchCount']))}/"
            f"{html.escape(str(summary['targetSpawnPair3x3TargetMapMatchCount']))}; "
            "target-spawn low3x3 target-linked/confirmed/rejected "
            f"{html.escape(str(summary['targetSpawnLow3x3TargetLinkedMatchCount']))}/"
            f"{html.escape(str(summary['targetSpawnLow3x3ConfirmedReviewMatchCount']))}/"
            f"{html.escape(str(summary['targetSpawnLow3x3RejectedReviewMatchCount']))}; "
            "target-spawn low3x3 owners "
            f"{html.escape(target_spawn_low3x3_owner_text)}; "
            "target-spawn low3x3 generic-only "
            f"{html.escape(str(summary['targetSpawnLow3x3GenericOnly']))}; "
            f"center same-source/target-linked/confirmed "
            f"{html.escape(str(summary['centerPairSameSourceMatchCount']))}/"
            f"{html.escape(str(summary['centerPairTargetLinkedMatchCount']))}/"
            f"{html.escape(str(summary['centerPairConfirmedReviewMatchCount']))}; "
            f"center rejected-review {html.escape(str(summary['centerPairRejectedReviewMatchCount']))}; "
            f"all center rejected-review {html.escape(str(summary['allCenterPairMatchesRejectedReview']))}; "
            f"target-linked matches {html.escape(str(summary['targetLinkedStrictEventMatchCount']))}; "
            "resource point classes "
            f"{html.escape(str(summary.get('resourcePointCandidateClassCounts')))}; "
            "current frontier point classes/route hits "
            f"{html.escape(str(summary.get('currentFrontierPointCandidateClassCounts')))}/"
            f"{html.escape(str(summary.get('currentFrontierRouteExitPointHitCount')))}; "
            "target selector-only source overlap "
            f"{html.escape(str(summary['targetSelectorOnlySourceOverlapCount']))}; "
            "current frontier maps/route pairs/source outgoing/target incoming "
            f"{html.escape(str(summary['currentFrontierManifestMapCount']))}/"
            f"{html.escape(str(summary['currentFrontierRoutePairCount']))}/"
            f"{html.escape(str(summary['currentFrontierSourceOutgoingRoutePairCount']))}/"
            f"{html.escape(str(summary['currentFrontierTargetIncomingRoutePairCount']))}; "
            "generic edge trigger source/auto/transition/route/latch/window/global/script-runner/selected-pointer "
            f"{html.escape(str(summary['edgeTriggerSourceBoundaryCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerAutoBoundaryCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerTransitionLikeDirectRelHitCount']))}/"
            f"{html.escape(str(summary['edgeTriggerRouteImmediateHitCount']))}/"
            f"{html.escape(str(summary['edgeTriggerDirectionLatchTextRefCount']))}/"
            f"{html.escape(str(summary['edgeTriggerDirectionLatchRouteWindowRelHitCount']))},"
            f"{html.escape(str(summary['edgeTriggerDirectionLatchRouteWindowImmediateHitCount']))}/"
            f"{html.escape(str(summary['edgeTriggerGlobalMapLoaderRelHitCount']))},"
            f"{html.escape(str(summary['edgeTriggerGlobalScriptRunnerRelHitCount']))},"
            f"{html.escape(str(summary['edgeTriggerGlobalSelectorTableRelHitCount']))}; "
            "scriptRunnerWindows="
            f"{html.escape(str(summary['edgeTriggerScriptRunnerCallerCount']))}/"
            f"{html.escape(str(summary['edgeTriggerScriptRunnerRouteWindowImmediateHitCount']))}/"
            f"{html.escape(str(summary['edgeTriggerScriptRunnerMapLoaderWindowRelHitCount']))}/"
            f"{html.escape(str(summary['edgeTriggerScriptRunnerSelectorTableWindowRelHitCount']))}; "
            "selectedPointerWindows="
            f"{html.escape(str(summary['edgeTriggerSelectedPointerImmediateRefCount']))}/"
            f"{html.escape(str(summary['edgeTriggerSelectedPointerRouteSpecificWindowHitCount']))}; "
            "encoded handler/local/callgraph/contrast="
            f"{html.escape(str(summary['edgeTriggerHandlerEncodedTargetRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerHandlerEncodedTargetTransitionRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerHandlerEncodedTargetRouteProofRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerHandlerEncodedTargetSelectedPointerRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerHandlerEncodedTargetPromotingCandidateCount']))};"
            f"{html.escape(str(summary['edgeTriggerLocalWindowEncodedTargetRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerLocalWindowEncodedTargetTransitionRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerLocalWindowEncodedTargetRouteProofRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerLocalWindowEncodedTargetSelectedPointerRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerLocalWindowEncodedTargetPromotingCandidateCount']))};"
            f"{html.escape(str(summary['edgeTriggerCallGraphEncodedTargetRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerCallGraphEncodedTargetTransitionRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerCallGraphEncodedTargetRouteProofRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerCallGraphEncodedTargetSelectedPointerRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerCallGraphEncodedTargetPromotingCandidateCount']))};"
            f"{html.escape(str(summary['edgeTriggerGlobalContrastEncodedTargetRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerGlobalContrastEncodedTargetTransitionRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerGlobalContrastEncodedTargetRouteProofRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerGlobalContrastEncodedTargetSelectedPointerRawScalarCandidateCount']))}/"
            f"{html.escape(str(summary['edgeTriggerGlobalContrastEncodedTargetPromotingCandidateCount']))}; "
            "encoded classes="
            f"{html.escape(str(summary['edgeTriggerHandlerEncodedTargetClassification']))}/"
            f"{html.escape(str(summary['edgeTriggerLocalWindowEncodedTargetClassification']))}/"
            f"{html.escape(str(summary['edgeTriggerCallGraphEncodedTargetClassification']))}/"
            f"{html.escape(str(summary['edgeTriggerGlobalContrastEncodedTargetClassification']))}; "
            f"edge status {html.escape(str(summary['edgeTriggerPromotionStatus']))}; "
            f"proof found {html.escape(str(summary['proofFound']))}; "
            f"strict proof {html.escape(str(summary['strictSourceHotspotProofFound']))}; "
            "failed strict hotspot gates "
            f"<code>{html.escape(csv(summary.get('failedStrictHotspotGateIds')))}</code>; "
            f"evidence refs {html.escape(str(summary.get('evidenceRefCount')))}; "
            f"rejection <code>{html.escape(str(summary['strictHotspotRejectionClassification']))}</code>.</p>"
        ),
        "  <h2>Missing Evidence</h2>",
        f"  <ul>{missing_items}</ul>",
        "  <h2>Evidence Refs</h2>",
        (
            "  <table><thead><tr><th>path</th><th>fields</th></tr></thead>"
            f"<tbody>{evidence_ref_rows}</tbody></table>"
        ),
        "  <h2>Evidence</h2>",
        f"  <table><thead><tr><th>kind</th><th>status</th><th>detail</th></tr></thead><tbody>{evidence_rows}</tbody></table>",
        "  <h2>Candidates</h2>",
        (
            "  <table><thead><tr><th>side</th><th>tile</th><th>target</th><th>review links</th>"
            "<th>coord status</th><th>coord xy/yx</th><th>variant hits/root/char</th><th>route reviews</th>"
            "<th>strict events</th><th>source/target standable</th>"
            f"<th>low nibble</th><th>block reasons</th></tr></thead><tbody>{candidate_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 / "map1_01a_strict_source_hotspot_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("--html-out", type=Path)
    args = parser.parse_args()
    summary = build_summary(
        load_json(args.out_dir / "map1_01a_strict_hotspot_review_matrix.json"),
        load_json(args.out_dir / "map1_01a_strict_event_tile_signature_scan.json"),
        load_json(args.out_dir / "map1_01a_hotspot_gap.json"),
        load_json(args.out_dir / "map1_01a_exit_coordinate_variant_scan.json"),
        load_json(args.out_dir / "map1_01a_exit_byte_coordinate_scan.json"),
        load_json(args.out_dir / "map1_01a_exit_cns_payload_scan.json"),
        load_json(args.out_dir / "map1_01a_resource_ref_scan.json"),
        load_json(args.out_dir / "map1_01a_scene_payload_context.json"),
        load_json(args.out_dir / "map1_01a_record_pattern_contrast.json"),
        load_json(args.out_dir / "map1_01a_strict_target_link_gap.json"),
        load_json(args.out_dir / "save_selector_frontier_reader_branch_context.json"),
        load_json(args.out_dir / "save_selector_frontier_payload_shape.json"),
        load_json(args.out_dir / "save_selector_scene_adjacency_index.json"),
        load_json(args.out_dir / "map1_01a_edge_trigger_gap.json"),
        load_json(args.out_dir / "map1_01a_manifest_point_scan.json"),
        load_json(args.out_dir / "map1_01a_root_point_scan.json"),
        load_json(args.out_dir / "map1_01a_entry_context.json"),
        load_json(args.out_dir / "map1_01a_scene_record_cluster_context.json"),
        load_json(args.out_dir / "map1_01a_selector_bridge_refs.json"),
    )
    json_out = write_outputs(summary, args.out_dir, args.html_out)
    print(
        "wrote map1_01a strict source hotspot context -> "
        f"{json_out}"
    )


if __name__ == "__main__":
    main()
