"""Delivery closure workbench summary.

Builds the product-facing delivery closure view from existing committed,
read-only snapshots. The summary is intentionally compact so the UI does not
need to fan out across five separate endpoints or duplicate blocker math.
"""

from __future__ import annotations

from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo

from src.services.awoooi_gitea_onboarding_warning_step_runtime_enablement_gate import (
    load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate,
)
from src.services.awoooi_gitea_onboarding_warning_step_template_copy_apply_gate import (
    load_latest_awoooi_gitea_onboarding_warning_step_template_copy_apply_gate,
)
from src.services.awoooi_gitea_onboarding_warning_step_template_copy_receipt import (
    load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt,
)
from src.services.awoooi_production_deploy_readback_blocker import (
    load_latest_awoooi_production_deploy_readback_blocker,
)
from src.services.awoooi_status_cleanup_dashboard import (
    load_latest_awoooi_status_cleanup_dashboard,
)
from src.services.backup_dr_readiness_matrix import (
    load_latest_backup_dr_readiness_matrix,
)
from src.services.credential_escrow_evidence_intake_readiness import (
    load_latest_credential_escrow_evidence_intake_readiness,
)
from src.services.gitea_private_inventory_p0_scorecard import (
    load_latest_gitea_private_inventory_p0_scorecard,
)
from src.services.gitea_workflow_runner_health import (
    load_latest_gitea_workflow_runner_health,
)
from src.services.gitea_workflow_runner_owner_attestation_request import (
    load_latest_gitea_workflow_runner_owner_attestation_request,
)
from src.services.p0_cicd_baseline_source_readiness import (
    load_latest_p0_cicd_baseline_source_readiness,
)
from src.services.reboot_auto_recovery_drill_preflight import (
    load_latest_reboot_auto_recovery_drill_preflight,
)
from src.services.reboot_auto_recovery_slo_scorecard import (
    load_latest_reboot_auto_recovery_slo_scorecard,
)
from src.services.runtime_surface_inventory import (
    load_latest_runtime_surface_inventory,
)

_SCHEMA_VERSION = "delivery_closure_workbench_v1"


def load_delivery_closure_workbench() -> dict[str, Any]:
    """Load existing delivery snapshots and return a compact workbench model."""
    status_cleanup = load_latest_awoooi_status_cleanup_dashboard()
    production_deploy = load_latest_awoooi_production_deploy_readback_blocker()
    private_inventory = load_latest_gitea_private_inventory_p0_scorecard()
    cicd_baseline = load_latest_p0_cicd_baseline_source_readiness()
    cicd_template_copy_apply_gate = (
        load_latest_awoooi_gitea_onboarding_warning_step_template_copy_apply_gate()
    )
    cicd_template_copy_receipt = (
        load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt()
    )
    cicd_runtime_enablement_gate = (
        load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate()
    )
    gitea = load_latest_gitea_workflow_runner_health()
    gitea_runner_attestation_request = (
        load_latest_gitea_workflow_runner_owner_attestation_request()
    )
    runtime = load_latest_runtime_surface_inventory()
    backup = load_latest_backup_dr_readiness_matrix()
    credential_escrow_intake = load_latest_credential_escrow_evidence_intake_readiness()
    reboot_slo = load_latest_reboot_auto_recovery_slo_scorecard()
    reboot_drill_preflight = load_latest_reboot_auto_recovery_drill_preflight()
    return build_delivery_closure_workbench(
        status_cleanup=status_cleanup,
        production_deploy=production_deploy,
        private_inventory=private_inventory,
        cicd_baseline=cicd_baseline,
        cicd_template_copy_apply_gate=cicd_template_copy_apply_gate,
        cicd_template_copy_receipt=cicd_template_copy_receipt,
        cicd_runtime_enablement_gate=cicd_runtime_enablement_gate,
        gitea=gitea,
        gitea_runner_attestation_request=gitea_runner_attestation_request,
        runtime=runtime,
        backup=backup,
        credential_escrow_intake=credential_escrow_intake,
        reboot_slo=reboot_slo,
        reboot_drill_preflight=reboot_drill_preflight,
    )


def build_delivery_closure_workbench(
    *,
    status_cleanup: dict[str, Any],
    production_deploy: dict[str, Any],
    private_inventory: dict[str, Any],
    cicd_baseline: dict[str, Any],
    cicd_template_copy_apply_gate: dict[str, Any],
    cicd_template_copy_receipt: dict[str, Any],
    cicd_runtime_enablement_gate: dict[str, Any],
    gitea: dict[str, Any],
    gitea_runner_attestation_request: dict[str, Any],
    runtime: dict[str, Any],
    backup: dict[str, Any],
    credential_escrow_intake: dict[str, Any],
    reboot_slo: dict[str, Any],
    reboot_drill_preflight: dict[str, Any],
) -> dict[str, Any]:
    """Build the delivery workbench response from already validated snapshots."""
    status_summary = _dict(status_cleanup.get("summary"))
    private_inventory_readback = _dict(private_inventory.get("readback"))
    private_inventory_rollups = _dict(private_inventory.get("rollups"))
    private_inventory_boundaries = _dict(private_inventory.get("operation_boundaries"))
    private_inventory_retired_github = _dict(
        private_inventory.get("github_retired_context")
    )
    private_inventory_single_preflight = _dict(
        private_inventory.get("authenticated_inventory_single_preflight_intake")
    )
    private_inventory_single_preflight_boundaries = _dict(
        private_inventory_single_preflight.get("operation_boundaries")
    )
    cicd_baseline_readback = _dict(cicd_baseline.get("readback"))
    cicd_baseline_rollups = _dict(cicd_baseline.get("rollups"))
    cicd_apply_gate_readback = _dict(cicd_template_copy_apply_gate.get("readback"))
    cicd_apply_gate_boundaries = _dict(
        cicd_template_copy_apply_gate.get("operation_boundaries")
    )
    cicd_template_copy_receipt_readback = _dict(
        cicd_template_copy_receipt.get("readback")
    )
    cicd_template_copy_receipt_rollups = _dict(
        cicd_template_copy_receipt.get("rollups")
    )
    cicd_template_copy_receipt_boundaries = _dict(
        cicd_template_copy_receipt.get("operation_boundaries")
    )
    cicd_runtime_enablement_readback = _dict(
        cicd_runtime_enablement_gate.get("readback")
    )
    cicd_runtime_enablement_rollups = _dict(
        cicd_runtime_enablement_gate.get("rollups")
    )
    cicd_runtime_enablement_controlled_apply = _dict(
        cicd_runtime_enablement_gate.get("controlled_apply")
    )
    cicd_runtime_enablement_boundaries = _dict(
        cicd_runtime_enablement_gate.get("operation_boundaries")
    )
    production_deploy_readback = _dict(production_deploy.get("readback"))
    production_deploy_rollups = _dict(production_deploy.get("rollups"))
    production_deploy_runtime_matches_gitops_desired = (
        production_deploy_readback.get("runtime_build_matches_gitops_desired_image_tag")
        is True
    )
    production_deploy_runtime_readback_status = str(
        production_deploy_readback.get("runtime_build_readback_status") or ""
    )
    production_deploy_runtime_committed_drift_accepted = (
        production_deploy_runtime_readback_status
        == "matches_gitops_desired_image_tag_with_committed_deploy_readback_drift"
    )
    production_deploy_runtime_readback_current = (
        production_deploy_runtime_matches_gitops_desired
        and production_deploy_readback.get("desired_main_api_image_tag_readback_status")
        == "ok"
    )
    gitea_status = _dict(gitea.get("program_status"))
    gitea_rollups = _dict(gitea.get("rollups"))
    gitea_runner_request_readback = _dict(
        gitea_runner_attestation_request.get("readback")
    )
    gitea_runner_request_packet = _dict(
        gitea_runner_attestation_request.get("request_packet")
    )
    gitea_runner_request_rollups = _dict(
        gitea_runner_attestation_request.get("rollups")
    )
    gitea_runner_request_boundaries = _dict(
        gitea_runner_attestation_request.get("operation_boundaries")
    )
    runtime_status = _dict(runtime.get("program_status"))
    runtime_rollups = _dict(runtime.get("rollups"))
    backup_status = _dict(backup.get("program_status"))
    backup_rollups = _dict(backup.get("rollups"))
    reboot_readback = _dict(reboot_slo.get("readback"))
    reboot_rollups = _dict(reboot_slo.get("rollups"))
    reboot_stockplatform = _dict(reboot_slo.get("stockplatform_data_freshness"))
    reboot_stockplatform_eod = _dict(reboot_stockplatform.get("eod_window"))
    reboot_stockplatform_recovery_gate = _dict(
        reboot_stockplatform.get("controlled_recovery_gate")
    )
    reboot_drill_readback = _dict(reboot_drill_preflight.get("readback"))
    reboot_drill_rollups = _dict(reboot_drill_preflight.get("rollups"))
    reboot_drill_target_selector = _dict(reboot_drill_preflight.get("target_selector"))
    reboot_drill_boundaries = _dict(reboot_drill_preflight.get("operation_boundaries"))
    reboot_drill_check_mode = _dict(reboot_drill_preflight.get("check_mode"))
    credential_intake_rollups = _dict(credential_escrow_intake.get("rollups"))
    credential_intake_readback = _dict(credential_escrow_intake.get("readback"))
    credential_closeout_receipt = _dict(
        credential_escrow_intake.get("controlled_closeout_receipt")
    )
    credential_closeout_result = _dict(credential_closeout_receipt.get("result"))
    single_preflight_intake = _dict(
        credential_escrow_intake.get("single_preflight_intake")
    )
    single_preflight_boundaries = _dict(
        single_preflight_intake.get("operation_boundaries")
    )

    private_inventory_blockers = _int(
        private_inventory_rollups.get("active_blocker_count")
    )
    reboot_blockers = _int(reboot_rollups.get("active_blocker_count"))
    credential_escrow_required_items = _int(
        credential_intake_rollups.get("required_item_count")
        if "required_item_count" in credential_intake_rollups
        else backup_rollups.get("credential_escrow_required_item_count")
    )
    credential_escrow_missing_items = _int(
        credential_intake_rollups.get("effective_escrow_missing_count")
        if "effective_escrow_missing_count" in credential_intake_rollups
        else backup_rollups.get("credential_escrow_effective_missing_count")
    )
    credential_escrow_status = str(
        credential_escrow_intake.get("status")
        or backup_rollups.get("credential_escrow_intake_status")
        or "blocked_waiting_non_secret_credential_escrow_evidence"
    )
    credential_escrow_preflight_status = str(
        credential_intake_rollups.get("preflight_status")
        or backup_rollups.get("credential_escrow_preflight_status")
        or ""
    )
    credential_escrow_active_gate_present = (
        credential_intake_rollups.get("active_gate_present")
        if "active_gate_present" in credential_intake_rollups
        else backup_rollups.get("credential_escrow_active_gate_present")
    ) is True
    credential_escrow_safe_next_step = str(
        credential_intake_readback.get("safe_next_step")
        or credential_escrow_intake.get("safe_next_step")
        or ""
    )
    credential_escrow_completion = _percent(
        (
            (credential_escrow_required_items - credential_escrow_missing_items)
            / max(credential_escrow_required_items, 1)
        )
        * 100
    )
    backup_blocked_row_ids = _strings(backup_rollups.get("blocked_row_ids"))
    backup_non_credential_blockers = [
        row_id
        for row_id in backup_blocked_row_ids
        if row_id != "credential_escrow_markers"
    ]
    runtime_action_required = set(
        _strings(runtime_rollups.get("action_required_surface_ids"))
    )
    runtime_secret_surfaces = set(_strings(runtime_rollups.get("secret_surface_ids")))

    release_raw_completion = _percent(status_summary.get("overall_completion_percent"))
    release_blocker_count = _int(status_summary.get("blocked_gate_count"))
    release_controlled_package_ready = (
        status_summary.get("controlled_status_cleanup_package_ready") is True
        and release_blocker_count == 0
    )
    release_completion = 100 if release_controlled_package_ready else release_raw_completion

    lanes = [
        {
            "id": "release",
            "source_id": "status_cleanup",
            "completion_percent": release_completion,
            "status": str(status_summary.get("dashboard_status") or "unknown"),
            "blocker_count": release_blocker_count,
            "metric": {
                "kind": "blocked_gate",
                "blocked": release_blocker_count,
                "total": _int(status_summary.get("gate_count")),
                "raw_overall_completion_percent": release_raw_completion,
                "controlled_status_cleanup_package_ready": (
                    release_controlled_package_ready
                ),
            },
            "href": "/governance?tab=automation-inventory",
            "next_action": _first_string(status_cleanup.get("next_actions")),
        },
        {
            "id": "production_deploy",
            "source_id": "production_deploy_readback",
            "completion_percent": _percent(
                100
                if production_deploy_rollups.get("production_image_tag_matches_main")
                is True
                else 40
            ),
            "status": str(production_deploy.get("status") or "unknown"),
            "blocker_count": _int(production_deploy_rollups.get("hard_blocker_count")),
            "metric": {
                "kind": "deploy_readback",
                "observed_source_control_main_short_sha": str(
                    production_deploy_readback.get(
                        "observed_source_control_main_short_sha"
                    )
                    or ""
                ),
                "production_image_tag_short_sha": str(
                    production_deploy_readback.get("production_image_tag_short_sha")
                    or ""
                ),
                "runtime_build_commit_short_sha": str(
                    production_deploy_readback.get("runtime_build_commit_short_sha")
                    or ""
                ),
                "runtime_build_readback_status": str(
                    production_deploy_readback.get("runtime_build_readback_status")
                    or ""
                ),
                "runtime_build_matches_gitops_desired_image_tag": (
                    production_deploy_runtime_matches_gitops_desired
                ),
                "runtime_build_deploy_readback_current": (
                    production_deploy_runtime_readback_current
                ),
                "runtime_build_committed_readback_drift_accepted": (
                    production_deploy_runtime_committed_drift_accepted
                ),
                "runtime_build_matches_committed_source_control_readback": (
                    production_deploy_readback.get(
                        "runtime_build_matches_committed_source_control_readback"
                    )
                    is True
                ),
                "runtime_build_matches_committed_production_image_tag": (
                    production_deploy_readback.get(
                        "runtime_build_matches_committed_production_image_tag"
                    )
                    is True
                ),
                "desired_main_api_image_tag_short_sha": str(
                    production_deploy_readback.get(
                        "desired_main_api_image_tag_short_sha"
                    )
                    or ""
                ),
                "desired_main_api_image_tag_readback_status": str(
                    production_deploy_readback.get(
                        "desired_main_api_image_tag_readback_status"
                    )
                    or ""
                ),
                "production_image_tag_matches_main": production_deploy_readback.get(
                    "production_image_tag_matches_main"
                )
                is True,
                "current_main_cd_run_visible": production_deploy_readback.get(
                    "current_main_cd_run_visible"
                )
                is True,
                "authorized_dispatch_channel_ready": production_deploy_readback.get(
                    "authorized_dispatch_channel_ready"
                )
                is True,
                "manual_run_button_visible": production_deploy_readback.get(
                    "manual_run_button_visible"
                )
                is True,
                "gitea_sign_in_required": production_deploy_readback.get(
                    "gitea_sign_in_required"
                )
                is True,
                "dispatch_without_token_http_status": _int(
                    production_deploy_readback.get(
                        "dispatch_without_token_http_status"
                    )
                ),
                "dispatch_without_token_message": str(
                    production_deploy_readback.get("dispatch_without_token_message")
                    or ""
                ),
                "latest_visible_cd_run_id": str(
                    production_deploy_readback.get("latest_visible_cd_run_id") or ""
                ),
                "latest_visible_cd_run_status": str(
                    production_deploy_readback.get("latest_visible_cd_run_status")
                    or ""
                ),
                "latest_visible_cd_run_jobs_total_count": _int(
                    production_deploy_readback.get(
                        "latest_visible_cd_run_jobs_total_count"
                    )
                ),
                "gitea_actions_list_without_token_http_status": _int(
                    production_deploy_readback.get(
                        "gitea_actions_list_without_token_http_status"
                    )
                ),
                "gitea_actions_list_without_token_message": str(
                    production_deploy_readback.get(
                        "gitea_actions_list_without_token_message"
                    )
                    or ""
                ),
                "latest_visible_waiting_runner_run_id": str(
                    production_deploy_readback.get(
                        "latest_visible_waiting_runner_run_id"
                    )
                    or ""
                ),
                "latest_visible_waiting_runner_workflow": str(
                    production_deploy_readback.get(
                        "latest_visible_waiting_runner_workflow"
                    )
                    or ""
                ),
                "latest_visible_waiting_runner_kind": str(
                    production_deploy_readback.get(
                        "latest_visible_waiting_runner_kind"
                    )
                    or ""
                ),
                "latest_visible_waiting_runner_status": str(
                    production_deploy_readback.get(
                        "latest_visible_waiting_runner_status"
                    )
                    or ""
                ),
                "latest_visible_waiting_runner_label": str(
                    production_deploy_readback.get(
                        "latest_visible_waiting_runner_label"
                    )
                    or ""
                ),
                "public_actions_queue_readback_schema_version": str(
                    production_deploy_readback.get(
                        "public_actions_queue_readback_schema_version"
                    )
                    or ""
                ),
                "public_actions_queue_readback_verifier": str(
                    production_deploy_readback.get(
                        "public_actions_queue_readback_verifier"
                    )
                    or ""
                ),
                "non110_runner_cd_closure_verifier_schema_version": str(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_verifier_schema_version"
                    )
                    or ""
                ),
                "non110_runner_cd_closure_verifier": str(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_verifier"
                    )
                    or ""
                ),
                "non110_runner_cd_closure_status": str(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_status"
                    )
                    or ""
                ),
                "non110_runner_cd_closure_required": production_deploy_readback.get(
                    "non110_runner_cd_closure_required"
                )
                is True,
                "non110_runner_cd_closure_ordered_step_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_ordered_step_count"
                    )
                ),
                "non110_runner_cd_closure_ordered_completed_prefix_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_ordered_completed_prefix_count"
                    )
                ),
                "non110_runner_cd_closure_evidence_completed_step_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_evidence_completed_step_count"
                    )
                ),
                "non110_runner_cd_closure_ordered_completion_percent": _int(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_ordered_completion_percent"
                    )
                ),
                "non110_runner_cd_closure_evidence_completion_percent": _int(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_evidence_completion_percent"
                    )
                ),
                "non110_runner_cd_closure_next_blocked_step_index": _int(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_next_blocked_step_index"
                    )
                ),
                "non110_runner_cd_closure_next_blocked_step_id": str(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_next_blocked_step_id"
                    )
                    or ""
                ),
                "non110_runner_cd_closure_next_blocked_step_action": str(
                    production_deploy_readback.get(
                        "non110_runner_cd_closure_next_blocked_step_action"
                    )
                    or ""
                ),
                "non110_runner_ready": production_deploy_readback.get(
                    "non110_runner_ready"
                )
                is True,
                "non110_runner_prepare_only_source_ready": production_deploy_readback.get(
                    "non110_runner_prepare_only_source_ready"
                )
                is True,
                "non110_runner_safe_registration_helper_ready": production_deploy_readback.get(
                    "non110_runner_safe_registration_helper_ready"
                )
                is True,
                "non110_runner_workflow_labels_aligned": production_deploy_readback.get(
                    "non110_runner_workflow_labels_aligned"
                )
                is True,
                "non110_runner_host_label": str(
                    production_deploy_readback.get("non110_runner_host_label") or ""
                ),
                "non110_runner_ubuntu_label": str(
                    production_deploy_readback.get("non110_runner_ubuntu_label") or ""
                ),
                "non110_runner_online_label_match": production_deploy_readback.get(
                    "non110_runner_online_label_match"
                )
                is True,
                "non110_runner_autostart_path_armed": production_deploy_readback.get(
                    "non110_runner_autostart_path_armed"
                )
                is True,
                "non110_runner_ready_autostart_path_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_ready_autostart_path_count"
                    )
                ),
                "non110_runner_registration_condition_required": production_deploy_readback.get(
                    "non110_runner_registration_condition_required"
                )
                is True,
                "non110_runner_ready_config_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_ready_config_count"
                    )
                ),
                "non110_runner_ready_service_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_ready_service_count"
                    )
                ),
                "non110_runner_ready_registration_count": _int(
                    production_deploy_readback.get(
                        "non110_runner_ready_registration_count"
                    )
                ),
                "non110_runner_safe_next_step": str(
                    production_deploy_readback.get("non110_runner_safe_next_step")
                    or ""
                ),
                "non110_runner_remaining_blocker_count": len(
                    _strings(
                        production_deploy_readback.get(
                            "non110_runner_remaining_blockers"
                        )
                    )
                ),
            },
            "href": "/deployments",
            "next_action": _first_string(production_deploy.get("next_actions")),
        },
        {
            "id": "reboot_auto_recovery",
            "source_id": "reboot_auto_recovery_slo_scorecard",
            "completion_percent": _percent(
                reboot_rollups.get("readiness_percent")
            ),
            "status": str(reboot_slo.get("status") or "unknown"),
            "blocker_count": reboot_blockers,
            "metric": {
                "kind": "reboot_auto_recovery_slo",
                "workplan_id": str(reboot_readback.get("workplan_id") or "P0-006"),
                "target_minutes": _int(reboot_readback.get("target_minutes")),
                "can_claim_all_services_recovered_within_target": reboot_rollups.get(
                    "can_claim_all_services_recovered_within_target"
                )
                is True,
                "active_blockers": _strings(reboot_slo.get("active_blockers")),
                "post_start_blocked": _int(
                    reboot_rollups.get("post_start_blocked")
                ),
                "service_green": reboot_rollups.get("service_green") is True,
                "product_data_green": reboot_rollups.get("product_data_green")
                is True,
                "backup_core_green": reboot_rollups.get("backup_core_green") is True,
                "observed_host_count": _int(
                    reboot_rollups.get("observed_host_count")
                ),
                "missing_host_count": _int(reboot_rollups.get("missing_host_count")),
                "unreachable_host_count": _int(
                    reboot_rollups.get("unreachable_host_count")
                ),
                "stale_host_count": _int(reboot_rollups.get("stale_host_count")),
                "stockplatform_freshness_status": str(
                    reboot_rollups.get("stockplatform_freshness_status") or ""
                ),
                "stockplatform_ingestion_status": str(
                    reboot_rollups.get("stockplatform_ingestion_status") or ""
                ),
                "stockplatform_freshness_blocker_count": _int(
                    reboot_rollups.get("stockplatform_freshness_blocker_count")
                ),
                "stockplatform_ingestion_blocker_count": _int(
                    reboot_rollups.get("stockplatform_ingestion_blocker_count")
                ),
                "stockplatform_freshness_blockers": _strings(
                    reboot_stockplatform.get("freshness_blockers")
                ),
                "stockplatform_ingestion_blockers": _strings(
                    reboot_stockplatform.get("ingestion_blockers")
                ),
                "stockplatform_eod_classification": str(
                    reboot_stockplatform_eod.get("classification") or ""
                ),
                "stockplatform_eod_next_action": str(
                    reboot_stockplatform_eod.get("next_action") or ""
                ),
                "stockplatform_final_retry_window_end_local": str(
                    reboot_stockplatform_eod.get("final_retry_window_end_local") or ""
                ),
                "stockplatform_final_retry_window_passed": reboot_rollups.get(
                    "stockplatform_final_retry_window_passed"
                )
                is True,
                "stockplatform_controlled_recovery_gate_required": reboot_rollups.get(
                    "stockplatform_controlled_recovery_gate_required"
                )
                is True,
                "stockplatform_controlled_recovery_gate_status": str(
                    reboot_stockplatform_recovery_gate.get("status") or ""
                ),
                "drill_preflight_status": str(
                    reboot_drill_preflight.get("status") or ""
                ),
                "drill_preflight_ready": (
                    reboot_drill_rollups.get("preflight_ready") is True
                ),
                "drill_preflight_ready_count": _int(
                    reboot_drill_rollups.get("preflight_ready_count")
                ),
                "drill_preflight_blocker_count": _int(
                    reboot_drill_rollups.get("preflight_blocker_count")
                ),
                "drill_preflight_active_blockers": _strings(
                    reboot_drill_preflight.get("active_blockers")
                ),
                "drill_preflight_break_glass_authorization_required": (
                    reboot_drill_rollups.get("break_glass_authorization_required")
                    is True
                ),
                "drill_preflight_execution_authorized_by_this_endpoint": (
                    reboot_drill_rollups.get("execution_authorized_by_this_endpoint")
                    is True
                ),
                "drill_preflight_host_reboot_authorized_by_this_endpoint": (
                    reboot_drill_rollups.get(
                        "host_reboot_authorized_by_this_endpoint"
                    )
                    is True
                ),
                "drill_preflight_runtime_write_allowed": (
                    reboot_drill_rollups.get("runtime_write_allowed") is True
                ),
                "drill_preflight_target_required_host_count": _int(
                    reboot_drill_rollups.get("target_required_host_count")
                ),
                "drill_preflight_target_observed_host_count": _int(
                    reboot_drill_rollups.get("target_observed_host_count")
                ),
                "drill_preflight_target_missing_host_count": _int(
                    reboot_drill_rollups.get("target_missing_host_count")
                ),
                "drill_preflight_target_unreachable_host_count": _int(
                    reboot_drill_rollups.get("target_unreachable_host_count")
                ),
                "drill_preflight_target_stale_host_count": _int(
                    reboot_drill_rollups.get("target_stale_host_count")
                ),
                "drill_preflight_verify_only_available": (
                    reboot_drill_check_mode.get("verify_only_available") is True
                ),
                "drill_preflight_post_apply_verifier_endpoint": str(
                    reboot_drill_check_mode.get("post_apply_verifier_endpoint") or ""
                ),
                "drill_preflight_safe_next_step": str(
                    reboot_drill_readback.get("safe_next_step")
                    or reboot_drill_preflight.get("safe_next_step")
                    or ""
                ),
                "host_reboot_performed": _dict(
                    reboot_slo.get("operation_boundaries")
                ).get("host_reboot_performed")
                is True,
                "service_restart_performed": _dict(
                    reboot_slo.get("operation_boundaries")
                ).get("service_restart_performed")
                is True,
                "database_write_or_restore_performed": _dict(
                    reboot_slo.get("operation_boundaries")
                ).get("database_write_or_restore_performed")
                is True,
                "secret_value_collection_allowed": _dict(
                    reboot_slo.get("operation_boundaries")
                ).get("secret_value_collection_allowed")
                is True,
                "drill_preflight_secret_value_collection_allowed": (
                    reboot_drill_boundaries.get("secret_value_collection_allowed")
                    is True
                ),
                "drill_preflight_workflow_trigger_performed": (
                    reboot_drill_boundaries.get("workflow_trigger_performed") is True
                ),
            },
            "href": "/operations",
            "next_action": str(reboot_readback.get("safe_next_step") or ""),
        },
        {
            "id": "credential_escrow",
            "source_id": "credential_escrow_evidence_intake_readiness",
            "completion_percent": credential_escrow_completion,
            "status": credential_escrow_status,
            "blocker_count": credential_escrow_missing_items,
            "metric": {
                "kind": "credential_escrow_evidence",
                "workplan_id": "P0-005",
                "required_item_count": credential_escrow_required_items,
                "effective_missing_count": credential_escrow_missing_items,
                "active_gate_present": credential_escrow_active_gate_present,
                "preflight_status": credential_escrow_preflight_status,
                "accepted_item_count": _int(
                    credential_intake_rollups.get("accepted_item_count")
                ),
                "owner_response_received_count": _int(
                    credential_intake_rollups.get("owner_response_received_count")
                ),
                "owner_response_accepted_count": _int(
                    credential_intake_rollups.get("owner_response_accepted_count")
                ),
                "runtime_gate_count": _int(
                    credential_intake_rollups.get("runtime_gate_count")
                ),
                "secret_value_collection_allowed": (
                    credential_intake_rollups.get("secret_value_collection_allowed")
                    is True
                ),
                "credential_marker_write_authorized_count": _int(
                    credential_intake_rollups.get(
                        "credential_marker_write_authorized_count"
                    )
                ),
                "forbidden_true_field_count": _int(
                    credential_intake_rollups.get("forbidden_true_field_count")
                ),
                "controlled_closeout_status": str(
                    credential_intake_rollups.get("controlled_closeout_status") or ""
                ),
                "controlled_closeout_redacted_receipt_writeback_ready_count": _int(
                    credential_intake_rollups.get(
                        "controlled_closeout_redacted_receipt_writeback_ready_count"
                    )
                ),
                "controlled_closeout_source_ref": str(
                    credential_intake_readback.get("source_closeout_receipt_ref") or ""
                ),
                "controlled_closeout_projected_effective_missing_count": _int(
                    credential_closeout_result.get(
                        "projected_effective_escrow_missing_count"
                    )
                ),
                "single_preflight_intake_ready": (
                    credential_escrow_intake.get("single_preflight_intake_ready")
                    is True
                ),
                "single_preflight_intake_ready_count": _int(
                    credential_intake_rollups.get("single_preflight_intake_ready_count")
                ),
                "single_preflight_intake_schema_version": str(
                    single_preflight_intake.get("schema_version") or ""
                ),
                "single_preflight_required_item_count": _int(
                    single_preflight_intake.get("required_item_count")
                ),
                "single_preflight_secret_value_collection_allowed": (
                    single_preflight_boundaries.get("secret_value_collection_allowed")
                    is True
                ),
                "single_preflight_credential_marker_write_performed": (
                    single_preflight_boundaries.get(
                        "credential_marker_write_performed"
                    )
                    is True
                ),
                "single_preflight_runtime_action_performed": (
                    single_preflight_boundaries.get("runtime_action_performed") is True
                ),
                "owner_response_skeleton_required_item_count": _int(
                    credential_escrow_intake.get(
                        "owner_response_skeleton_required_item_count"
                    )
                ),
                "owner_response_skeleton_secret_value_collection_allowed": (
                    credential_escrow_intake.get(
                        "owner_response_skeleton_secret_value_collection_allowed"
                    )
                    is True
                ),
                "scorecard_schema_version": str(
                    backup_rollups.get(
                        "credential_escrow_intake_scorecard_schema_version"
                    )
                    or ""
                ),
                "scorecard_verifier": str(
                    backup_rollups.get("credential_escrow_intake_scorecard_verifier")
                    or ""
                ),
            },
            "href": "/operations",
            "next_action": credential_escrow_safe_next_step,
        },
        {
            "id": "gitea_private_inventory",
            "source_id": "gitea_private_inventory_p0_scorecard",
            "completion_percent": _percent(
                private_inventory_rollups.get("review_readiness_percent")
            ),
            "status": str(private_inventory.get("status") or "unknown"),
            "blocker_count": private_inventory_blockers,
            "metric": {
                "kind": "private_inventory",
                "workplan_id": str(
                    private_inventory_readback.get("workplan_id") or "P0-003"
                ),
                "private_inventory_source": str(
                    private_inventory_readback.get("private_inventory_source")
                    or "gitea"
                ),
                "gitea_repo_inventory_status": str(
                    private_inventory_rollups.get("gitea_repo_inventory_status")
                    or "unknown"
                ),
                "gitea_visibility_scope": str(
                    private_inventory_rollups.get("gitea_visibility_scope")
                    or "unknown"
                ),
                "gitea_public_repo_count": _int(
                    private_inventory_rollups.get("gitea_public_repo_count")
                ),
                "expected_product_count": _int(
                    private_inventory_rollups.get("expected_product_count")
                ),
                "present_product_row_count": _int(
                    private_inventory_rollups.get("present_product_row_count")
                ),
                "missing_product_row_count": _int(
                    private_inventory_rollups.get("missing_product_row_count")
                ),
                "accepted_inventory_payload_count": _int(
                    private_inventory_rollups.get("accepted_inventory_payload_count")
                ),
                "owner_coverage_attestation_received_count": _int(
                    private_inventory_rollups.get(
                        "owner_coverage_attestation_received_count"
                    )
                ),
                "authenticated_inventory_single_preflight_intake_ready": (
                    private_inventory.get(
                        "authenticated_inventory_single_preflight_intake_ready"
                    )
                    is True
                ),
                "authenticated_inventory_single_preflight_intake_ready_count": _int(
                    private_inventory_rollups.get(
                        "authenticated_inventory_single_preflight_intake_ready_count"
                    )
                ),
                "authenticated_inventory_single_preflight_intake_schema_version": str(
                    private_inventory_single_preflight.get("schema_version") or ""
                ),
                "authenticated_inventory_payload_skeleton_repo_count_floor": _int(
                    private_inventory_rollups.get(
                        "authenticated_inventory_payload_skeleton_repo_count_floor"
                    )
                ),
                "authenticated_inventory_required_redaction_attestation_count": _int(
                    private_inventory_rollups.get(
                        "authenticated_inventory_required_redaction_attestation_count"
                    )
                ),
                "authenticated_inventory_single_preflight_token_value_collection_allowed": (
                    private_inventory_single_preflight_boundaries.get(
                        "token_value_collection_allowed"
                    )
                    is True
                ),
                "authenticated_inventory_single_preflight_repo_write_performed": (
                    private_inventory_single_preflight_boundaries.get(
                        "repo_write_performed"
                    )
                    is True
                ),
                "authenticated_inventory_single_preflight_refs_sync_performed": (
                    private_inventory_single_preflight_boundaries.get(
                        "refs_sync_performed"
                    )
                    is True
                ),
                "authenticated_inventory_single_preflight_github_api_used": (
                    private_inventory_single_preflight_boundaries.get("github_api_used")
                    is True
                ),
                "authenticated_inventory_single_preflight_runtime_action_performed": (
                    private_inventory_single_preflight_boundaries.get(
                        "runtime_action_performed"
                    )
                    is True
                ),
                "github_lane_excluded_from_p0_blocker_count": (
                    private_inventory_rollups.get(
                        "github_lane_excluded_from_p0_blocker_count"
                    )
                    is True
                ),
                "active_blockers": _strings(private_inventory.get("active_blockers")),
            },
            "href": "/delivery",
            "next_action": str(private_inventory_readback.get("safe_next_step") or ""),
        },
        {
            "id": "cicd_baseline",
            "source_id": "p0_cicd_baseline_source_readiness",
            "completion_percent": _percent(
                cicd_baseline_rollups.get("source_readiness_percent")
            ),
            "status": str(cicd_baseline.get("status") or "unknown"),
            "blocker_count": _int(
                cicd_baseline_rollups.get("missing_required_source_count")
            ),
            "metric": {
                "kind": "source_readiness",
                "workplan_id": str(
                    cicd_baseline_readback.get("workplan_id") or "P0-004"
                ),
                "template_copy_apply_gate_status": str(
                    cicd_template_copy_apply_gate.get("status") or ""
                ),
                "template_copy_apply_allowed": (
                    cicd_apply_gate_readback.get("apply_allowed") is True
                ),
                "template_copy_authorized": (
                    cicd_apply_gate_readback.get(
                        "workflow_template_copy_authorized"
                    )
                    is True
                ),
                "workflow_trigger_authorized": (
                    cicd_apply_gate_readback.get("workflow_trigger_authorized")
                    is True
                ),
                "auto_branch_trigger_authorized": (
                    cicd_apply_gate_readback.get(
                        "auto_push_or_pull_request_trigger_authorized"
                    )
                    is True
                ),
                "generic_runner_label_authorized": (
                    cicd_apply_gate_readback.get("generic_runner_label_authorized")
                    is True
                ),
                "runner_pressure_guard_required": (
                    cicd_apply_gate_readback.get("runner_pressure_guard_required")
                    is True
                ),
                "template_copy_receipt_status": str(
                    cicd_template_copy_receipt.get("status") or ""
                ),
                "template_copy_receipt_ready": (
                    cicd_template_copy_receipt.get("status")
                    == "controlled_template_copy_receipt_ready"
                ),
                "template_copy_receipt_active_blocker_count": _int(
                    cicd_template_copy_receipt_rollups.get("active_blocker_count")
                ),
                "source_template_path": str(
                    cicd_template_copy_receipt_readback.get("source_template_path")
                    or ""
                ),
                "destination_workflow_path": str(
                    cicd_template_copy_receipt_readback.get(
                        "destination_workflow_path"
                    )
                    or ""
                ),
                "source_template_file_present": (
                    cicd_template_copy_receipt_rollups.get("template_file_present")
                    is True
                ),
                "destination_workflow_file_present": (
                    cicd_template_copy_receipt_rollups.get("workflow_file_present")
                    is True
                ),
                "destination_workflow_matches_template": (
                    cicd_template_copy_receipt_rollups.get("workflow_matches_template")
                    is True
                ),
                "destination_workflow_dispatch_declared": (
                    cicd_template_copy_receipt_rollups.get(
                        "workflow_dispatch_declared"
                    )
                    is True
                ),
                "destination_workflow_auto_branch_event_count": _int(
                    cicd_template_copy_receipt_rollups.get("auto_branch_event_count")
                ),
                "destination_workflow_generic_runner_label_count": _int(
                    cicd_template_copy_receipt_rollups.get(
                        "generic_runner_label_count"
                    )
                ),
                "destination_workflow_active_file_created": (
                    cicd_template_copy_receipt_boundaries.get(
                        "active_workflow_file_created"
                    )
                    is True
                ),
                "destination_workflow_trigger_performed": (
                    cicd_template_copy_receipt_boundaries.get(
                        "workflow_trigger_performed"
                    )
                    is True
                ),
                "runtime_enablement_gate_status": str(
                    cicd_runtime_enablement_gate.get("status") or ""
                ),
                "runtime_enablement_gate_ready": (
                    cicd_runtime_enablement_gate.get("status")
                    in {
                        "controlled_warning_step_runtime_enablement_gate_ready",
                        "controlled_warning_step_runtime_enabled",
                        "controlled_warning_step_runtime_enabled_receipt_ready",
                    }
                ),
                "runtime_enablement_gate_active_blocker_count": _int(
                    cicd_runtime_enablement_rollups.get("active_blocker_count")
                ),
                "runtime_enablement_controlled_apply_allowed": (
                    cicd_runtime_enablement_controlled_apply.get(
                        "controlled_apply_allowed"
                    )
                    is True
                ),
                "runtime_enablement_controlled_apply_completed": (
                    cicd_runtime_enablement_controlled_apply.get(
                        "controlled_apply_completed"
                    )
                    is True
                ),
                "runtime_enablement_runtime_execution_enabled": (
                    cicd_runtime_enablement_rollups.get("runtime_execution_enabled")
                    is True
                ),
                "runtime_enablement_switch_changed": (
                    cicd_runtime_enablement_rollups.get("runtime_switch_changed") is True
                ),
                "runtime_enablement_workflow_dispatch_authorized": (
                    cicd_runtime_enablement_controlled_apply.get(
                        "workflow_dispatch_authorized"
                    )
                    is True
                ),
                "runtime_enablement_switch": str(
                    cicd_runtime_enablement_readback.get("runtime_enablement_switch")
                    or ""
                ),
                "runtime_enablement_current_switch_default": str(
                    cicd_runtime_enablement_readback.get("current_switch_default")
                    or ""
                ),
                "runtime_enablement_desired_switch_value": str(
                    cicd_runtime_enablement_readback.get(
                        "desired_switch_value_after_controlled_apply"
                    )
                    or ""
                ),
                "runtime_enablement_trigger_performed": (
                    cicd_runtime_enablement_boundaries.get(
                        "workflow_trigger_performed"
                    )
                    is True
                ),
                "required_source_count": _int(
                    cicd_baseline_rollups.get("required_source_count")
                ),
                "present_required_source_count": _int(
                    cicd_baseline_rollups.get("present_required_source_count")
                ),
                "missing_required_source_count": _int(
                    cicd_baseline_rollups.get("missing_required_source_count")
                ),
                "source_readiness_percent": _int(
                    cicd_baseline_rollups.get("source_readiness_percent")
                ),
                "blocked_source_ids": _strings(
                    cicd_baseline_rollups.get("blocked_source_ids")
                ),
                "workflow_modification_allowed": _dict(
                    cicd_template_copy_apply_gate.get("operation_boundaries")
                ).get("workflow_modification_allowed")
                is True,
                "workflow_trigger_allowed": cicd_apply_gate_boundaries.get(
                    "workflow_trigger_allowed"
                )
                is True,
                "safe_next_step": str(
                    _first_string(cicd_template_copy_apply_gate.get("next_actions"))
                    or cicd_baseline_readback.get("safe_next_step")
                    or ""
                ),
            },
            "href": "/deployments",
            "next_action": _first_string(cicd_baseline.get("next_actions")),
        },
        {
            "id": "gitea",
            "source_id": "gitea_ci_cd",
            "completion_percent": _percent(
                gitea_status.get("overall_completion_percent")
            ),
            "status": str(gitea_status.get("current_task_id") or "unknown"),
            "blocker_count": len(
                _strings(gitea_rollups.get("runner_contracts_requiring_action"))
            ),
            "metric": {
                "kind": "workflow_count",
                "count": _int(gitea_rollups.get("total_workflows")),
                "runner_attestation_request_status": str(
                    gitea_runner_attestation_request.get("status") or ""
                ),
                "runner_attestation_request_ready": (
                    gitea_runner_request_rollups.get("request_template_ready") is True
                ),
                "runner_attestation_request_active_blocker_count": _int(
                    gitea_runner_request_rollups.get("active_blocker_count")
                ),
                "runner_attestation_contract_id": str(
                    gitea_runner_request_readback.get("contract_id") or ""
                ),
                "runner_attestation_workflow_count": _int(
                    gitea_runner_request_rollups.get(
                        "workflow_requiring_attestation_count"
                    )
                ),
                "runner_attestation_required_owner_field_count": _int(
                    gitea_runner_request_rollups.get("required_owner_field_count")
                ),
                "runner_attestation_owner_response_received_count": _int(
                    gitea_runner_request_rollups.get("owner_response_received_count")
                ),
                "runner_attestation_owner_response_accepted_count": _int(
                    gitea_runner_request_rollups.get("owner_response_accepted_count")
                ),
                "runner_attestation_request_send_performed": (
                    gitea_runner_request_boundaries.get("request_send_performed")
                    is True
                ),
                "runner_attestation_runner_label_change_allowed": (
                    gitea_runner_request_boundaries.get("runner_label_change_allowed")
                    is True
                ),
                "runner_attestation_runner_registration_allowed": (
                    gitea_runner_request_boundaries.get("runner_registration_allowed")
                    is True
                ),
                "runner_attestation_secret_read_allowed": (
                    gitea_runner_request_boundaries.get("secret_read_allowed") is True
                ),
            },
            "href": "/deployments",
            "next_action": _first_contract_action(gitea.get("runner_contracts")),
        },
        {
            "id": "runtime",
            "source_id": "runtime_surface",
            "completion_percent": _percent(
                runtime_status.get("overall_completion_percent")
            ),
            "status": str(runtime_status.get("current_task_id") or "unknown"),
            "blocker_count": len(runtime_action_required | runtime_secret_surfaces),
            "metric": {
                "kind": "surface_count",
                "total": _int(runtime_rollups.get("total_surfaces")),
            },
            "href": "/governance?tab=automation-inventory",
            "next_action": _first_surface_action(runtime.get("runtime_surfaces")),
        },
        {
            "id": "backup",
            "source_id": "backup_dr",
            "completion_percent": _percent(
                backup_status.get("overall_completion_percent")
            ),
            "status": str(backup_status.get("current_task_id") or "unknown"),
            "blocker_count": len(backup_non_credential_blockers),
            "metric": {
                "kind": "readiness_row_count",
                "rows": _int(backup_rollups.get("total_rows")),
                "blocked_row_ids": backup_blocked_row_ids,
                "non_credential_blocked_row_ids": backup_non_credential_blockers,
                "credential_escrow_intake_scorecard_schema_version": str(
                    backup_rollups.get(
                        "credential_escrow_intake_scorecard_schema_version"
                    )
                    or ""
                ),
                "credential_escrow_intake_scorecard_verifier": str(
                    backup_rollups.get("credential_escrow_intake_scorecard_verifier")
                    or ""
                ),
                "credential_escrow_intake_status": str(
                    credential_escrow_status
                ),
                "credential_escrow_active_gate_present": (
                    credential_escrow_active_gate_present
                ),
                "credential_escrow_preflight_status": credential_escrow_preflight_status,
                "credential_escrow_required_item_count": credential_escrow_required_items,
                "credential_escrow_effective_missing_count": credential_escrow_missing_items,
                "credential_escrow_accepted_item_count": _int(
                    credential_intake_rollups.get("accepted_item_count")
                ),
                "credential_escrow_owner_response_received_count": _int(
                    credential_intake_rollups.get("owner_response_received_count")
                ),
                "credential_escrow_owner_response_accepted_count": _int(
                    credential_intake_rollups.get("owner_response_accepted_count")
                ),
                "credential_escrow_runtime_gate_count": _int(
                    credential_intake_rollups.get("runtime_gate_count")
                ),
                "credential_escrow_secret_value_collection_allowed": (
                    credential_intake_rollups.get("secret_value_collection_allowed")
                    is True
                ),
                "credential_marker_write_authorized_count": _int(
                    credential_intake_rollups.get(
                        "credential_marker_write_authorized_count"
                    )
                ),
                "credential_escrow_forbidden_true_field_count": _int(
                    credential_intake_rollups.get("forbidden_true_field_count")
                ),
                "credential_escrow_controlled_closeout_status": str(
                    credential_intake_rollups.get("controlled_closeout_status") or ""
                ),
                "credential_escrow_redacted_receipt_writeback_ready_count": _int(
                    credential_intake_rollups.get(
                        "controlled_closeout_redacted_receipt_writeback_ready_count"
                    )
                ),
                "credential_escrow_single_preflight_intake_ready": (
                    credential_escrow_intake.get("single_preflight_intake_ready")
                    is True
                ),
                "credential_escrow_single_preflight_intake_schema_version": str(
                    single_preflight_intake.get("schema_version") or ""
                ),
                "credential_escrow_single_preflight_required_item_count": _int(
                    single_preflight_intake.get("required_item_count")
                ),
                "credential_escrow_single_preflight_secret_value_collection_allowed": (
                    single_preflight_boundaries.get("secret_value_collection_allowed")
                    is True
                ),
            },
            "href": "/operations",
            "next_action": _first_backup_action(backup.get("readiness_rows")),
        },
    ]

    for lane in lanes:
        lane["tone"] = _tone(
            _int(lane["blocker_count"]), _int(lane["completion_percent"])
        )

    source_statuses = [
        _source_status("status_cleanup", status_cleanup),
        _source_status("production_deploy_readback", production_deploy),
        _source_status("reboot_auto_recovery_slo_scorecard", reboot_slo),
        _source_status(
            "reboot_auto_recovery_drill_preflight", reboot_drill_preflight
        ),
        _source_status("gitea_private_inventory_p0_scorecard", private_inventory),
        _source_status("p0_cicd_baseline_source_readiness", cicd_baseline),
        _source_status("gitea_ci_cd", gitea),
        _source_status("runtime_surface", runtime),
        _source_status("backup_dr", backup),
    ]
    source_generated_candidates = [
        source["generated_at"] for source in source_statuses if source["generated_at"]
    ]
    snapshot_generated_candidates = [
        source["snapshot_generated_at"]
        for source in source_statuses
        if source["snapshot_generated_at"]
    ]
    loaded_source_count = sum(1 for source in source_statuses if source["loaded"])
    high_risk_blocker_count = sum(_int(lane["blocker_count"]) for lane in lanes)
    average_completion = _percent(
        sum(_int(lane["completion_percent"]) for lane in lanes) / max(len(lanes), 1)
    )
    source_generated_at = (
        max(source_generated_candidates) if source_generated_candidates else ""
    )
    snapshot_generated_at = (
        max(snapshot_generated_candidates)
        if snapshot_generated_candidates
        else source_generated_at
    )
    runtime_readback_generated_at = _taipei_now_iso()
    next_focus = [
        {
            "lane_id": lane["id"],
            "blocker_count": lane["blocker_count"],
            "completion_percent": lane["completion_percent"],
            "next_action": lane["next_action"],
        }
        for lane in lanes
        if _int(lane["blocker_count"]) > 0 or _int(lane["completion_percent"]) < 80
    ][:5]

    delivery_status = (
        "blocked_delivery_actions_required" if high_risk_blocker_count else "ready"
    )
    current_p0_safe_next_step = str(reboot_readback.get("safe_next_step") or "")
    current_p0_workplan_id = str(reboot_readback.get("workplan_id") or "P0-006")
    current_p0_active_blockers = _strings(reboot_slo.get("active_blockers"))

    return {
        "schema_version": _SCHEMA_VERSION,
        "generated_at": runtime_readback_generated_at,
        "runtime_readback_generated_at": runtime_readback_generated_at,
        "source_generated_at": source_generated_at,
        "snapshot_generated_at": snapshot_generated_at,
        "status": delivery_status,
        "safe_next_step": current_p0_safe_next_step,
        "active_blockers": current_p0_active_blockers,
        "readback": {
            "workbench_status": delivery_status,
            "generated_at": runtime_readback_generated_at,
            "runtime_readback_generated_at": runtime_readback_generated_at,
            "source_generated_at": source_generated_at,
            "snapshot_generated_at": snapshot_generated_at,
            "current_p0_workplan_id": current_p0_workplan_id,
            "current_p0_source_id": "reboot_auto_recovery_slo_scorecard",
            "current_p0_status": str(reboot_slo.get("status") or ""),
            "current_p0_safe_next_step": current_p0_safe_next_step,
            "current_p0_active_blockers": current_p0_active_blockers,
            "current_p0_readiness_percent": _int(
                reboot_rollups.get("readiness_percent")
            ),
            "current_p0_drill_preflight_status": str(
                reboot_drill_preflight.get("status") or ""
            ),
            "current_p0_drill_preflight_ready": (
                reboot_drill_rollups.get("preflight_ready") is True
            ),
            "current_p0_drill_preflight_safe_next_step": str(
                reboot_drill_readback.get("safe_next_step")
                or reboot_drill_preflight.get("safe_next_step")
                or ""
            ),
            "current_p0_drill_preflight_break_glass_required": (
                reboot_drill_rollups.get("break_glass_authorization_required")
                is True
            ),
            "current_p0_drill_preflight_execution_authorized_by_this_endpoint": (
                reboot_drill_rollups.get("execution_authorized_by_this_endpoint")
                is True
            ),
            "closed_p0_workplan_ids": ["P0-003", "P0-005"],
            "github_lane_status": "stopped_retired_do_not_use",
            "secret_value_collection_allowed": False,
            "workflow_trigger_authorized": False,
            "runtime_write_authorized": False,
        },
        "rollups": {
            "source_count": len(source_statuses),
            "loaded_source_count": loaded_source_count,
            "average_completion_percent": average_completion,
            "high_risk_blocker_count": high_risk_blocker_count,
            "current_p0_blocker_count": reboot_blockers,
            "current_p0_readiness_percent": _int(
                reboot_rollups.get("readiness_percent")
            ),
            "current_p0_blocked_by_fresh_reboot_window_only": (
                reboot_rollups.get("blocked_by_fresh_reboot_window_only") is True
            ),
            "current_p0_service_green": reboot_rollups.get("service_green") is True,
            "current_p0_product_data_green": (
                reboot_rollups.get("product_data_green") is True
            ),
            "current_p0_backup_core_green": (
                reboot_rollups.get("backup_core_green") is True
            ),
            "current_p0_stockplatform_freshness_status": str(
                reboot_rollups.get("stockplatform_freshness_status") or ""
            ),
            "current_p0_stockplatform_ingestion_status": str(
                reboot_rollups.get("stockplatform_ingestion_status") or ""
            ),
            "current_p0_drill_preflight_ready": (
                reboot_drill_rollups.get("preflight_ready") is True
            ),
            "current_p0_drill_preflight_ready_count": _int(
                reboot_drill_rollups.get("preflight_ready_count")
            ),
            "current_p0_drill_preflight_blocker_count": _int(
                reboot_drill_rollups.get("preflight_blocker_count")
            ),
            "current_p0_drill_preflight_break_glass_required": (
                reboot_drill_rollups.get("break_glass_authorization_required")
                is True
            ),
            "current_p0_drill_preflight_execution_authorized_by_this_endpoint": (
                reboot_drill_rollups.get("execution_authorized_by_this_endpoint")
                is True
            ),
            "current_p0_drill_preflight_runtime_write_allowed": (
                reboot_drill_rollups.get("runtime_write_allowed") is True
            ),
            "gitea_private_inventory_blocker_count": private_inventory_blockers,
            "credential_escrow_blocker_count": credential_escrow_missing_items,
            "production_deploy_hard_blocker_count": _int(
                production_deploy_rollups.get("hard_blocker_count")
            ),
            "secret_values_collected": False,
            "workflow_trigger_authorized": False,
            "runtime_write_authorized": False,
            "runtime_readback_generated_at_present": True,
            "source_generated_at_present": bool(source_generated_at),
        },
        "summary": {
            "generated_at": runtime_readback_generated_at,
            "runtime_readback_generated_at": runtime_readback_generated_at,
            "source_generated_at": source_generated_at,
            "snapshot_generated_at": snapshot_generated_at,
            "source_count": len(source_statuses),
            "loaded_source_count": loaded_source_count,
            "average_completion_percent": average_completion,
            "high_risk_blocker_count": high_risk_blocker_count,
            "runtime_execution_authorized": False,
            "remote_write_authorized": False,
            "repo_creation_authorized": False,
            "visibility_change_authorized": False,
            "refs_sync_authorized": False,
            "workflow_trigger_authorized": False,
            "reboot_auto_recovery_status": str(reboot_slo.get("status") or ""),
            "reboot_auto_recovery_workplan_id": str(
                reboot_readback.get("workplan_id") or "P0-006"
            ),
            "reboot_auto_recovery_readiness_percent": _int(
                reboot_rollups.get("readiness_percent")
            ),
            "reboot_auto_recovery_active_blocker_count": reboot_blockers,
            "reboot_auto_recovery_can_claim_slo": reboot_rollups.get(
                "can_claim_all_services_recovered_within_target"
            )
            is True,
            "reboot_auto_recovery_service_green": reboot_rollups.get("service_green")
            is True,
            "reboot_auto_recovery_product_data_green": reboot_rollups.get(
                "product_data_green"
            )
            is True,
            "reboot_auto_recovery_observed_host_count": _int(
                reboot_rollups.get("observed_host_count")
            ),
            "reboot_auto_recovery_stale_host_count": _int(
                reboot_rollups.get("stale_host_count")
            ),
            "reboot_auto_recovery_stockplatform_freshness_status": str(
                reboot_rollups.get("stockplatform_freshness_status") or ""
            ),
            "reboot_auto_recovery_stockplatform_ingestion_status": str(
                reboot_rollups.get("stockplatform_ingestion_status") or ""
            ),
            "reboot_auto_recovery_stockplatform_final_retry_window_passed": (
                reboot_rollups.get("stockplatform_final_retry_window_passed") is True
            ),
            "reboot_auto_recovery_stockplatform_controlled_recovery_gate_required": (
                reboot_rollups.get("stockplatform_controlled_recovery_gate_required")
                is True
            ),
            "reboot_auto_recovery_safe_next_step": str(
                reboot_readback.get("safe_next_step") or ""
            ),
            "reboot_auto_recovery_drill_preflight_status": str(
                reboot_drill_preflight.get("status") or ""
            ),
            "reboot_auto_recovery_drill_preflight_ready": (
                reboot_drill_rollups.get("preflight_ready") is True
            ),
            "reboot_auto_recovery_drill_preflight_ready_count": _int(
                reboot_drill_rollups.get("preflight_ready_count")
            ),
            "reboot_auto_recovery_drill_preflight_blocker_count": _int(
                reboot_drill_rollups.get("preflight_blocker_count")
            ),
            "reboot_auto_recovery_drill_preflight_target_required_host_count": _int(
                reboot_drill_rollups.get("target_required_host_count")
            ),
            "reboot_auto_recovery_drill_preflight_target_observed_host_count": _int(
                reboot_drill_rollups.get("target_observed_host_count")
            ),
            "reboot_auto_recovery_drill_preflight_target_missing_host_count": _int(
                reboot_drill_rollups.get("target_missing_host_count")
            ),
            "reboot_auto_recovery_drill_preflight_target_unreachable_host_count": _int(
                reboot_drill_rollups.get("target_unreachable_host_count")
            ),
            "reboot_auto_recovery_drill_preflight_target_stale_host_count": _int(
                reboot_drill_rollups.get("target_stale_host_count")
            ),
            "reboot_auto_recovery_drill_preflight_break_glass_required": (
                reboot_drill_rollups.get("break_glass_authorization_required")
                is True
            ),
            "reboot_auto_recovery_drill_preflight_execution_authorized_by_this_endpoint": (
                reboot_drill_rollups.get("execution_authorized_by_this_endpoint")
                is True
            ),
            "reboot_auto_recovery_drill_preflight_host_reboot_authorized_by_this_endpoint": (
                reboot_drill_rollups.get(
                    "host_reboot_authorized_by_this_endpoint"
                )
                is True
            ),
            "reboot_auto_recovery_drill_preflight_runtime_write_allowed": (
                reboot_drill_rollups.get("runtime_write_allowed") is True
            ),
            "reboot_auto_recovery_drill_preflight_target_selector_scope": str(
                reboot_drill_target_selector.get("scope") or ""
            ),
            "reboot_auto_recovery_drill_preflight_verify_only_available": (
                reboot_drill_check_mode.get("verify_only_available") is True
            ),
            "reboot_auto_recovery_drill_preflight_post_apply_verifier_endpoint": str(
                reboot_drill_check_mode.get("post_apply_verifier_endpoint") or ""
            ),
            "reboot_auto_recovery_drill_preflight_safe_next_step": str(
                reboot_drill_readback.get("safe_next_step")
                or reboot_drill_preflight.get("safe_next_step")
                or ""
            ),
            "gitea_private_inventory_status": str(private_inventory.get("status") or ""),
            "gitea_private_inventory_workplan_id": str(
                private_inventory_readback.get("workplan_id") or ""
            ),
            "gitea_private_inventory_source": str(
                private_inventory_readback.get("private_inventory_source") or ""
            ),
            "gitea_private_inventory_review_readiness_percent": _int(
                private_inventory_rollups.get("review_readiness_percent")
            ),
            "gitea_private_inventory_active_blocker_count": private_inventory_blockers,
            "gitea_private_inventory_repo_inventory_status": str(
                private_inventory_rollups.get("gitea_repo_inventory_status") or ""
            ),
            "gitea_private_inventory_visibility_scope": str(
                private_inventory_rollups.get("gitea_visibility_scope") or ""
            ),
            "gitea_private_inventory_public_repo_count": _int(
                private_inventory_rollups.get("gitea_public_repo_count")
            ),
            "gitea_private_inventory_expected_product_count": _int(
                private_inventory_rollups.get("expected_product_count")
            ),
            "gitea_private_inventory_present_product_row_count": _int(
                private_inventory_rollups.get("present_product_row_count")
            ),
            "gitea_private_inventory_missing_product_row_count": _int(
                private_inventory_rollups.get("missing_product_row_count")
            ),
            "gitea_private_inventory_accepted_payload_count": _int(
                private_inventory_rollups.get("accepted_inventory_payload_count")
            ),
            "gitea_private_inventory_owner_coverage_attestation_received_count": _int(
                private_inventory_rollups.get(
                    "owner_coverage_attestation_received_count"
                )
            ),
            "gitea_private_inventory_authenticated_single_preflight_intake_ready": (
                private_inventory.get(
                    "authenticated_inventory_single_preflight_intake_ready"
                )
                is True
            ),
            "gitea_private_inventory_authenticated_single_preflight_intake_ready_count": _int(
                private_inventory_rollups.get(
                    "authenticated_inventory_single_preflight_intake_ready_count"
                )
            ),
            "gitea_private_inventory_authenticated_single_preflight_intake_schema_version": str(
                private_inventory_single_preflight.get("schema_version") or ""
            ),
            "gitea_private_inventory_authenticated_payload_skeleton_repo_count_floor": _int(
                private_inventory_rollups.get(
                    "authenticated_inventory_payload_skeleton_repo_count_floor"
                )
            ),
            "gitea_private_inventory_authenticated_required_redaction_attestation_count": _int(
                private_inventory_rollups.get(
                    "authenticated_inventory_required_redaction_attestation_count"
                )
            ),
            "gitea_private_inventory_authenticated_single_preflight_token_value_collection_allowed": (
                private_inventory_single_preflight_boundaries.get(
                    "token_value_collection_allowed"
                )
                is True
            ),
            "gitea_private_inventory_authenticated_single_preflight_repo_write_performed": (
                private_inventory_single_preflight_boundaries.get("repo_write_performed")
                is True
            ),
            "gitea_private_inventory_authenticated_single_preflight_refs_sync_performed": (
                private_inventory_single_preflight_boundaries.get("refs_sync_performed")
                is True
            ),
            "gitea_private_inventory_authenticated_single_preflight_github_api_used": (
                private_inventory_single_preflight_boundaries.get("github_api_used")
                is True
            ),
            "gitea_private_inventory_authenticated_single_preflight_runtime_action_performed": (
                private_inventory_single_preflight_boundaries.get(
                    "runtime_action_performed"
                )
                is True
            ),
            "gitea_private_inventory_all_active_product_repos_have_owner_readiness_row": (
                private_inventory_rollups.get(
                    "all_active_product_repos_have_gitea_owner_readiness_row"
                )
                is True
            ),
            "gitea_private_inventory_safe_next_step": str(
                private_inventory_readback.get("safe_next_step") or ""
            ),
            "github_global_freeze_enabled": True,
            "github_lane_status": str(
                private_inventory_retired_github.get("status")
                or "stopped_retired_do_not_use"
            ),
            "github_lane_excluded_from_p0_blocker_count": (
                private_inventory_rollups.get(
                    "github_lane_excluded_from_p0_blocker_count"
                )
                is True
            ),
            "gitea_runner_attestation_request_status": str(
                gitea_runner_attestation_request.get("status") or ""
            ),
            "gitea_runner_attestation_request_ready": (
                gitea_runner_request_rollups.get("request_template_ready") is True
            ),
            "gitea_runner_attestation_request_active_blocker_count": _int(
                gitea_runner_request_rollups.get("active_blocker_count")
            ),
            "gitea_runner_attestation_contract_id": str(
                gitea_runner_request_readback.get("contract_id") or ""
            ),
            "gitea_runner_attestation_runner_label": str(
                gitea_runner_request_readback.get("runner_label") or ""
            ),
            "gitea_runner_attestation_workflow_count": _int(
                gitea_runner_request_rollups.get(
                    "workflow_requiring_attestation_count"
                )
            ),
            "gitea_runner_attestation_required_owner_field_count": _int(
                gitea_runner_request_rollups.get("required_owner_field_count")
            ),
            "gitea_runner_attestation_forbidden_action_count": _int(
                gitea_runner_request_rollups.get("forbidden_action_count")
            ),
            "gitea_runner_attestation_owner_response_received_count": _int(
                gitea_runner_request_rollups.get("owner_response_received_count")
            ),
            "gitea_runner_attestation_owner_response_accepted_count": _int(
                gitea_runner_request_rollups.get("owner_response_accepted_count")
            ),
            "gitea_runner_attestation_request_sent": (
                gitea_runner_request_packet.get("request_sent") is True
            ),
            "gitea_runner_attestation_request_send_performed": (
                gitea_runner_request_boundaries.get("request_send_performed") is True
            ),
            "gitea_runner_attestation_runner_label_change_allowed": (
                gitea_runner_request_boundaries.get("runner_label_change_allowed")
                is True
            ),
            "gitea_runner_attestation_runner_registration_allowed": (
                gitea_runner_request_boundaries.get("runner_registration_allowed")
                is True
            ),
            "gitea_runner_attestation_secret_read_allowed": (
                gitea_runner_request_boundaries.get("secret_read_allowed") is True
            ),
            "p0_cicd_baseline_status": str(cicd_baseline.get("status") or ""),
            "p0_cicd_baseline_workplan_id": str(
                cicd_baseline_readback.get("workplan_id") or ""
            ),
            "p0_cicd_baseline_source_readiness_percent": _int(
                cicd_baseline_rollups.get("source_readiness_percent")
            ),
            "p0_cicd_baseline_required_source_count": _int(
                cicd_baseline_rollups.get("required_source_count")
            ),
            "p0_cicd_baseline_present_required_source_count": _int(
                cicd_baseline_rollups.get("present_required_source_count")
            ),
            "p0_cicd_baseline_missing_required_source_count": _int(
                cicd_baseline_rollups.get("missing_required_source_count")
            ),
            "p0_cicd_baseline_blocked_source_ids": _strings(
                cicd_baseline_rollups.get("blocked_source_ids")
            ),
            "p0_cicd_baseline_safe_next_step": str(
                cicd_baseline_readback.get("safe_next_step") or ""
            ),
            "p0_cicd_template_copy_apply_gate_status": str(
                cicd_template_copy_apply_gate.get("status") or ""
            ),
            "p0_cicd_template_copy_apply_allowed": (
                cicd_apply_gate_readback.get("apply_allowed") is True
            ),
            "p0_cicd_template_copy_authorized": (
                cicd_apply_gate_readback.get("workflow_template_copy_authorized")
                is True
            ),
            "p0_cicd_template_copy_workflow_trigger_authorized": (
                cicd_apply_gate_readback.get("workflow_trigger_authorized") is True
            ),
            "p0_cicd_template_copy_auto_branch_trigger_authorized": (
                cicd_apply_gate_readback.get(
                    "auto_push_or_pull_request_trigger_authorized"
                )
                is True
            ),
            "p0_cicd_template_copy_generic_runner_label_authorized": (
                cicd_apply_gate_readback.get("generic_runner_label_authorized")
                is True
            ),
            "p0_cicd_template_copy_runner_pressure_guard_required": (
                cicd_apply_gate_readback.get("runner_pressure_guard_required")
                is True
            ),
            "p0_cicd_template_copy_receipt_status": str(
                cicd_template_copy_receipt.get("status") or ""
            ),
            "p0_cicd_template_copy_receipt_ready": (
                cicd_template_copy_receipt.get("status")
                == "controlled_template_copy_receipt_ready"
            ),
            "p0_cicd_template_copy_receipt_active_blocker_count": _int(
                cicd_template_copy_receipt_rollups.get("active_blocker_count")
            ),
            "p0_cicd_template_copy_source_template_path": str(
                cicd_template_copy_receipt_readback.get("source_template_path")
                or ""
            ),
            "p0_cicd_template_copy_destination_workflow_path": str(
                cicd_template_copy_receipt_readback.get("destination_workflow_path")
                or ""
            ),
            "p0_cicd_template_copy_source_template_file_present": (
                cicd_template_copy_receipt_rollups.get("template_file_present")
                is True
            ),
            "p0_cicd_template_copy_destination_workflow_file_present": (
                cicd_template_copy_receipt_rollups.get("workflow_file_present") is True
            ),
            "p0_cicd_template_copy_destination_workflow_matches_template": (
                cicd_template_copy_receipt_rollups.get("workflow_matches_template")
                is True
            ),
            "p0_cicd_template_copy_workflow_dispatch_declared": (
                cicd_template_copy_receipt_rollups.get("workflow_dispatch_declared")
                is True
            ),
            "p0_cicd_template_copy_auto_branch_event_count": _int(
                cicd_template_copy_receipt_rollups.get("auto_branch_event_count")
            ),
            "p0_cicd_template_copy_generic_runner_label_count": _int(
                cicd_template_copy_receipt_rollups.get("generic_runner_label_count")
            ),
            "p0_cicd_template_copy_active_workflow_file_created": (
                cicd_template_copy_receipt_boundaries.get("active_workflow_file_created")
                is True
            ),
            "p0_cicd_template_copy_workflow_trigger_performed": (
                cicd_template_copy_receipt_boundaries.get("workflow_trigger_performed")
                is True
            ),
            "p0_cicd_warning_step_runtime_enablement_gate_status": str(
                cicd_runtime_enablement_gate.get("status") or ""
            ),
            "p0_cicd_warning_step_runtime_enablement_gate_ready": (
                cicd_runtime_enablement_gate.get("status")
                in {
                    "controlled_warning_step_runtime_enablement_gate_ready",
                    "controlled_warning_step_runtime_enabled",
                    "controlled_warning_step_runtime_enabled_receipt_ready",
                }
            ),
            "p0_cicd_warning_step_runtime_enablement_active_blocker_count": _int(
                cicd_runtime_enablement_rollups.get("active_blocker_count")
            ),
            "p0_cicd_warning_step_runtime_enablement_controlled_apply_allowed": (
                cicd_runtime_enablement_controlled_apply.get(
                    "controlled_apply_allowed"
                )
                is True
            ),
            "p0_cicd_warning_step_runtime_enablement_controlled_apply_completed": (
                cicd_runtime_enablement_controlled_apply.get(
                    "controlled_apply_completed"
                )
                is True
            ),
            "p0_cicd_warning_step_runtime_enablement_runtime_execution_enabled": (
                cicd_runtime_enablement_rollups.get("runtime_execution_enabled") is True
            ),
            "p0_cicd_warning_step_runtime_enablement_switch_changed": (
                cicd_runtime_enablement_rollups.get("runtime_switch_changed") is True
            ),
            "p0_cicd_warning_step_runtime_enablement_workflow_dispatch_authorized": (
                cicd_runtime_enablement_controlled_apply.get(
                    "workflow_dispatch_authorized"
                )
                is True
            ),
            "p0_cicd_warning_step_runtime_enablement_switch": str(
                cicd_runtime_enablement_readback.get("runtime_enablement_switch") or ""
            ),
            "p0_cicd_warning_step_runtime_enablement_current_switch_default": str(
                cicd_runtime_enablement_readback.get("current_switch_default") or ""
            ),
            "p0_cicd_warning_step_runtime_enablement_desired_switch_value": str(
                cicd_runtime_enablement_readback.get(
                    "desired_switch_value_after_controlled_apply"
                )
                or ""
            ),
            "p0_cicd_warning_step_runtime_enablement_trigger_performed": (
                cicd_runtime_enablement_boundaries.get("workflow_trigger_performed")
                is True
            ),
            "production_deploy_status": str(production_deploy.get("status") or ""),
            "production_deploy_source_control_main_ready": production_deploy_rollups.get(
                "source_control_main_ready"
            )
            is True,
            "production_deploy_image_tag_matches_main": production_deploy_rollups.get(
                "production_image_tag_matches_main"
            )
            is True,
            "production_deploy_runtime_build_commit_sha": str(
                production_deploy_readback.get("runtime_build_commit_sha") or ""
            ),
            "production_deploy_runtime_build_commit_short_sha": str(
                production_deploy_readback.get("runtime_build_commit_short_sha") or ""
            ),
            "production_deploy_runtime_build_readback_status": str(
                production_deploy_readback.get("runtime_build_readback_status") or ""
            ),
            "production_deploy_runtime_build_matches_gitops_desired_image_tag": (
                production_deploy_runtime_matches_gitops_desired
            ),
            "production_deploy_runtime_build_deploy_readback_current": (
                production_deploy_runtime_readback_current
            ),
            "production_deploy_runtime_build_committed_readback_drift_accepted": (
                production_deploy_runtime_committed_drift_accepted
            ),
            "production_deploy_runtime_build_matches_committed_source_control_readback": (
                production_deploy_readback.get(
                    "runtime_build_matches_committed_source_control_readback"
                )
                is True
            ),
            "production_deploy_runtime_build_matches_committed_production_image_tag": (
                production_deploy_readback.get(
                    "runtime_build_matches_committed_production_image_tag"
                )
                is True
            ),
            "production_deploy_desired_main_api_image_tag_short_sha": str(
                production_deploy_readback.get("desired_main_api_image_tag_short_sha")
                or ""
            ),
            "production_deploy_desired_main_api_image_tag_readback_status": str(
                production_deploy_readback.get(
                    "desired_main_api_image_tag_readback_status"
                )
                or ""
            ),
            "production_deploy_governance_fields_present": production_deploy_rollups.get(
                "production_governance_fields_present"
            )
            is True,
            "production_deploy_authorized_dispatch_channel_ready": (
                production_deploy_rollups.get("authorized_dispatch_channel_ready")
                is True
            ),
            "production_deploy_manual_run_button_visible": production_deploy_readback.get(
                "manual_run_button_visible"
            )
            is True,
            "production_deploy_gitea_sign_in_required": production_deploy_readback.get(
                "gitea_sign_in_required"
            )
            is True,
            "production_deploy_dispatch_without_token_http_status": _int(
                production_deploy_readback.get("dispatch_without_token_http_status")
            ),
            "production_deploy_dispatch_without_token_message": str(
                production_deploy_readback.get("dispatch_without_token_message") or ""
            ),
            "production_deploy_hard_blocker_count": _int(
                production_deploy_rollups.get("hard_blocker_count")
            ),
            "production_deploy_latest_visible_cd_run_id": str(
                production_deploy_readback.get("latest_visible_cd_run_id") or ""
            ),
            "production_deploy_latest_visible_cd_run_status": str(
                production_deploy_readback.get("latest_visible_cd_run_status") or ""
            ),
            "production_deploy_latest_visible_cd_run_jobs_total_count": _int(
                production_deploy_readback.get(
                    "latest_visible_cd_run_jobs_total_count"
                )
            ),
            "production_deploy_gitea_actions_list_without_token_http_status": _int(
                production_deploy_readback.get(
                    "gitea_actions_list_without_token_http_status"
                )
            ),
            "production_deploy_gitea_actions_list_without_token_message": str(
                production_deploy_readback.get(
                    "gitea_actions_list_without_token_message"
                )
                or ""
            ),
            "production_deploy_latest_visible_waiting_runner_run_id": str(
                production_deploy_readback.get("latest_visible_waiting_runner_run_id")
                or ""
            ),
            "production_deploy_latest_visible_waiting_runner_workflow": str(
                production_deploy_readback.get(
                    "latest_visible_waiting_runner_workflow"
                )
                or ""
            ),
            "production_deploy_latest_visible_waiting_runner_kind": str(
                production_deploy_readback.get("latest_visible_waiting_runner_kind")
                or ""
            ),
            "production_deploy_latest_visible_waiting_runner_status": str(
                production_deploy_readback.get("latest_visible_waiting_runner_status")
                or ""
            ),
            "production_deploy_latest_visible_waiting_runner_label": str(
                production_deploy_readback.get("latest_visible_waiting_runner_label")
                or ""
            ),
            "production_deploy_public_actions_queue_readback_schema_version": str(
                production_deploy_readback.get(
                    "public_actions_queue_readback_schema_version"
                )
                or ""
            ),
            "production_deploy_public_actions_queue_readback_verifier": str(
                production_deploy_readback.get("public_actions_queue_readback_verifier")
                or ""
            ),
            "production_deploy_non110_runner_cd_closure_verifier_schema_version": str(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_verifier_schema_version"
                )
                or ""
            ),
            "production_deploy_non110_runner_cd_closure_verifier": str(
                production_deploy_readback.get("non110_runner_cd_closure_verifier")
                or ""
            ),
            "production_deploy_non110_runner_cd_closure_status": str(
                production_deploy_readback.get("non110_runner_cd_closure_status")
                or ""
            ),
            "production_deploy_non110_runner_cd_closure_required": (
                production_deploy_readback.get("non110_runner_cd_closure_required")
                is True
            ),
            "production_deploy_non110_runner_cd_closure_ordered_step_count": _int(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_ordered_step_count"
                )
            ),
            "production_deploy_non110_runner_cd_closure_ordered_completed_prefix_count": _int(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_ordered_completed_prefix_count"
                )
            ),
            "production_deploy_non110_runner_cd_closure_evidence_completed_step_count": _int(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_evidence_completed_step_count"
                )
            ),
            "production_deploy_non110_runner_cd_closure_ordered_completion_percent": _int(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_ordered_completion_percent"
                )
            ),
            "production_deploy_non110_runner_cd_closure_evidence_completion_percent": _int(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_evidence_completion_percent"
                )
            ),
            "production_deploy_non110_runner_cd_closure_next_blocked_step_index": _int(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_next_blocked_step_index"
                )
            ),
            "production_deploy_non110_runner_cd_closure_next_blocked_step_id": str(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_next_blocked_step_id"
                )
                or ""
            ),
            "production_deploy_non110_runner_cd_closure_next_blocked_step_action": str(
                production_deploy_readback.get(
                    "non110_runner_cd_closure_next_blocked_step_action"
                )
                or ""
            ),
            "production_deploy_non110_runner_ready": production_deploy_readback.get(
                "non110_runner_ready"
            )
            is True,
            "production_deploy_non110_runner_prepare_only_source_ready": (
                production_deploy_readback.get("non110_runner_prepare_only_source_ready")
                is True
            ),
            "production_deploy_non110_runner_safe_registration_helper_ready": (
                production_deploy_readback.get(
                    "non110_runner_safe_registration_helper_ready"
                )
                is True
            ),
            "production_deploy_non110_runner_workflow_labels_aligned": (
                production_deploy_readback.get(
                    "non110_runner_workflow_labels_aligned"
                )
                is True
            ),
            "production_deploy_non110_runner_host_label": str(
                production_deploy_readback.get("non110_runner_host_label") or ""
            ),
            "production_deploy_non110_runner_ubuntu_label": str(
                production_deploy_readback.get("non110_runner_ubuntu_label") or ""
            ),
            "production_deploy_non110_runner_online_label_match": (
                production_deploy_readback.get("non110_runner_online_label_match")
                is True
            ),
            "production_deploy_non110_runner_autostart_path_armed": (
                production_deploy_readback.get("non110_runner_autostart_path_armed")
                is True
            ),
            "production_deploy_non110_runner_ready_autostart_path_count": _int(
                production_deploy_readback.get(
                    "non110_runner_ready_autostart_path_count"
                )
            ),
            "production_deploy_non110_runner_registration_condition_required": (
                production_deploy_readback.get(
                    "non110_runner_registration_condition_required"
                )
                is True
            ),
            "production_deploy_non110_runner_ready_config_count": _int(
                production_deploy_readback.get("non110_runner_ready_config_count")
            ),
            "production_deploy_non110_runner_ready_service_count": _int(
                production_deploy_readback.get("non110_runner_ready_service_count")
            ),
            "production_deploy_non110_runner_ready_registration_count": _int(
                production_deploy_readback.get(
                    "non110_runner_ready_registration_count"
                )
            ),
            "production_deploy_non110_runner_safe_next_step": str(
                production_deploy_readback.get("non110_runner_safe_next_step") or ""
            ),
            "production_deploy_non110_runner_remaining_blocker_count": len(
                _strings(
                    production_deploy_readback.get(
                        "non110_runner_remaining_blockers"
                    )
                )
            ),
            "backup_credential_escrow_intake_scorecard_schema_version": str(
                backup_rollups.get(
                    "credential_escrow_intake_scorecard_schema_version"
                )
                or ""
            ),
            "backup_credential_escrow_intake_scorecard_verifier": str(
                backup_rollups.get("credential_escrow_intake_scorecard_verifier")
                or ""
            ),
            "backup_credential_escrow_intake_status": str(
                credential_escrow_status
            ),
            "backup_credential_escrow_active_gate_present": (
                credential_escrow_active_gate_present
            ),
            "backup_credential_escrow_preflight_status": credential_escrow_preflight_status,
            "backup_credential_escrow_required_item_count": credential_escrow_required_items,
            "backup_credential_escrow_effective_missing_count": credential_escrow_missing_items,
            "backup_credential_escrow_accepted_item_count": _int(
                credential_intake_rollups.get("accepted_item_count")
            ),
            "backup_credential_escrow_owner_response_received_count": _int(
                credential_intake_rollups.get("owner_response_received_count")
            ),
            "backup_credential_escrow_owner_response_accepted_count": _int(
                credential_intake_rollups.get("owner_response_accepted_count")
            ),
            "backup_credential_escrow_runtime_gate_count": _int(
                credential_intake_rollups.get("runtime_gate_count")
            ),
            "backup_credential_escrow_secret_value_collection_allowed": (
                credential_intake_rollups.get("secret_value_collection_allowed")
                is True
            ),
            "backup_credential_marker_write_authorized_count": _int(
                credential_intake_rollups.get(
                    "credential_marker_write_authorized_count"
                )
            ),
            "backup_credential_escrow_forbidden_true_field_count": _int(
                credential_intake_rollups.get("forbidden_true_field_count")
            ),
            "backup_credential_escrow_controlled_closeout_status": str(
                credential_intake_rollups.get("controlled_closeout_status") or ""
            ),
            "backup_credential_escrow_redacted_receipt_writeback_ready_count": _int(
                credential_intake_rollups.get(
                    "controlled_closeout_redacted_receipt_writeback_ready_count"
                )
            ),
            "backup_credential_escrow_closeout_receipt_ref": str(
                credential_intake_readback.get("source_closeout_receipt_ref") or ""
            ),
            "backup_credential_escrow_single_preflight_intake_ready": (
                credential_escrow_intake.get("single_preflight_intake_ready") is True
            ),
            "backup_credential_escrow_single_preflight_intake_ready_count": _int(
                credential_intake_rollups.get("single_preflight_intake_ready_count")
            ),
            "backup_credential_escrow_single_preflight_intake_schema_version": str(
                single_preflight_intake.get("schema_version") or ""
            ),
            "backup_credential_escrow_single_preflight_required_item_count": _int(
                single_preflight_intake.get("required_item_count")
            ),
            "backup_credential_escrow_single_preflight_safe_next_step": str(
                credential_intake_readback.get("safe_next_step")
                or credential_escrow_intake.get("safe_next_step")
                or ""
            ),
            "backup_credential_escrow_single_preflight_secret_value_collection_allowed": (
                single_preflight_boundaries.get("secret_value_collection_allowed")
                is True
            ),
            "backup_credential_escrow_single_preflight_credential_marker_write_performed": (
                single_preflight_boundaries.get("credential_marker_write_performed")
                is True
            ),
            "backup_credential_escrow_single_preflight_runtime_action_performed": (
                single_preflight_boundaries.get("runtime_action_performed") is True
            ),
            "github_write_channel_ready": False,
            "github_account_status": "stopped_retired_do_not_use",
            "github_account_suspended": False,
            "github_api_forbidden_count": 0,
            "github_controlled_apply_ready_count": 0,
            "github_blocked_preflight_target_count": 0,
            "github_operator_unblock_required": False,
            "github_operator_unblock_status": "github_global_freeze_stopped_retired_do_not_use",
            "github_internal_governance_writeback_ready": False,
            "github_mcp_evidence_packet_count": 0,
            "github_rag_evidence_ref_count": 0,
            "github_km_writeback_ready_count": 0,
            "github_playbook_writeback_ready_count": 0,
            "github_timeline_log_ready_count": 0,
            "github_logbook_entry_count": 0,
            "secret_values_collected": False,
        },
        "source_statuses": source_statuses,
        "lanes": lanes,
        "next_focus": next_focus,
        "operation_boundaries": {
            "read_only_api_allowed": True,
            "runtime_write_allowed": False,
            "remote_write_allowed": False,
            "repo_creation_allowed": False,
            "visibility_change_allowed": False,
            "refs_sync_allowed": False,
            "workflow_trigger_allowed": False,
            "production_deploy_trigger_allowed": _dict(
                production_deploy.get("operation_boundaries")
            ).get("deploy_trigger_allowed")
            is True,
            "gitea_api_write_allowed": private_inventory_boundaries.get(
                "gitea_api_write_allowed"
            )
            is True,
            "gitea_authenticated_inventory_import_execution_allowed": (
                private_inventory_boundaries.get(
                    "authenticated_inventory_import_execution_allowed"
                )
                is True
            ),
            "github_write_channel_ready": False,
            "github_controlled_apply_allowed": False,
            "secret_value_collection_allowed": False,
            "backup_restore_execution_allowed": False,
            "active_scan_allowed": False,
            "host_reboot_performed": _dict(
                reboot_slo.get("operation_boundaries")
            ).get("host_reboot_performed")
            is True,
            "service_restart_performed": _dict(
                reboot_slo.get("operation_boundaries")
            ).get("service_restart_performed")
            is True,
            "database_write_or_restore_performed": _dict(
                reboot_slo.get("operation_boundaries")
            ).get("database_write_or_restore_performed")
            is True,
            "stockplatform_manual_data_write_performed": _dict(
                reboot_slo.get("operation_boundaries")
            ).get("stockplatform_manual_data_write_performed")
            is True,
        },
    }


def _source_status(source_id: str, payload: dict[str, Any]) -> dict[str, Any]:
    source_missing = payload.get("source_missing") is True
    return {
        "id": source_id,
        "loaded": not source_missing,
        "schema_version": str(payload.get("schema_version") or ""),
        "generated_at": str(payload.get("generated_at") or ""),
        "runtime_readback_generated_at": str(
            payload.get("runtime_readback_generated_at") or ""
        ),
        "snapshot_generated_at": str(payload.get("snapshot_generated_at") or ""),
        "missing_reason": str(payload.get("missing_reason") or "")
        if source_missing
        else "",
    }


def _tone(blocker_count: int, percent: int) -> str:
    if blocker_count > 0:
        return "danger"
    if percent < 80:
        return "warn"
    return "ok"


def _dict(value: Any) -> dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _int(value: Any) -> int:
    if isinstance(value, bool):
        return int(value)
    if isinstance(value, int | float):
        return int(value)
    return 0


def _percent(value: Any) -> int:
    return max(0, min(100, round(float(value or 0))))


def _strings(value: Any) -> list[str]:
    if not isinstance(value, list):
        return []
    return [str(item) for item in value if item is not None]


def _taipei_now_iso() -> str:
    return datetime.now(ZoneInfo("Asia/Taipei")).isoformat(timespec="seconds")


def _first_string(value: Any) -> str:
    if isinstance(value, list) and value:
        return str(value[0])
    return ""


def _first_contract_action(value: Any) -> str:
    if not isinstance(value, list):
        return ""
    for row in value:
        if isinstance(row, dict) and row.get("status") == "action_required":
            return str(row.get("next_action") or "")
    return _first_row_action(value)


def _first_surface_action(value: Any) -> str:
    if not isinstance(value, list):
        return ""
    for row in value:
        if isinstance(row, dict) and row.get("status") != "manifest_mapped":
            return str(row.get("next_action") or "")
    return _first_row_action(value)


def _first_backup_action(value: Any) -> str:
    if not isinstance(value, list):
        return ""
    for row in value:
        if isinstance(row, dict) and row.get("overall_readiness") in {
            "blocked",
            "action_required",
        }:
            return str(row.get("next_action") or "")
    return _first_row_action(value)


def _first_row_action(value: Any) -> str:
    if not isinstance(value, list):
        return ""
    for row in value:
        if isinstance(row, dict) and row.get("next_action"):
            return str(row["next_action"])
    return ""
