"""Smoke checks for the four-agent AI automation control plane.

The checks are read-only and intentionally avoid outbound network calls. They
are meant for a fast dashboard/API sanity check, not for deep production probes.
"""

from __future__ import annotations

import os
import json
import threading
from datetime import datetime, timedelta, timezone
from html import escape
from typing import Any, Dict, List

from sqlalchemy import text

from config import SYSTEM_VERSION
from database.manager import get_session


STATUS_RANK = {"ok": 0, "warning": 1, "critical": 2}
SCHEDULED_AUTOMATION_HEALTH_SUMMARY_POLICY = "read_only_ai_automation_scheduled_health_summary"
_HISTORY_PATH = os.getenv(
    "MOMO_AI_AUTOMATION_SMOKE_HISTORY",
    os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "ai_automation_smoke_history.jsonl"),
)
_HISTORY_LIMIT = int(os.getenv("MOMO_AI_AUTOMATION_SMOKE_HISTORY_LIMIT", "200"))
_HISTORY_LOCK = threading.Lock()
_PCHOME_DRIFT_MONITOR_DB_STATEMENT_TIMEOUT_MS = int(
    os.getenv("MOMO_PCHOME_DRIFT_MONITOR_DB_STATEMENT_TIMEOUT_MS", "5000")
)
_PCHOME_AUTO_POLICY_GUARD_LIMIT = int(
    os.getenv("MOMO_PCHOME_AUTO_POLICY_GUARD_LIMIT", "20")
)
_PCHOME_AUTO_POLICY_GUARD_BATCH_SIZE = int(
    os.getenv("MOMO_PCHOME_AUTO_POLICY_GUARD_BATCH_SIZE", "12")
)
_PCHOME_AUTO_POLICY_GUARD_TIMEOUT_SECONDS = int(
    os.getenv("MOMO_PCHOME_AUTO_POLICY_GUARD_TIMEOUT_SECONDS", "5")
)
_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE = int(
    os.getenv(
        "MOMO_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE",
        str(_PCHOME_AUTO_POLICY_GUARD_BATCH_SIZE),
    )
)
_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS = int(
    os.getenv(
        "MOMO_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS",
        str(_PCHOME_AUTO_POLICY_GUARD_TIMEOUT_SECONDS),
    )
)


def _check(name: str, status: str, summary: str, details: Dict[str, Any] | None = None) -> Dict[str, Any]:
    return {
        "name": name,
        "status": status,
        "summary": summary,
        "details": details or {},
    }


def _count_jsonl_lines(path: str) -> int:
    try:
        with open(path, "r", encoding="utf-8") as fh:
            return sum(1 for line in fh if line.strip())
    except FileNotFoundError:
        return 0


def _compact_history_record(result: Dict[str, Any]) -> Dict[str, Any]:
    return {
        "generated_at": result.get("generated_at"),
        "status": result.get("status", "critical"),
        "summary": result.get("summary", {}),
        "checks": [
            {
                "name": item.get("name"),
                "status": item.get("status"),
                "summary": item.get("summary"),
            }
            for item in result.get("checks", [])
        ],
    }


def _read_history_lines() -> List[str]:
    with _HISTORY_LOCK:
        with open(_HISTORY_PATH, "r", encoding="utf-8") as fh:
            return fh.readlines()


def _load_history(limit: int = 20) -> List[Dict[str, Any]]:
    if limit <= 0:
        return []
    try:
        lines = _read_history_lines()
    except FileNotFoundError:
        return []

    records = []
    for line in lines[-limit:]:
        try:
            records.append(json.loads(line))
        except json.JSONDecodeError:
            continue
    return records


def _append_history(result: Dict[str, Any]) -> None:
    record = _compact_history_record(result)
    os.makedirs(os.path.dirname(_HISTORY_PATH), exist_ok=True)
    with _HISTORY_LOCK:
        existing = []
        try:
            with open(_HISTORY_PATH, "r", encoding="utf-8") as fh:
                existing = fh.readlines()
        except FileNotFoundError:
            pass

        existing.append(json.dumps(record, ensure_ascii=False, default=str) + "\n")
        if len(existing) > _HISTORY_LIMIT:
            existing = existing[-_HISTORY_LIMIT:]

        with open(_HISTORY_PATH, "w", encoding="utf-8") as fh:
            fh.writelines(existing)


def _history_summary(records: List[Dict[str, Any]]) -> Dict[str, Any]:
    counts = {"ok": 0, "warning": 0, "critical": 0}
    for record in records:
        status = record.get("status", "critical")
        if status in counts:
            counts[status] += 1
    return {
        "counts": counts,
        "recent": records,
        "latest": records[-1] if records else None,
        "daily": _daily_summary(records),
    }


def _parse_history_timestamp(value: Any) -> datetime | None:
    if not value:
        return None
    text_value = str(value).strip()
    if not text_value:
        return None
    try:
        return datetime.fromisoformat(text_value.replace("Z", "+00:00"))
    except ValueError:
        return None


def _history_freshness_family(
    latest: Dict[str, Any] | None,
    *,
    max_age_hours: int,
) -> Dict[str, Any]:
    if not latest:
        return {
            "key": "smoke_history_freshness",
            "label": "Smoke history freshness",
            "status": "warning",
            "summary": "No scheduled smoke history is available yet.",
            "next_machine_action": "run_ai_automation_smoke_once",
            "details": {"history_record_count": 0, "writes_database": False},
        }
    generated_at = _parse_history_timestamp(latest.get("generated_at"))
    if generated_at is None:
        return {
            "key": "smoke_history_freshness",
            "label": "Smoke history freshness",
            "status": "warning",
            "summary": "Latest scheduled smoke history timestamp cannot be parsed.",
            "next_machine_action": "refresh_smoke_history_timestamp",
            "details": {
                "generated_at": latest.get("generated_at"),
                "writes_database": False,
            },
        }

    now = datetime.now(generated_at.tzinfo) if generated_at.tzinfo else datetime.now()
    age_hours = max((now - generated_at).total_seconds() / 3600, 0)
    fresh = age_hours <= max_age_hours
    return {
        "key": "smoke_history_freshness",
        "label": "Smoke history freshness",
        "status": "ok" if fresh else "warning",
        "summary": (
            f"Latest smoke history is {age_hours:.1f}h old."
            if fresh
            else f"Latest smoke history is stale at {age_hours:.1f}h old."
        ),
        "next_machine_action": "keep_scheduled_smoke_cadence" if fresh else "run_ai_automation_smoke_once",
        "details": {
            "generated_at": latest.get("generated_at"),
            "age_hours": round(age_hours, 2),
            "max_age_hours": max_age_hours,
            "writes_database": False,
        },
    }


def _find_check(result: Dict[str, Any], name: str) -> Dict[str, Any]:
    for item in result.get("checks", []) or []:
        if item.get("name") == name:
            return item
    return {}


def build_scheduled_automation_health_summary(
    *,
    history_limit: int = 200,
    include_current_smoke: bool = False,
    current_smoke: Dict[str, Any] | None = None,
    freshness_max_age_hours: int = 26,
) -> Dict[str, Any]:
    """Build a machine-readable scheduled health summary without sending notifications."""
    records = _load_history(limit=history_limit)
    history = _history_summary(records)
    latest_history = history.get("latest") or {}
    current = current_smoke
    if current is None and include_current_smoke:
        current = collect_ai_automation_smoke(record_history=False, history_limit=history_limit)
    source_result = current or latest_history or {}
    source_kind = "current_smoke" if current else "latest_history"
    pchome_drift = _find_check(source_result, "PChome 受控落地 drift monitor")
    pchome_details = pchome_drift.get("details") or {}
    auto_policy_guard = _find_check(source_result, "PChome auto-policy authorization guard")
    auto_policy_details = auto_policy_guard.get("details") or {}
    if not auto_policy_guard or not auto_policy_details:
        auto_policy_guard = _pchome_auto_policy_authorization_guard_check()
        auto_policy_details = auto_policy_guard.get("details") or {}
    auto_policy_preflight = _find_check(source_result, "PChome auto-policy decision preflight")
    auto_policy_preflight_details = auto_policy_preflight.get("details") or {}
    if not auto_policy_preflight or not auto_policy_preflight_details:
        auto_policy_preflight = _pchome_auto_policy_decision_preflight_check()
        auto_policy_preflight_details = auto_policy_preflight.get("details") or {}
    auto_policy_closeout = _find_check(source_result, "PChome auto-policy decision closeout")
    auto_policy_closeout_details = auto_policy_closeout.get("details") or {}
    if not auto_policy_closeout or not auto_policy_closeout_details:
        auto_policy_closeout = _pchome_auto_policy_decision_closeout_check()
        auto_policy_closeout_details = auto_policy_closeout.get("details") or {}
    auto_policy_issuer_gate = _find_check(
        source_result,
        "PChome auto-policy authorization issuer gate",
    )
    auto_policy_issuer_gate_details = auto_policy_issuer_gate.get("details") or {}
    if not auto_policy_issuer_gate or not auto_policy_issuer_gate_details:
        auto_policy_issuer_gate = _pchome_auto_policy_authorization_issuer_gate_check()
        auto_policy_issuer_gate_details = auto_policy_issuer_gate.get("details") or {}
    auto_policy_signing_preflight = _find_check(
        source_result,
        "PChome auto-policy signing decision preflight",
    )
    auto_policy_signing_preflight_details = auto_policy_signing_preflight.get("details") or {}
    if not auto_policy_signing_preflight or not auto_policy_signing_preflight_details:
        auto_policy_signing_preflight = _pchome_auto_policy_signing_decision_preflight_check()
        auto_policy_signing_preflight_details = auto_policy_signing_preflight.get("details") or {}
    auto_policy_signing_closeout = _find_check(
        source_result,
        "PChome auto-policy signing decision closeout",
    )
    auto_policy_signing_closeout_details = auto_policy_signing_closeout.get("details") or {}
    if not auto_policy_signing_closeout or not auto_policy_signing_closeout_details:
        auto_policy_signing_closeout = _pchome_auto_policy_signing_decision_closeout_check()
        auto_policy_signing_closeout_details = auto_policy_signing_closeout.get("details") or {}
    auto_policy_signing_issuer_guard = _find_check(
        source_result,
        "PChome auto-policy signing issuer guard",
    )
    auto_policy_signing_issuer_guard_details = (
        auto_policy_signing_issuer_guard.get("details") or {}
    )
    if not auto_policy_signing_issuer_guard or not auto_policy_signing_issuer_guard_details:
        auto_policy_signing_issuer_guard = _pchome_auto_policy_signing_issuer_guard_check()
        auto_policy_signing_issuer_guard_details = (
            auto_policy_signing_issuer_guard.get("details") or {}
        )
    auto_policy_signing_issuer_closeout = _find_check(
        source_result,
        "PChome auto-policy signing issuer closeout",
    )
    auto_policy_signing_issuer_closeout_details = (
        auto_policy_signing_issuer_closeout.get("details") or {}
    )
    if (
        not auto_policy_signing_issuer_closeout
        or not auto_policy_signing_issuer_closeout_details
    ):
        auto_policy_signing_issuer_closeout = (
            _pchome_auto_policy_signing_issuer_closeout_check()
        )
        auto_policy_signing_issuer_closeout_details = (
            auto_policy_signing_issuer_closeout.get("details") or {}
        )
    auto_policy_signing_execution_preflight = _find_check(
        source_result,
        "PChome auto-policy signing execution preflight",
    )
    auto_policy_signing_execution_preflight_details = (
        auto_policy_signing_execution_preflight.get("details") or {}
    )
    if (
        not auto_policy_signing_execution_preflight
        or not auto_policy_signing_execution_preflight_details
    ):
        auto_policy_signing_execution_preflight = (
            _pchome_auto_policy_signing_execution_preflight_check()
        )
        auto_policy_signing_execution_preflight_details = (
            auto_policy_signing_execution_preflight.get("details") or {}
        )
    auto_policy_signing_execution_closeout = _find_check(
        source_result,
        "PChome auto-policy signing execution closeout",
    )
    auto_policy_signing_execution_closeout_details = (
        auto_policy_signing_execution_closeout.get("details") or {}
    )
    if (
        not auto_policy_signing_execution_closeout
        or not auto_policy_signing_execution_closeout_details
    ):
        auto_policy_signing_execution_closeout = (
            _pchome_auto_policy_signing_execution_closeout_check()
        )
        auto_policy_signing_execution_closeout_details = (
            auto_policy_signing_execution_closeout.get("details") or {}
        )
    auto_policy_signed_receipt_preflight = _find_check(
        source_result,
        "PChome auto-policy signed receipt preflight",
    )
    auto_policy_signed_receipt_preflight_details = (
        auto_policy_signed_receipt_preflight.get("details") or {}
    )
    if (
        not auto_policy_signed_receipt_preflight
        or not auto_policy_signed_receipt_preflight_details
    ):
        auto_policy_signed_receipt_preflight = (
            _pchome_auto_policy_signed_receipt_preflight_check()
        )
        auto_policy_signed_receipt_preflight_details = (
            auto_policy_signed_receipt_preflight.get("details") or {}
        )
    auto_policy_signed_receipt_closeout = _find_check(
        source_result,
        "PChome auto-policy signed receipt closeout",
    )
    auto_policy_signed_receipt_closeout_details = (
        auto_policy_signed_receipt_closeout.get("details") or {}
    )
    if (
        not auto_policy_signed_receipt_closeout
        or not auto_policy_signed_receipt_closeout_details
    ):
        auto_policy_signed_receipt_closeout = (
            _pchome_auto_policy_signed_receipt_closeout_check()
        )
        auto_policy_signed_receipt_closeout_details = (
            auto_policy_signed_receipt_closeout.get("details") or {}
        )
    auto_policy_signed_receipt_evidence_intake = _find_check(
        source_result,
        "PChome auto-policy signed receipt evidence intake",
    )
    auto_policy_signed_receipt_evidence_intake_details = (
        auto_policy_signed_receipt_evidence_intake.get("details") or {}
    )
    if (
        not auto_policy_signed_receipt_evidence_intake
        or not auto_policy_signed_receipt_evidence_intake_details
    ):
        auto_policy_signed_receipt_evidence_intake = (
            _pchome_auto_policy_signed_receipt_evidence_intake_check()
        )
        auto_policy_signed_receipt_evidence_intake_details = (
            auto_policy_signed_receipt_evidence_intake.get("details") or {}
        )
    auto_policy_detached_validation = _find_check(
        source_result,
        "PChome auto-policy detached verification evidence validation",
    )
    auto_policy_detached_validation_details = (
        auto_policy_detached_validation.get("details") or {}
    )
    if (
        not auto_policy_detached_validation
        or not auto_policy_detached_validation_details
    ):
        auto_policy_detached_validation = (
            _pchome_auto_policy_detached_verification_evidence_validation_check()
        )
        auto_policy_detached_validation_details = (
            auto_policy_detached_validation.get("details") or {}
        )
    auto_policy_verifier_receipt_closeout = _find_check(
        source_result,
        "PChome auto-policy verifier receipt closeout",
    )
    auto_policy_verifier_receipt_closeout_details = (
        auto_policy_verifier_receipt_closeout.get("details") or {}
    )
    if (
        not auto_policy_verifier_receipt_closeout
        or not auto_policy_verifier_receipt_closeout_details
    ):
        auto_policy_verifier_receipt_closeout = (
            _pchome_auto_policy_verifier_receipt_closeout_check()
        )
        auto_policy_verifier_receipt_closeout_details = (
            auto_policy_verifier_receipt_closeout.get("details") or {}
        )
    auto_policy_authorization_evidence_preflight = _find_check(
        source_result,
        "PChome auto-policy authorization evidence execution preflight",
    )
    auto_policy_authorization_evidence_preflight_details = (
        auto_policy_authorization_evidence_preflight.get("details") or {}
    )
    if (
        not auto_policy_authorization_evidence_preflight
        or not auto_policy_authorization_evidence_preflight_details
    ):
        auto_policy_authorization_evidence_preflight = (
            _pchome_auto_policy_authorization_evidence_execution_preflight_check()
        )
        auto_policy_authorization_evidence_preflight_details = (
            auto_policy_authorization_evidence_preflight.get("details") or {}
        )
    auto_policy_authorization_evidence_closeout = _find_check(
        source_result,
        "PChome auto-policy authorization evidence execution closeout",
    )
    auto_policy_authorization_evidence_closeout_details = (
        auto_policy_authorization_evidence_closeout.get("details") or {}
    )
    if (
        not auto_policy_authorization_evidence_closeout
        or not auto_policy_authorization_evidence_closeout_details
    ):
        auto_policy_authorization_evidence_closeout = (
            _pchome_auto_policy_authorization_evidence_execution_closeout_check()
        )
        auto_policy_authorization_evidence_closeout_details = (
            auto_policy_authorization_evidence_closeout.get("details") or {}
        )
    auto_policy_controlled_apply_final_preflight = _find_check(
        source_result,
        "PChome auto-policy controlled apply final preflight",
    )
    auto_policy_controlled_apply_final_preflight_details = (
        auto_policy_controlled_apply_final_preflight.get("details") or {}
    )
    if (
        not auto_policy_controlled_apply_final_preflight
        or not auto_policy_controlled_apply_final_preflight_details
    ):
        auto_policy_controlled_apply_final_preflight = (
            _pchome_auto_policy_controlled_apply_final_preflight_check()
        )
        auto_policy_controlled_apply_final_preflight_details = (
            auto_policy_controlled_apply_final_preflight.get("details") or {}
        )
    auto_policy_controlled_dry_run_package = _find_check(
        source_result,
        "PChome auto-policy controlled dry-run package",
    )
    auto_policy_controlled_dry_run_package_details = (
        auto_policy_controlled_dry_run_package.get("details") or {}
    )
    if (
        not auto_policy_controlled_dry_run_package
        or not auto_policy_controlled_dry_run_package_details
    ):
        auto_policy_controlled_dry_run_package = (
            _pchome_auto_policy_controlled_dry_run_package_check()
        )
        auto_policy_controlled_dry_run_package_details = (
            auto_policy_controlled_dry_run_package.get("details") or {}
        )
    auto_policy_controlled_dry_run_receipt_closeout = _find_check(
        source_result,
        "PChome auto-policy controlled dry-run receipt closeout",
    )
    auto_policy_controlled_dry_run_receipt_closeout_details = (
        auto_policy_controlled_dry_run_receipt_closeout.get("details") or {}
    )
    if (
        not auto_policy_controlled_dry_run_receipt_closeout
        or not auto_policy_controlled_dry_run_receipt_closeout_details
    ):
        auto_policy_controlled_dry_run_receipt_closeout = (
            _pchome_auto_policy_controlled_dry_run_receipt_closeout_check()
        )
        auto_policy_controlled_dry_run_receipt_closeout_details = (
            auto_policy_controlled_dry_run_receipt_closeout.get("details") or {}
        )
    auto_policy_controlled_dry_run_runner_readiness = _find_check(
        source_result,
        "PChome auto-policy controlled dry-run runner readiness",
    )
    auto_policy_controlled_dry_run_runner_readiness_details = (
        auto_policy_controlled_dry_run_runner_readiness.get("details") or {}
    )
    if (
        not auto_policy_controlled_dry_run_runner_readiness
        or not auto_policy_controlled_dry_run_runner_readiness_details
    ):
        auto_policy_controlled_dry_run_runner_readiness = (
            _pchome_auto_policy_controlled_dry_run_runner_readiness_check()
        )
        auto_policy_controlled_dry_run_runner_readiness_details = (
            auto_policy_controlled_dry_run_runner_readiness.get("details") or {}
        )
    surface_readback = _find_check(source_result, "AI surface HTML readback")
    surface_details = surface_readback.get("details") or {}
    sitewide_readback = _find_check(source_result, "Sitewide UI/UX Agent readback")
    sitewide_details = sitewide_readback.get("details") or {}
    visual_qa_readback = _find_check(source_result, "Sitewide visual QA readback")
    visual_qa_details = visual_qa_readback.get("details") or {}
    if not visual_qa_readback or not visual_qa_details:
        visual_qa_readback = _latest_sitewide_visual_qa_readback_check()
        visual_qa_details = visual_qa_readback.get("details") or {}
    external_mcp_rag = _find_check(source_result, "External MCP/RAG integration readback")
    external_mcp_rag_details = external_mcp_rag.get("details") or {}
    if not external_mcp_rag or not external_mcp_rag_details:
        external_mcp_rag = _external_mcp_rag_integration_check()
        external_mcp_rag_details = external_mcp_rag.get("details") or {}
    pixelrag_rag_replay = _find_check(source_result, "PixelRAG RAG candidate replay")
    pixelrag_rag_replay_details = pixelrag_rag_replay.get("details") or {}
    if not pixelrag_rag_replay or not pixelrag_rag_replay_details:
        pixelrag_rag_replay = _pixelrag_rag_candidate_replay_check()
        pixelrag_rag_replay_details = pixelrag_rag_replay.get("details") or {}
    pixelrag_source_contract_worker = _find_check(
        source_result,
        "PixelRAG source-contract replay worker",
    )
    pixelrag_source_contract_worker_details = (
        pixelrag_source_contract_worker.get("details") or {}
    )
    if (
        not pixelrag_source_contract_worker
        or not pixelrag_source_contract_worker_details
    ):
        pixelrag_source_contract_worker = _pixelrag_source_contract_replay_worker_check()
        pixelrag_source_contract_worker_details = (
            pixelrag_source_contract_worker.get("details") or {}
        )
    pixelrag_marketplace_adapter_preflight = _find_check(
        source_result,
        "PixelRAG marketplace adapter preflight",
    )
    pixelrag_marketplace_adapter_preflight_details = (
        pixelrag_marketplace_adapter_preflight.get("details") or {}
    )
    if (
        not pixelrag_marketplace_adapter_preflight
        or not pixelrag_marketplace_adapter_preflight_details
    ):
        pixelrag_marketplace_adapter_preflight = (
            _pixelrag_marketplace_adapter_preflight_check()
        )
        pixelrag_marketplace_adapter_preflight_details = (
            pixelrag_marketplace_adapter_preflight.get("details") or {}
        )
    pixelrag_marketplace_adapter_dry_run = _find_check(
        source_result,
        "PixelRAG marketplace adapter dry-run",
    )
    pixelrag_marketplace_adapter_dry_run_details = (
        pixelrag_marketplace_adapter_dry_run.get("details") or {}
    )
    if (
        not pixelrag_marketplace_adapter_dry_run
        or not pixelrag_marketplace_adapter_dry_run_details
    ):
        pixelrag_marketplace_adapter_dry_run = (
            _pixelrag_marketplace_adapter_dry_run_check()
        )
        pixelrag_marketplace_adapter_dry_run_details = (
            pixelrag_marketplace_adapter_dry_run.get("details") or {}
        )
    pixelrag_marketplace_identity_matcher = _find_check(
        source_result,
        "PixelRAG marketplace identity matcher replay",
    )
    pixelrag_marketplace_identity_matcher_details = (
        pixelrag_marketplace_identity_matcher.get("details") or {}
    )
    if (
        not pixelrag_marketplace_identity_matcher
        or not pixelrag_marketplace_identity_matcher_details
    ):
        pixelrag_marketplace_identity_matcher = (
            _pixelrag_marketplace_identity_matcher_replay_check()
        )
        pixelrag_marketplace_identity_matcher_details = (
            pixelrag_marketplace_identity_matcher.get("details") or {}
        )
    pixelrag_marketplace_promotion_gate = _find_check(
        source_result,
        "PixelRAG marketplace PromotionGate replay",
    )
    pixelrag_marketplace_promotion_gate_details = (
        pixelrag_marketplace_promotion_gate.get("details") or {}
    )
    if (
        not pixelrag_marketplace_promotion_gate
        or not pixelrag_marketplace_promotion_gate_details
    ):
        pixelrag_marketplace_promotion_gate = (
            _pixelrag_marketplace_promotion_gate_replay_check()
        )
        pixelrag_marketplace_promotion_gate_details = (
            pixelrag_marketplace_promotion_gate.get("details") or {}
        )
    pixelrag_marketplace_embedding_signature = _find_check(
        source_result,
        "PixelRAG marketplace embedding signature guard replay",
    )
    pixelrag_marketplace_embedding_signature_details = (
        pixelrag_marketplace_embedding_signature.get("details") or {}
    )
    if (
        not pixelrag_marketplace_embedding_signature
        or not pixelrag_marketplace_embedding_signature_details
    ):
        pixelrag_marketplace_embedding_signature = (
            _pixelrag_marketplace_embedding_signature_guard_replay_check()
        )
        pixelrag_marketplace_embedding_signature_details = (
            pixelrag_marketplace_embedding_signature.get("details") or {}
        )
    pixelrag_marketplace_candidate_knowledge = _find_check(
        source_result,
        "PixelRAG marketplace candidate knowledge replay",
    )
    pixelrag_marketplace_candidate_knowledge_details = (
        pixelrag_marketplace_candidate_knowledge.get("details") or {}
    )
    if (
        not pixelrag_marketplace_candidate_knowledge
        or not pixelrag_marketplace_candidate_knowledge_details
    ):
        pixelrag_marketplace_candidate_knowledge = (
            _pixelrag_marketplace_candidate_knowledge_replay_check()
        )
        pixelrag_marketplace_candidate_knowledge_details = (
            pixelrag_marketplace_candidate_knowledge.get("details") or {}
        )
    pixelrag_ocr_vlm_replay = _find_check(source_result, "PixelRAG OCR/VLM replay contract")
    pixelrag_ocr_vlm_replay_details = pixelrag_ocr_vlm_replay.get("details") or {}
    if not pixelrag_ocr_vlm_replay or not pixelrag_ocr_vlm_replay_details:
        pixelrag_ocr_vlm_replay = _pixelrag_ocr_vlm_replay_check()
        pixelrag_ocr_vlm_replay_details = pixelrag_ocr_vlm_replay.get("details") or {}
    pixelrag_vlm_route_readiness = _find_check(source_result, "PixelRAG VLM route readiness")
    pixelrag_vlm_route_readiness_details = pixelrag_vlm_route_readiness.get("details") or {}
    if not pixelrag_vlm_route_readiness or not pixelrag_vlm_route_readiness_details:
        pixelrag_vlm_route_readiness = _pixelrag_vlm_route_readiness_check()
        pixelrag_vlm_route_readiness_details = pixelrag_vlm_route_readiness.get("details") or {}
    pixelrag_vlm_replay_worker = _find_check(source_result, "PixelRAG VLM replay worker")
    pixelrag_vlm_replay_worker_details = pixelrag_vlm_replay_worker.get("details") or {}
    if not pixelrag_vlm_replay_worker or not pixelrag_vlm_replay_worker_details:
        pixelrag_vlm_replay_worker = _pixelrag_vlm_replay_worker_check()
        pixelrag_vlm_replay_worker_details = pixelrag_vlm_replay_worker.get("details") or {}
    pixelrag_platform_probe = _find_check(source_result, "PixelRAG platform probe readiness")
    pixelrag_platform_probe_details = pixelrag_platform_probe.get("details") or {}
    if not pixelrag_platform_probe or not pixelrag_platform_probe_details:
        pixelrag_platform_probe = _pixelrag_platform_probe_check()
        pixelrag_platform_probe_details = pixelrag_platform_probe.get("details") or {}
    pixelrag_platform_probe_worker = _find_check(source_result, "PixelRAG platform probe worker")
    pixelrag_platform_probe_worker_details = pixelrag_platform_probe_worker.get("details") or {}
    if not pixelrag_platform_probe_worker or not pixelrag_platform_probe_worker_details:
        pixelrag_platform_probe_worker = _pixelrag_platform_probe_worker_check()
        pixelrag_platform_probe_worker_details = pixelrag_platform_probe_worker.get("details") or {}
    security_governance = _find_check(
        source_result,
        "Security governance automation review",
    )
    security_governance_details = security_governance.get("details") or {}
    if not security_governance or not security_governance_details:
        security_governance = _security_governance_review_check()
        security_governance_details = security_governance.get("details") or {}
    smoke_status = source_result.get("status") or ("warning" if latest_history else "warning")
    freshness_family = _history_freshness_family(
        latest_history,
        max_age_hours=max(1, int(freshness_max_age_hours or 26)),
    )
    daily_rows = history.get("daily") or []
    history_count = len(records)
    families = [
        {
            "key": "ai_automation_smoke",
            "label": "AI automation smoke",
            "status": smoke_status,
            "summary": (
                f"Smoke source={source_kind}; "
                f"checks={(source_result.get('summary') or {}).get('total', 0)}"
            ),
            "next_machine_action": (
                "keep_monitoring"
                if smoke_status == "ok"
                else "inspect_warning_or_critical_checks"
            ),
            "details": {
                "source_kind": source_kind,
                "generated_at": source_result.get("generated_at"),
                "summary": source_result.get("summary") or {},
                "writes_database": False,
            },
        },
        {
            "key": "security_governance_review",
            "label": "Security governance automation review",
            "status": security_governance.get("status") or "warning",
            "summary": (
                security_governance.get("summary")
                or "Security governance review has no latest readback."
            ),
            "next_machine_action": security_governance_details.get(
                "next_machine_action"
            ) or "refresh_security_governance_review",
            "details": {
                "policy": security_governance_details.get("policy"),
                "review_status": security_governance_details.get("review_status"),
                "program_percent": security_governance_details.get("program_percent"),
                "asset_field_coverage_percent": security_governance_details.get(
                    "asset_field_coverage_percent"
                ),
                "asset_runtime_reconciliation_complete": bool(
                    security_governance_details.get(
                        "asset_runtime_reconciliation_complete"
                    )
                ),
                "runtime_closure_passed": int(
                    security_governance_details.get("runtime_closure_passed") or 0
                ),
                "runtime_closure_total": int(
                    security_governance_details.get("runtime_closure_total") or 0
                ),
                "blocking_failure_count": int(
                    security_governance_details.get("blocking_failure_count") or 0
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pchome_controlled_apply_drift_monitor",
            "label": "PChome controlled apply drift monitor",
            "status": pchome_drift.get("status") or "warning",
            "summary": pchome_drift.get("summary") or "PChome drift monitor has no latest check.",
            "next_machine_action": (
                "keep_monitoring_drift"
                if (pchome_drift.get("status") == "ok" and int(pchome_details.get("drift_count") or 0) == 0)
                else "run_pchome_drift_verifier_and_recovery_package"
            ),
            "details": {
                "result": pchome_details.get("result"),
                "source_receipt_replay_result": pchome_details.get("source_receipt_replay_result"),
                "selector_count": int(pchome_details.get("selector_count") or 0),
                "readback_pass_count": int(pchome_details.get("readback_pass_count") or 0),
                "drift_count": int(pchome_details.get("drift_count") or 0),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_authorization_guard",
            "label": "PChome auto-policy authorization guard",
            "status": auto_policy_guard.get("status") or "warning",
            "summary": (
                auto_policy_guard.get("summary")
                or "PChome auto-policy authorization guard has no latest check."
            ),
            "next_machine_action": auto_policy_details.get("next_machine_action")
            or (
                "continue_pchome_auto_policy_guard_monitoring"
                if auto_policy_guard.get("status") == "ok"
                else "refresh_pchome_auto_policy_authorization_guard"
            ),
            "details": {
                "policy": auto_policy_details.get("policy"),
                "result": auto_policy_details.get("result"),
                "guard_ready_count": int(auto_policy_details.get("guard_ready_count") or 0),
                "lane_guard_check_count": int(auto_policy_details.get("lane_guard_check_count") or 0),
                "lane_guard_pass_count": int(auto_policy_details.get("lane_guard_pass_count") or 0),
                "lane_guard_waiting_count": int(auto_policy_details.get("lane_guard_waiting_count") or 0),
                "authorization_request_closeout_ready_count": int(
                    auto_policy_details.get("authorization_request_closeout_ready_count") or 0
                ),
                "exact_request_payload_field_count": int(
                    auto_policy_details.get("exact_request_payload_field_count") or 0
                ),
                "machine_request_manifest_step_count": int(
                    auto_policy_details.get("machine_request_manifest_step_count") or 0
                ),
                "lane_entry_requirement_count": int(
                    auto_policy_details.get("lane_entry_requirement_count") or 0
                ),
                "reads_secret_count": int(auto_policy_details.get("reads_secret_count") or 0),
                "executes_sql_count": int(auto_policy_details.get("executes_sql_count") or 0),
                "writes_database_count": int(auto_policy_details.get("writes_database_count") or 0),
                "primary_human_gate_count": int(
                    auto_policy_details.get("primary_human_gate_count") or 0
                ),
                "manual_review_mode": auto_policy_details.get("manual_review_mode"),
                "machine_verifiable": bool(auto_policy_details.get("machine_verifiable")),
                "ready_for_database_apply_now": bool(
                    auto_policy_details.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_details.get("issues_database_apply_authorization")
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_decision_preflight",
            "label": "PChome auto-policy decision preflight",
            "status": auto_policy_preflight.get("status") or "warning",
            "summary": (
                auto_policy_preflight.get("summary")
                or "PChome auto-policy decision preflight has no latest check."
            ),
            "next_machine_action": auto_policy_preflight_details.get("next_machine_action")
            or (
                "continue_pchome_auto_policy_decision_preflight_monitoring"
                if auto_policy_preflight.get("status") == "ok"
                else "refresh_pchome_auto_policy_decision_preflight"
            ),
            "details": {
                "policy": auto_policy_preflight_details.get("policy"),
                "result": auto_policy_preflight_details.get("result"),
                "decision_preflight_ready_count": int(
                    auto_policy_preflight_details.get("decision_preflight_ready_count") or 0
                ),
                "authorization_lane_guard_ready_count": int(
                    auto_policy_preflight_details.get("authorization_lane_guard_ready_count") or 0
                ),
                "decision_preflight_check_count": int(
                    auto_policy_preflight_details.get("decision_preflight_check_count") or 0
                ),
                "decision_preflight_pass_count": int(
                    auto_policy_preflight_details.get("decision_preflight_pass_count") or 0
                ),
                "decision_preflight_waiting_count": int(
                    auto_policy_preflight_details.get("decision_preflight_waiting_count") or 0
                ),
                "decision_input_requirement_count": int(
                    auto_policy_preflight_details.get("decision_input_requirement_count") or 0
                ),
                "decision_rejection_reason_count": int(
                    auto_policy_preflight_details.get("decision_rejection_reason_count") or 0
                ),
                "machine_fetch_evidence_ready_count": int(
                    auto_policy_preflight_details.get("machine_fetch_evidence_ready_count") or 0
                ),
                "reads_secret_count": int(
                    auto_policy_preflight_details.get("reads_secret_count") or 0
                ),
                "executes_sql_count": int(
                    auto_policy_preflight_details.get("executes_sql_count") or 0
                ),
                "writes_database_count": int(
                    auto_policy_preflight_details.get("writes_database_count") or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_preflight_details.get("primary_human_gate_count") or 0
                ),
                "manual_review_mode": auto_policy_preflight_details.get("manual_review_mode"),
                "payload_source": auto_policy_preflight_details.get("payload_source"),
                "execute_fetch": bool(auto_policy_preflight_details.get("execute_fetch")),
                "outbound_network": bool(auto_policy_preflight_details.get("outbound_network")),
                "business_data_source": bool(
                    auto_policy_preflight_details.get("business_data_source")
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_preflight_details.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_preflight_details.get("issues_database_apply_authorization")
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_decision_closeout",
            "label": "PChome auto-policy decision closeout",
            "status": auto_policy_closeout.get("status") or "warning",
            "summary": (
                auto_policy_closeout.get("summary")
                or "PChome auto-policy decision closeout has no latest check."
            ),
            "next_machine_action": auto_policy_closeout_details.get("next_machine_action")
            or (
                "continue_pchome_auto_policy_decision_closeout_monitoring"
                if auto_policy_closeout.get("status") == "ok"
                else "refresh_pchome_auto_policy_decision_closeout"
            ),
            "details": {
                "policy": auto_policy_closeout_details.get("policy"),
                "result": auto_policy_closeout_details.get("result"),
                "decision_closeout_ready_count": int(
                    auto_policy_closeout_details.get("decision_closeout_ready_count") or 0
                ),
                "decision_preflight_ready_count": int(
                    auto_policy_closeout_details.get("decision_preflight_ready_count") or 0
                ),
                "decision_closeout_check_count": int(
                    auto_policy_closeout_details.get("decision_closeout_check_count") or 0
                ),
                "decision_closeout_pass_count": int(
                    auto_policy_closeout_details.get("decision_closeout_pass_count") or 0
                ),
                "decision_closeout_waiting_count": int(
                    auto_policy_closeout_details.get("decision_closeout_waiting_count") or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_closeout_details.get("post_apply_verifier_required_count") or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_closeout_details.get("same_run_truth_required_count") or 0
                ),
                "reads_secret_count": int(auto_policy_closeout_details.get("reads_secret_count") or 0),
                "executes_sql_count": int(auto_policy_closeout_details.get("executes_sql_count") or 0),
                "writes_database_count": int(
                    auto_policy_closeout_details.get("writes_database_count") or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_closeout_details.get("primary_human_gate_count") or 0
                ),
                "manual_review_mode": auto_policy_closeout_details.get("manual_review_mode"),
                "payload_source": auto_policy_closeout_details.get("payload_source"),
                "execute_fetch": bool(auto_policy_closeout_details.get("execute_fetch")),
                "outbound_network": bool(auto_policy_closeout_details.get("outbound_network")),
                "business_data_source": bool(auto_policy_closeout_details.get("business_data_source")),
                "ready_for_database_apply_now": bool(
                    auto_policy_closeout_details.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_closeout_details.get("issues_database_apply_authorization")
                ),
                "permits_future_authorization_decision_lane": bool(
                    auto_policy_closeout_details.get("permits_future_authorization_decision_lane")
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_authorization_issuer_gate",
            "label": "PChome auto-policy authorization issuer gate",
            "status": auto_policy_issuer_gate.get("status") or "warning",
            "summary": (
                auto_policy_issuer_gate.get("summary")
                or "PChome auto-policy authorization issuer gate has no latest check."
            ),
            "next_machine_action": auto_policy_issuer_gate_details.get("next_machine_action")
            or (
                "continue_pchome_auto_policy_authorization_issuer_gate_monitoring"
                if auto_policy_issuer_gate.get("status") == "ok"
                else "refresh_pchome_auto_policy_authorization_issuer_gate"
            ),
            "details": {
                "policy": auto_policy_issuer_gate_details.get("policy"),
                "result": auto_policy_issuer_gate_details.get("result"),
                "issuer_gate_ready_count": int(
                    auto_policy_issuer_gate_details.get("issuer_gate_ready_count") or 0
                ),
                "decision_closeout_ready_count": int(
                    auto_policy_issuer_gate_details.get("decision_closeout_ready_count") or 0
                ),
                "issuer_gate_check_count": int(
                    auto_policy_issuer_gate_details.get("issuer_gate_check_count") or 0
                ),
                "issuer_gate_pass_count": int(
                    auto_policy_issuer_gate_details.get("issuer_gate_pass_count") or 0
                ),
                "issuer_gate_waiting_count": int(
                    auto_policy_issuer_gate_details.get("issuer_gate_waiting_count") or 0
                ),
                "required_issuer_evidence_count": int(
                    auto_policy_issuer_gate_details.get("required_issuer_evidence_count") or 0
                ),
                "nonsecret_authorization_claim_count": int(
                    auto_policy_issuer_gate_details.get("nonsecret_authorization_claim_count") or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_issuer_gate_details.get("post_apply_verifier_required_count") or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_issuer_gate_details.get("same_run_truth_required_count") or 0
                ),
                "reads_secret_count": int(auto_policy_issuer_gate_details.get("reads_secret_count") or 0),
                "executes_sql_count": int(auto_policy_issuer_gate_details.get("executes_sql_count") or 0),
                "writes_database_count": int(
                    auto_policy_issuer_gate_details.get("writes_database_count") or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_issuer_gate_details.get("signs_database_apply_authorization_count") or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_issuer_gate_details.get("primary_human_gate_count") or 0
                ),
                "manual_review_mode": auto_policy_issuer_gate_details.get("manual_review_mode"),
                "payload_source": auto_policy_issuer_gate_details.get("payload_source"),
                "execute_fetch": bool(auto_policy_issuer_gate_details.get("execute_fetch")),
                "outbound_network": bool(auto_policy_issuer_gate_details.get("outbound_network")),
                "business_data_source": bool(
                    auto_policy_issuer_gate_details.get("business_data_source")
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_issuer_gate_details.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_issuer_gate_details.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_issuer_gate_details.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    auto_policy_issuer_gate_details.get("secret_material_included")
                ),
                "permits_future_authorization_issuer_lane": bool(
                    auto_policy_issuer_gate_details.get("permits_future_authorization_issuer_lane")
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signing_decision_preflight",
            "label": "PChome auto-policy signing decision preflight",
            "status": auto_policy_signing_preflight.get("status") or "warning",
            "summary": (
                auto_policy_signing_preflight.get("summary")
                or "PChome auto-policy signing decision preflight has no latest check."
            ),
            "next_machine_action": auto_policy_signing_preflight_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signing_decision_preflight_monitoring"
                if auto_policy_signing_preflight.get("status") == "ok"
                else "refresh_pchome_auto_policy_signing_decision_preflight"
            ),
            "details": {
                "policy": auto_policy_signing_preflight_details.get("policy"),
                "result": auto_policy_signing_preflight_details.get("result"),
                "signing_decision_preflight_ready_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signing_decision_preflight_ready_count"
                    )
                    or 0
                ),
                "authorization_issuer_gate_ready_count": int(
                    auto_policy_signing_preflight_details.get(
                        "authorization_issuer_gate_ready_count"
                    )
                    or 0
                ),
                "signing_decision_preflight_check_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signing_decision_preflight_check_count"
                    )
                    or 0
                ),
                "signing_decision_preflight_pass_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signing_decision_preflight_pass_count"
                    )
                    or 0
                ),
                "signing_decision_preflight_waiting_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signing_decision_preflight_waiting_count"
                    )
                    or 0
                ),
                "required_issuer_evidence_count": int(
                    auto_policy_signing_preflight_details.get(
                        "required_issuer_evidence_count"
                    )
                    or 0
                ),
                "nonsecret_authorization_claim_count": int(
                    auto_policy_signing_preflight_details.get(
                        "nonsecret_authorization_claim_count"
                    )
                    or 0
                ),
                "signing_decision_input_requirement_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signing_decision_input_requirement_count"
                    )
                    or 0
                ),
                "signing_decision_rejection_reason_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signing_decision_rejection_reason_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signing_preflight_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signing_preflight_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signing_preflight_details.get("reads_secret_count") or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signing_preflight_details.get("executes_sql_count") or 0
                ),
                "writes_database_count": int(
                    auto_policy_signing_preflight_details.get("writes_database_count") or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signing_preflight_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signing_preflight_details.get("primary_human_gate_count")
                    or 0
                ),
                "manual_review_mode": auto_policy_signing_preflight_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signing_preflight_details.get("payload_source"),
                "execute_fetch": bool(
                    auto_policy_signing_preflight_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signing_preflight_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signing_preflight_details.get("business_data_source")
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signing_preflight_details.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signing_preflight_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signing_preflight_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signing_preflight_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "allows_future_authorization_signing_decision_lane": bool(
                    auto_policy_signing_preflight_details.get(
                        "allows_future_authorization_signing_decision_lane"
                    )
                ),
                "rejects_direct_database_apply": bool(
                    auto_policy_signing_preflight_details.get("rejects_direct_database_apply")
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signing_decision_closeout",
            "label": "PChome auto-policy signing decision closeout",
            "status": auto_policy_signing_closeout.get("status") or "warning",
            "summary": (
                auto_policy_signing_closeout.get("summary")
                or "PChome auto-policy signing decision closeout has no latest check."
            ),
            "next_machine_action": auto_policy_signing_closeout_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signing_decision_closeout_monitoring"
                if auto_policy_signing_closeout.get("status") == "ok"
                else "refresh_pchome_auto_policy_signing_decision_closeout"
            ),
            "details": {
                "policy": auto_policy_signing_closeout_details.get("policy"),
                "result": auto_policy_signing_closeout_details.get("result"),
                "signing_decision_closeout_ready_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_closeout_ready_count"
                    )
                    or 0
                ),
                "signing_decision_preflight_ready_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_preflight_ready_count"
                    )
                    or 0
                ),
                "signing_decision_closeout_check_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_closeout_check_count"
                    )
                    or 0
                ),
                "signing_decision_closeout_pass_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_closeout_pass_count"
                    )
                    or 0
                ),
                "signing_decision_closeout_waiting_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_closeout_waiting_count"
                    )
                    or 0
                ),
                "signing_decision_preflight_check_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_preflight_check_count"
                    )
                    or 0
                ),
                "signing_decision_input_requirement_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_input_requirement_count"
                    )
                    or 0
                ),
                "signing_decision_rejection_reason_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signing_decision_rejection_reason_count"
                    )
                    or 0
                ),
                "required_issuer_evidence_count": int(
                    auto_policy_signing_closeout_details.get(
                        "required_issuer_evidence_count"
                    )
                    or 0
                ),
                "nonsecret_authorization_claim_count": int(
                    auto_policy_signing_closeout_details.get(
                        "nonsecret_authorization_claim_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signing_closeout_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signing_closeout_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signing_closeout_details.get("reads_secret_count") or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signing_closeout_details.get("executes_sql_count") or 0
                ),
                "writes_database_count": int(
                    auto_policy_signing_closeout_details.get("writes_database_count") or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signing_closeout_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signing_closeout_details.get("primary_human_gate_count")
                    or 0
                ),
                "manual_review_mode": auto_policy_signing_closeout_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signing_closeout_details.get("payload_source"),
                "execute_fetch": bool(
                    auto_policy_signing_closeout_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signing_closeout_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signing_closeout_details.get("business_data_source")
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signing_closeout_details.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signing_closeout_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signing_closeout_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signing_closeout_details.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signing_closeout_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "permits_future_unsigned_signing_decision_package_lane": bool(
                    auto_policy_signing_closeout_details.get(
                        "permits_future_unsigned_signing_decision_package_lane"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signing_issuer_guard",
            "label": "PChome auto-policy signing issuer guard",
            "status": auto_policy_signing_issuer_guard.get("status") or "warning",
            "summary": (
                auto_policy_signing_issuer_guard.get("summary")
                or "PChome auto-policy signing issuer guard has no latest check."
            ),
            "next_machine_action": auto_policy_signing_issuer_guard_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signing_issuer_guard_monitoring"
                if auto_policy_signing_issuer_guard.get("status") == "ok"
                else "refresh_pchome_auto_policy_signing_issuer_guard"
            ),
            "details": {
                "policy": auto_policy_signing_issuer_guard_details.get("policy"),
                "result": auto_policy_signing_issuer_guard_details.get("result"),
                "signing_issuer_guard_ready_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_issuer_guard_ready_count"
                    )
                    or 0
                ),
                "signing_issuer_guard_check_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_issuer_guard_check_count"
                    )
                    or 0
                ),
                "signing_issuer_guard_pass_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_issuer_guard_pass_count"
                    )
                    or 0
                ),
                "signing_issuer_guard_waiting_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_issuer_guard_waiting_count"
                    )
                    or 0
                ),
                "signing_decision_closeout_ready_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_decision_closeout_ready_count"
                    )
                    or 0
                ),
                "signing_decision_closeout_check_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_decision_closeout_check_count"
                    )
                    or 0
                ),
                "signing_decision_input_requirement_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_decision_input_requirement_count"
                    )
                    or 0
                ),
                "signing_decision_rejection_reason_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signing_decision_rejection_reason_count"
                    )
                    or 0
                ),
                "required_issuer_evidence_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "required_issuer_evidence_count"
                    )
                    or 0
                ),
                "nonsecret_authorization_claim_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "nonsecret_authorization_claim_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signing_issuer_guard_details.get("reads_secret_count") or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signing_issuer_guard_details.get("executes_sql_count") or 0
                ),
                "writes_database_count": int(
                    auto_policy_signing_issuer_guard_details.get("writes_database_count") or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signing_issuer_guard_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signing_issuer_guard_details.get("primary_human_gate_count")
                    or 0
                ),
                "manual_review_mode": auto_policy_signing_issuer_guard_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signing_issuer_guard_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signing_issuer_guard_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signing_issuer_guard_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signing_issuer_guard_details.get("business_data_source")
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signing_issuer_guard_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signing_issuer_guard_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signing_issuer_guard_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signing_issuer_guard_details.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signing_issuer_guard_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "ready_for_future_signable_request_boundary": bool(
                    auto_policy_signing_issuer_guard_details.get(
                        "ready_for_future_signable_request_boundary"
                    )
                ),
                "permits_future_authorization_signing_issuer_lane": bool(
                    auto_policy_signing_issuer_guard_details.get(
                        "permits_future_authorization_signing_issuer_lane"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signing_issuer_closeout",
            "label": "PChome auto-policy signing issuer closeout",
            "status": auto_policy_signing_issuer_closeout.get("status") or "warning",
            "summary": (
                auto_policy_signing_issuer_closeout.get("summary")
                or "PChome auto-policy signing issuer closeout has no latest check."
            ),
            "next_machine_action": auto_policy_signing_issuer_closeout_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signing_issuer_closeout_monitoring"
                if auto_policy_signing_issuer_closeout.get("status") == "ok"
                else "refresh_pchome_auto_policy_signing_issuer_closeout"
            ),
            "details": {
                "policy": auto_policy_signing_issuer_closeout_details.get("policy"),
                "result": auto_policy_signing_issuer_closeout_details.get("result"),
                "signing_issuer_closeout_ready_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_issuer_closeout_ready_count"
                    )
                    or 0
                ),
                "signing_issuer_closeout_check_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_issuer_closeout_check_count"
                    )
                    or 0
                ),
                "signing_issuer_closeout_pass_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_issuer_closeout_pass_count"
                    )
                    or 0
                ),
                "signing_issuer_closeout_waiting_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_issuer_closeout_waiting_count"
                    )
                    or 0
                ),
                "signing_issuer_guard_ready_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_issuer_guard_ready_count"
                    )
                    or 0
                ),
                "signing_issuer_guard_check_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_issuer_guard_check_count"
                    )
                    or 0
                ),
                "signing_decision_input_requirement_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_decision_input_requirement_count"
                    )
                    or 0
                ),
                "signing_decision_rejection_reason_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signing_decision_rejection_reason_count"
                    )
                    or 0
                ),
                "required_issuer_evidence_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "required_issuer_evidence_count"
                    )
                    or 0
                ),
                "nonsecret_authorization_claim_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "nonsecret_authorization_claim_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signing_issuer_closeout_details.get("reads_secret_count")
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signing_issuer_closeout_details.get("executes_sql_count")
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signing_issuer_closeout_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_signing_issuer_closeout_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signing_issuer_closeout_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signing_issuer_closeout_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signing_issuer_closeout_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "business_data_source"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "ready_for_future_final_signable_request_package": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "ready_for_future_final_signable_request_package"
                    )
                ),
                "permits_future_final_signable_request_package_lane": bool(
                    auto_policy_signing_issuer_closeout_details.get(
                        "permits_future_final_signable_request_package_lane"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signing_execution_preflight",
            "label": "PChome auto-policy signing execution preflight",
            "status": auto_policy_signing_execution_preflight.get("status") or "warning",
            "summary": (
                auto_policy_signing_execution_preflight.get("summary")
                or "PChome auto-policy signing execution preflight has no latest check."
            ),
            "next_machine_action": auto_policy_signing_execution_preflight_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signing_execution_preflight_monitoring"
                if auto_policy_signing_execution_preflight.get("status") == "ok"
                else "refresh_pchome_auto_policy_signing_execution_preflight"
            ),
            "details": {
                "policy": auto_policy_signing_execution_preflight_details.get("policy"),
                "result": auto_policy_signing_execution_preflight_details.get("result"),
                "signing_execution_preflight_ready_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_execution_preflight_ready_count"
                    )
                    or 0
                ),
                "signing_execution_preflight_check_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_execution_preflight_check_count"
                    )
                    or 0
                ),
                "signing_execution_preflight_pass_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_execution_preflight_pass_count"
                    )
                    or 0
                ),
                "signing_execution_preflight_waiting_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_execution_preflight_waiting_count"
                    )
                    or 0
                ),
                "signing_issuer_closeout_ready_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_issuer_closeout_ready_count"
                    )
                    or 0
                ),
                "signing_issuer_closeout_check_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_issuer_closeout_check_count"
                    )
                    or 0
                ),
                "final_signable_request_package_ready_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "final_signable_request_package_ready_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "signing_execution_input_requirement_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_execution_input_requirement_count"
                    )
                    or 0
                ),
                "signing_execution_abort_condition_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signing_execution_abort_condition_count"
                    )
                    or 0
                ),
                "rollback_boundary_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "rollback_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signing_execution_preflight_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_signing_execution_preflight_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signing_execution_preflight_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signing_execution_preflight_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signing_execution_preflight_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "business_data_source"
                    )
                ),
                "secret_reference_mode": auto_policy_signing_execution_preflight_details.get(
                    "secret_reference_mode"
                ),
                "command_preview_redacts_secret_values": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "command_preview_redacts_secret_values"
                    )
                ),
                "command_preview_executes_in_preview": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "command_preview_executes_in_preview"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "ready_for_future_signing_execution_preflight": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "ready_for_future_signing_execution_preflight"
                    )
                ),
                "permits_future_explicit_authorization_signing_execution_lane": bool(
                    auto_policy_signing_execution_preflight_details.get(
                        "permits_future_explicit_authorization_signing_execution_lane"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signing_execution_closeout",
            "label": "PChome auto-policy signing execution closeout",
            "status": auto_policy_signing_execution_closeout.get("status") or "warning",
            "summary": (
                auto_policy_signing_execution_closeout.get("summary")
                or "PChome auto-policy signing execution closeout has no latest check."
            ),
            "next_machine_action": auto_policy_signing_execution_closeout_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signing_execution_closeout_monitoring"
                if auto_policy_signing_execution_closeout.get("status") == "ok"
                else "refresh_pchome_auto_policy_signing_execution_closeout"
            ),
            "details": {
                "policy": auto_policy_signing_execution_closeout_details.get("policy"),
                "result": auto_policy_signing_execution_closeout_details.get("result"),
                "signing_execution_closeout_ready_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_closeout_ready_count"
                    )
                    or 0
                ),
                "signing_execution_closeout_check_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_closeout_check_count"
                    )
                    or 0
                ),
                "signing_execution_closeout_pass_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_closeout_pass_count"
                    )
                    or 0
                ),
                "signing_execution_closeout_waiting_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_closeout_waiting_count"
                    )
                    or 0
                ),
                "signing_execution_preflight_ready_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_preflight_ready_count"
                    )
                    or 0
                ),
                "signing_execution_preflight_check_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_preflight_check_count"
                    )
                    or 0
                ),
                "unsigned_signed_authorization_receipt_boundary_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "unsigned_signed_authorization_receipt_boundary_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "signing_execution_input_requirement_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_input_requirement_count"
                    )
                    or 0
                ),
                "signing_execution_abort_condition_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signing_execution_abort_condition_count"
                    )
                    or 0
                ),
                "rollback_boundary_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "rollback_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signing_execution_closeout_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_signing_execution_closeout_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signing_execution_closeout_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signing_execution_closeout_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signing_execution_closeout_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "business_data_source"
                    )
                ),
                "secret_reference_mode": auto_policy_signing_execution_closeout_details.get(
                    "secret_reference_mode"
                ),
                "command_preview_redacts_secret_values": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "command_preview_redacts_secret_values"
                    )
                ),
                "command_preview_executes_in_preview": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "command_preview_executes_in_preview"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "signature_material_included"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "ready_for_future_signing_execution_closeout": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "ready_for_future_signing_execution_closeout"
                    )
                ),
                "ready_for_future_unsigned_signed_authorization_receipt_boundary": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "ready_for_future_unsigned_signed_authorization_receipt_boundary"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_lane": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "ready_for_future_signed_authorization_receipt_lane"
                    )
                ),
                "permits_future_unsigned_signed_authorization_receipt_boundary": bool(
                    auto_policy_signing_execution_closeout_details.get(
                        "permits_future_unsigned_signed_authorization_receipt_boundary"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signed_receipt_preflight",
            "label": "PChome auto-policy signed receipt preflight",
            "status": auto_policy_signed_receipt_preflight.get("status") or "warning",
            "summary": (
                auto_policy_signed_receipt_preflight.get("summary")
                or "PChome auto-policy signed receipt preflight has no latest check."
            ),
            "next_machine_action": auto_policy_signed_receipt_preflight_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signed_receipt_preflight_monitoring"
                if auto_policy_signed_receipt_preflight.get("status") == "ok"
                else "refresh_pchome_auto_policy_signed_receipt_preflight"
            ),
            "details": {
                "policy": auto_policy_signed_receipt_preflight_details.get("policy"),
                "result": auto_policy_signed_receipt_preflight_details.get("result"),
                "signed_receipt_preflight_ready_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signed_receipt_preflight_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_check_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signed_receipt_preflight_check_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_pass_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signed_receipt_preflight_pass_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_waiting_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signed_receipt_preflight_waiting_count"
                    )
                    or 0
                ),
                "signing_execution_closeout_ready_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signing_execution_closeout_ready_count"
                    )
                    or 0
                ),
                "signing_execution_closeout_check_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signing_execution_closeout_check_count"
                    )
                    or 0
                ),
                "unsigned_signed_authorization_receipt_boundary_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "unsigned_signed_authorization_receipt_boundary_count"
                    )
                    or 0
                ),
                "external_signing_receipt_evidence_boundary_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "external_signing_receipt_evidence_boundary_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "signing_execution_input_requirement_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signing_execution_input_requirement_count"
                    )
                    or 0
                ),
                "signing_execution_abort_condition_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signing_execution_abort_condition_count"
                    )
                    or 0
                ),
                "rollback_boundary_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "rollback_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signed_receipt_preflight_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_signed_receipt_preflight_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signed_receipt_preflight_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signed_receipt_preflight_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signed_receipt_preflight_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "business_data_source"
                    )
                ),
                "secret_reference_mode": auto_policy_signed_receipt_preflight_details.get(
                    "secret_reference_mode"
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signature_material_included"
                    )
                ),
                "signer_key_id_reference_only": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signer_key_id_reference_only"
                    )
                ),
                "signature_algorithm_reference_only": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signature_algorithm_reference_only"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_preflight": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "ready_for_future_signed_authorization_receipt_preflight"
                    )
                ),
                "can_enter_future_external_signing_receipt_evidence_boundary": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "can_enter_future_external_signing_receipt_evidence_boundary"
                    )
                ),
                "ready_for_future_external_signing_receipt_evidence_boundary": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "ready_for_future_external_signing_receipt_evidence_boundary"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_lane": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "ready_for_future_signed_authorization_receipt_lane"
                    )
                ),
                "permits_future_external_signing_receipt_evidence_boundary": bool(
                    auto_policy_signed_receipt_preflight_details.get(
                        "permits_future_external_signing_receipt_evidence_boundary"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signed_receipt_closeout",
            "label": "PChome auto-policy signed receipt closeout",
            "status": auto_policy_signed_receipt_closeout.get("status") or "warning",
            "summary": (
                auto_policy_signed_receipt_closeout.get("summary")
                or "PChome auto-policy signed receipt closeout has no latest check."
            ),
            "next_machine_action": auto_policy_signed_receipt_closeout_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signed_receipt_closeout_monitoring"
                if auto_policy_signed_receipt_closeout.get("status") == "ok"
                else "refresh_pchome_auto_policy_signed_receipt_closeout"
            ),
            "details": {
                "policy": auto_policy_signed_receipt_closeout_details.get("policy"),
                "result": auto_policy_signed_receipt_closeout_details.get("result"),
                "signed_receipt_closeout_ready_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_receipt_closeout_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_closeout_check_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "signed_receipt_closeout_pass_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_receipt_closeout_pass_count"
                    )
                    or 0
                ),
                "signed_receipt_closeout_waiting_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_receipt_closeout_waiting_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_ready_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_receipt_preflight_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_check_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_receipt_preflight_check_count"
                    )
                    or 0
                ),
                "external_signing_receipt_evidence_boundary_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "external_signing_receipt_evidence_boundary_count"
                    )
                    or 0
                ),
                "detached_receipt_verification_boundary_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "detached_receipt_verification_boundary_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "detached_receipt_verification_check_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "detached_receipt_verification_check_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "signing_execution_input_requirement_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signing_execution_input_requirement_count"
                    )
                    or 0
                ),
                "signing_execution_abort_condition_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signing_execution_abort_condition_count"
                    )
                    or 0
                ),
                "rollback_boundary_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "rollback_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signed_receipt_closeout_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_signed_receipt_closeout_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signed_receipt_closeout_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signed_receipt_closeout_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_signed_receipt_closeout_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "business_data_source"
                    )
                ),
                "secret_reference_mode": auto_policy_signed_receipt_closeout_details.get(
                    "secret_reference_mode"
                ),
                "requires_detached_signature_verification": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "requires_detached_signature_verification"
                    )
                ),
                "detached_signature_verification_performed": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "detached_signature_verification_performed"
                    )
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signature_material_included"
                    )
                ),
                "signer_key_id_reference_only": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signer_key_id_reference_only"
                    )
                ),
                "signature_algorithm_reference_only": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signature_algorithm_reference_only"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_closeout": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "ready_for_future_signed_authorization_receipt_closeout"
                    )
                ),
                "can_enter_future_detached_receipt_verification_boundary": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "can_enter_future_detached_receipt_verification_boundary"
                    )
                ),
                "ready_for_future_detached_receipt_verification_boundary": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "ready_for_future_detached_receipt_verification_boundary"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_verification_lane": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "ready_for_future_signed_authorization_receipt_verification_lane"
                    )
                ),
                "permits_future_detached_receipt_verification_boundary": bool(
                    auto_policy_signed_receipt_closeout_details.get(
                        "permits_future_detached_receipt_verification_boundary"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_signed_receipt_evidence_intake",
            "label": "PChome auto-policy signed receipt evidence intake",
            "status": auto_policy_signed_receipt_evidence_intake.get("status") or "warning",
            "summary": (
                auto_policy_signed_receipt_evidence_intake.get("summary")
                or "PChome auto-policy signed receipt evidence intake has no latest check."
            ),
            "next_machine_action": auto_policy_signed_receipt_evidence_intake_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_signed_receipt_evidence_intake_monitoring"
                if auto_policy_signed_receipt_evidence_intake.get("status") == "ok"
                else "refresh_pchome_auto_policy_signed_receipt_evidence_intake"
            ),
            "details": {
                "policy": auto_policy_signed_receipt_evidence_intake_details.get("policy"),
                "result": auto_policy_signed_receipt_evidence_intake_details.get("result"),
                "signed_receipt_evidence_intake_ready_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_evidence_intake_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_evidence_intake_check_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_evidence_intake_check_count"
                    )
                    or 0
                ),
                "signed_receipt_evidence_intake_pass_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_evidence_intake_pass_count"
                    )
                    or 0
                ),
                "signed_receipt_evidence_intake_waiting_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_evidence_intake_waiting_count"
                    )
                    or 0
                ),
                "signed_receipt_closeout_ready_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_closeout_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_closeout_check_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_ready_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_preflight_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_preflight_check_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_receipt_preflight_check_count"
                    )
                    or 0
                ),
                "external_signing_receipt_evidence_boundary_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "external_signing_receipt_evidence_boundary_count"
                    )
                    or 0
                ),
                "detached_receipt_verification_boundary_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "detached_receipt_verification_boundary_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_schema_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "detached_verification_evidence_schema_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "detached_receipt_verification_check_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "detached_receipt_verification_check_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_field_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "detached_verification_evidence_field_count"
                    )
                    or 0
                ),
                "detached_verification_acceptance_gate_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "detached_verification_acceptance_gate_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "rollback_boundary_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "rollback_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_signed_receipt_evidence_intake_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_signed_receipt_evidence_intake_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "execute_fetch"
                    )
                ),
                "outbound_network": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "outbound_network"
                    )
                ),
                "business_data_source": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "business_data_source"
                    )
                ),
                "secret_reference_mode": auto_policy_signed_receipt_evidence_intake_details.get(
                    "secret_reference_mode"
                ),
                "requires_detached_signature_verification": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "requires_detached_signature_verification"
                    )
                ),
                "detached_signature_verification_performed": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "detached_signature_verification_performed"
                    )
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signature_material_included"
                    )
                ),
                "signer_key_id_reference_only": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signer_key_id_reference_only"
                    )
                ),
                "signature_algorithm_reference_only": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signature_algorithm_reference_only"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "accepts_plaintext_secret"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_evidence_intake": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "ready_for_future_signed_authorization_receipt_evidence_intake"
                    )
                ),
                "can_enter_future_detached_verification_evidence_validation": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "can_enter_future_detached_verification_evidence_validation"
                    )
                ),
                "external_signed_authorization_receipt_evidence_schema_ready": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "external_signed_authorization_receipt_evidence_schema_ready"
                    )
                ),
                "ready_for_future_detached_verification_evidence_schema": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "ready_for_future_detached_verification_evidence_schema"
                    )
                ),
                "permits_future_detached_verification_evidence_validation": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "permits_future_detached_verification_evidence_validation"
                    )
                ),
                "performs_detached_signature_verification": bool(
                    auto_policy_signed_receipt_evidence_intake_details.get(
                        "performs_detached_signature_verification"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_detached_verification_evidence_validation",
            "label": "PChome auto-policy detached verification evidence validation",
            "status": auto_policy_detached_validation.get("status") or "warning",
            "summary": (
                auto_policy_detached_validation.get("summary")
                or "PChome auto-policy detached verification evidence validation has no latest check."
            ),
            "next_machine_action": auto_policy_detached_validation_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_detached_verification_evidence_validation_monitoring"
                if auto_policy_detached_validation.get("status") == "ok"
                else "refresh_pchome_auto_policy_detached_verification_evidence_validation"
            ),
            "details": {
                "policy": auto_policy_detached_validation_details.get("policy"),
                "result": auto_policy_detached_validation_details.get("result"),
                "detached_verification_evidence_validation_ready_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_evidence_validation_ready_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_check_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_evidence_validation_check_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_pass_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_evidence_validation_pass_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_waiting_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_evidence_validation_waiting_count"
                    )
                    or 0
                ),
                "signed_receipt_evidence_intake_ready_count": int(
                    auto_policy_detached_validation_details.get(
                        "signed_receipt_evidence_intake_ready_count"
                    )
                    or 0
                ),
                "signed_receipt_evidence_intake_check_count": int(
                    auto_policy_detached_validation_details.get(
                        "signed_receipt_evidence_intake_check_count"
                    )
                    or 0
                ),
                "signed_receipt_closeout_check_count": int(
                    auto_policy_detached_validation_details.get(
                        "signed_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_schema_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_evidence_schema_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_boundary_count": int(
                    auto_policy_detached_validation_details.get(
                        "verifier_receipt_closeout_boundary_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_detached_validation_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_detached_validation_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "detached_receipt_verification_check_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_receipt_verification_check_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_field_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_evidence_field_count"
                    )
                    or 0
                ),
                "detached_verification_acceptance_gate_count": int(
                    auto_policy_detached_validation_details.get(
                        "detached_verification_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_field_count": int(
                    auto_policy_detached_validation_details.get(
                        "verifier_receipt_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_acceptance_gate_count": int(
                    auto_policy_detached_validation_details.get(
                        "verifier_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_detached_validation_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_detached_validation_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_detached_validation_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_detached_validation_details.get("reads_secret_count")
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_detached_validation_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_detached_validation_details.get("executes_sql_count")
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_detached_validation_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_detached_validation_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_detached_validation_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_detached_validation_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_detached_validation_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_detached_validation_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_detached_validation_details.get("outbound_network")
                ),
                "business_data_source": bool(
                    auto_policy_detached_validation_details.get("business_data_source")
                ),
                "secret_reference_mode": auto_policy_detached_validation_details.get(
                    "secret_reference_mode"
                ),
                "requires_detached_signature_verification": bool(
                    auto_policy_detached_validation_details.get(
                        "requires_detached_signature_verification"
                    )
                ),
                "detached_signature_verification_performed": bool(
                    auto_policy_detached_validation_details.get(
                        "detached_signature_verification_performed"
                    )
                ),
                "verifier_receipt_persisted": bool(
                    auto_policy_detached_validation_details.get(
                        "verifier_receipt_persisted"
                    )
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    auto_policy_detached_validation_details.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_detached_validation_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_detached_validation_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_detached_validation_details.get(
                        "signature_material_included"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_detached_validation_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_detached_validation_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_detached_validation_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_detached_validation_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_detached_validation_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    auto_policy_detached_validation_details.get(
                        "accepts_plaintext_secret"
                    )
                ),
                "ready_for_future_detached_verification_evidence_validation": bool(
                    auto_policy_detached_validation_details.get(
                        "ready_for_future_detached_verification_evidence_validation"
                    )
                ),
                "can_enter_future_verifier_receipt_closeout": bool(
                    auto_policy_detached_validation_details.get(
                        "can_enter_future_verifier_receipt_closeout"
                    )
                ),
                "verifier_receipt_closeout_boundary_ready": bool(
                    auto_policy_detached_validation_details.get(
                        "verifier_receipt_closeout_boundary_ready"
                    )
                ),
                "ready_for_future_verifier_receipt_closeout_boundary": bool(
                    auto_policy_detached_validation_details.get(
                        "ready_for_future_verifier_receipt_closeout_boundary"
                    )
                ),
                "permits_future_verifier_receipt_closeout": bool(
                    auto_policy_detached_validation_details.get(
                        "permits_future_verifier_receipt_closeout"
                    )
                ),
                "persists_verifier_receipt": bool(
                    auto_policy_detached_validation_details.get(
                        "persists_verifier_receipt"
                    )
                ),
                "performs_detached_signature_verification": bool(
                    auto_policy_detached_validation_details.get(
                        "performs_detached_signature_verification"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_verifier_receipt_closeout",
            "label": "PChome auto-policy verifier receipt closeout",
            "status": auto_policy_verifier_receipt_closeout.get("status") or "warning",
            "summary": (
                auto_policy_verifier_receipt_closeout.get("summary")
                or "PChome auto-policy verifier receipt closeout has no latest check."
            ),
            "next_machine_action": auto_policy_verifier_receipt_closeout_details.get(
                "next_machine_action"
            )
            or (
                "continue_pchome_auto_policy_verifier_receipt_closeout_monitoring"
                if auto_policy_verifier_receipt_closeout.get("status") == "ok"
                else "refresh_pchome_auto_policy_verifier_receipt_closeout"
            ),
            "details": {
                "policy": auto_policy_verifier_receipt_closeout_details.get("policy"),
                "result": auto_policy_verifier_receipt_closeout_details.get("result"),
                "verifier_receipt_closeout_ready_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_closeout_ready_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_check_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_pass_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_closeout_pass_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_waiting_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_closeout_waiting_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_ready_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "detached_verification_evidence_validation_ready_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_check_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "detached_verification_evidence_validation_check_count"
                    )
                    or 0
                ),
                "signed_receipt_evidence_intake_check_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "signed_receipt_evidence_intake_check_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_boundary_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_closeout_boundary_count"
                    )
                    or 0
                ),
                "verifier_receipt_evidence_handoff_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_evidence_handoff_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_field_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_acceptance_gate_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_evidence_handoff_field_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_evidence_handoff_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_handoff_acceptance_gate_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_handoff_acceptance_gate_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_field_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "detached_verification_evidence_field_count"
                    )
                    or 0
                ),
                "detached_verification_acceptance_gate_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "detached_verification_acceptance_gate_count"
                    )
                    or 0
                ),
                "operator_held_secret_boundary_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "operator_held_secret_boundary_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_mode": auto_policy_verifier_receipt_closeout_details.get(
                    "manual_review_mode"
                ),
                "payload_source": auto_policy_verifier_receipt_closeout_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_verifier_receipt_closeout_details.get("execute_fetch")
                ),
                "outbound_network": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "outbound_network"
                    )
                ),
                "business_data_source": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "business_data_source"
                    )
                ),
                "secret_reference_mode": auto_policy_verifier_receipt_closeout_details.get(
                    "secret_reference_mode"
                ),
                "requires_detached_signature_verification": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "requires_detached_signature_verification"
                    )
                ),
                "detached_signature_verification_performed": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "detached_signature_verification_performed"
                    )
                ),
                "verifier_receipt_persisted": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_persisted"
                    )
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "signature_material_included"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "accepts_plaintext_secret"
                    )
                ),
                "ready_for_future_verifier_receipt_closeout": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "ready_for_future_verifier_receipt_closeout"
                    )
                ),
                "can_enter_future_database_apply_authorization_verifier_handoff": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "can_enter_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "verifier_receipt_evidence_handoff_ready": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "verifier_receipt_evidence_handoff_ready"
                    )
                ),
                "ready_for_future_verifier_receipt_evidence_handoff": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "ready_for_future_verifier_receipt_evidence_handoff"
                    )
                ),
                "permits_future_database_apply_authorization_verifier_handoff": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "permits_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "persists_verifier_receipt": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "persists_verifier_receipt"
                    )
                ),
                "performs_detached_signature_verification": bool(
                    auto_policy_verifier_receipt_closeout_details.get(
                        "performs_detached_signature_verification"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_authorization_evidence_execution_preflight",
            "label": "PChome auto-policy authorization evidence execution preflight",
            "status": (
                auto_policy_authorization_evidence_preflight.get("status")
                or "warning"
            ),
            "summary": (
                auto_policy_authorization_evidence_preflight.get("summary")
                or (
                    "PChome auto-policy authorization evidence execution "
                    "preflight has no latest check."
                )
            ),
            "next_machine_action": (
                auto_policy_authorization_evidence_preflight_details.get(
                    "next_machine_action"
                )
                or (
                    "continue_pchome_auto_policy_authorization_evidence_execution_preflight_monitoring"
                    if auto_policy_authorization_evidence_preflight.get("status")
                    == "ok"
                    else "refresh_pchome_auto_policy_authorization_evidence_execution_preflight"
                )
            ),
            "details": {
                "policy": auto_policy_authorization_evidence_preflight_details.get(
                    "policy"
                ),
                "result": auto_policy_authorization_evidence_preflight_details.get(
                    "result"
                ),
                "authorization_evidence_execution_preflight_ready_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_preflight_ready_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_check_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_preflight_check_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_pass_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_preflight_pass_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_waiting_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_preflight_waiting_count"
                    )
                    or 0
                ),
                "authorization_verifier_receipt_closeout_ready_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_verifier_receipt_closeout_ready_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_check_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_check_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "detached_verification_evidence_validation_check_count"
                    )
                    or 0
                ),
                "verifier_receipt_evidence_handoff_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_evidence_handoff_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_preflight_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_field_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_field_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_field_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_evidence_handoff_field_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_evidence_handoff_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_handoff_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_handoff_acceptance_gate_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_required_count": int(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "manual_review_required_count"
                    )
                    or 0
                ),
                "manual_review_mode": (
                    auto_policy_authorization_evidence_preflight_details.get(
                        "manual_review_mode"
                    )
                ),
                "payload_source": auto_policy_authorization_evidence_preflight_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "execute_fetch"
                    )
                ),
                "outbound_network": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "outbound_network"
                    )
                ),
                "business_data_source": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "business_data_source"
                    )
                ),
                "ready_for_future_database_apply_authorization_verifier_handoff": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "ready_for_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "can_enter_future_authorization_evidence_execution_closeout": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "can_enter_future_authorization_evidence_execution_closeout"
                    )
                ),
                "authorization_evidence_execution_preflight_ready": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "authorization_evidence_execution_preflight_ready"
                    )
                ),
                "ready_for_future_authorization_evidence_execution_preflight": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "ready_for_future_authorization_evidence_execution_preflight"
                    )
                ),
                "permits_future_authorization_evidence_execution_closeout": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "permits_future_authorization_evidence_execution_closeout"
                    )
                ),
                "requires_detached_signature_verification": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "requires_detached_signature_verification"
                    )
                ),
                "detached_signature_verification_performed": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "detached_signature_verification_performed"
                    )
                ),
                "verifier_receipt_persisted": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "verifier_receipt_persisted"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "signature_material_included"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "accepts_plaintext_secret"
                    )
                ),
                "reads_secret_in_preview": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "reads_secret_in_preview"
                    )
                ),
                "executes_authorization_evidence": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "executes_authorization_evidence"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_authorization_evidence_preflight_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_authorization_evidence_execution_closeout",
            "label": "PChome auto-policy authorization evidence execution closeout",
            "status": (
                auto_policy_authorization_evidence_closeout.get("status")
                or "warning"
            ),
            "summary": (
                auto_policy_authorization_evidence_closeout.get("summary")
                or (
                    "PChome auto-policy authorization evidence execution "
                    "closeout has no latest check."
                )
            ),
            "next_machine_action": (
                auto_policy_authorization_evidence_closeout_details.get(
                    "next_machine_action"
                )
                or (
                    "continue_pchome_auto_policy_authorization_evidence_execution_closeout_monitoring"
                    if auto_policy_authorization_evidence_closeout.get("status")
                    == "ok"
                    else "refresh_pchome_auto_policy_authorization_evidence_execution_closeout"
                )
            ),
            "details": {
                "policy": auto_policy_authorization_evidence_closeout_details.get(
                    "policy"
                ),
                "result": auto_policy_authorization_evidence_closeout_details.get(
                    "result"
                ),
                "authorization_evidence_execution_closeout_ready_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_ready_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_check_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_check_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_pass_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_pass_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_waiting_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_waiting_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_ready_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_preflight_ready_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_check_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_preflight_check_count"
                    )
                    or 0
                ),
                "authorization_verifier_receipt_closeout_ready_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_verifier_receipt_closeout_ready_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_check_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "detached_verification_evidence_validation_check_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "detached_verification_evidence_validation_check_count"
                    )
                    or 0
                ),
                "verifier_receipt_evidence_handoff_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_evidence_handoff_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_preflight_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_count"
                    )
                    or 0
                ),
                "database_apply_final_verifier_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "database_apply_final_verifier_gate_count"
                    )
                    or 0
                ),
                "database_apply_authorization_final_verifier_gate_ready_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "database_apply_authorization_final_verifier_gate_ready_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_field_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_field_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_acceptance_gate_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_field_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_field_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_field_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "verifier_receipt_evidence_handoff_field_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_evidence_handoff_field_count"
                    )
                    or 0
                ),
                "verifier_receipt_handoff_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_handoff_acceptance_gate_count"
                    )
                    or 0
                ),
                "required_external_receipt_evidence_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "required_external_receipt_evidence_count"
                    )
                    or 0
                ),
                "external_receipt_acceptance_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "external_receipt_acceptance_gate_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_required_count": int(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "manual_review_required_count"
                    )
                    or 0
                ),
                "manual_review_mode": (
                    auto_policy_authorization_evidence_closeout_details.get(
                        "manual_review_mode"
                    )
                ),
                "payload_source": auto_policy_authorization_evidence_closeout_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "execute_fetch"
                    )
                ),
                "outbound_network": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "outbound_network"
                    )
                ),
                "business_data_source": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "business_data_source"
                    )
                ),
                "ready_for_future_database_apply_authorization_final_verifier_gate": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "ready_for_future_database_apply_authorization_final_verifier_gate"
                    )
                ),
                "can_enter_future_database_apply_controlled_apply_final_preflight": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "can_enter_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "authorization_evidence_execution_closeout_ready": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "authorization_evidence_execution_closeout_ready"
                    )
                ),
                "ready_for_future_authorization_evidence_execution_closeout": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "ready_for_future_authorization_evidence_execution_closeout"
                    )
                ),
                "permits_future_database_apply_authorization_final_verifier_gate": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "permits_future_database_apply_authorization_final_verifier_gate"
                    )
                ),
                "permits_future_database_apply_controlled_apply_final_preflight": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "permits_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "requires_detached_signature_verification": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "requires_detached_signature_verification"
                    )
                ),
                "detached_signature_verification_performed": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "detached_signature_verification_performed"
                    )
                ),
                "verifier_receipt_persisted": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "verifier_receipt_persisted"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "signed_authorization_receipt_included"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "signature_material_included"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "accepts_plaintext_secret"
                    )
                ),
                "reads_secret_in_preview": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "reads_secret_in_preview"
                    )
                ),
                "executes_authorization_evidence": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "executes_authorization_evidence"
                    )
                ),
                "executes_database_apply": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "executes_database_apply"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "database_apply_authorized": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "database_apply_authorized"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_authorization_evidence_closeout_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_controlled_apply_final_preflight",
            "label": "PChome auto-policy controlled apply final preflight",
            "status": (
                auto_policy_controlled_apply_final_preflight.get("status")
                or "warning"
            ),
            "summary": (
                auto_policy_controlled_apply_final_preflight.get("summary")
                or (
                    "PChome auto-policy controlled apply final preflight "
                    "has no latest check."
                )
            ),
            "next_machine_action": (
                auto_policy_controlled_apply_final_preflight_details.get(
                    "next_machine_action"
                )
                or (
                    "continue_pchome_auto_policy_controlled_apply_final_preflight_monitoring"
                    if auto_policy_controlled_apply_final_preflight.get("status")
                    == "ok"
                    else "refresh_pchome_auto_policy_controlled_apply_final_preflight"
                )
            ),
            "details": {
                "policy": auto_policy_controlled_apply_final_preflight_details.get(
                    "policy"
                ),
                "result": auto_policy_controlled_apply_final_preflight_details.get(
                    "result"
                ),
                "controlled_apply_final_preflight_ready_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_ready_count"
                    )
                    or 0
                ),
                "controlled_apply_final_preflight_check_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_check_count"
                    )
                    or 0
                ),
                "controlled_apply_final_preflight_pass_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_pass_count"
                    )
                    or 0
                ),
                "controlled_apply_final_preflight_waiting_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_waiting_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_ready_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_evidence_execution_closeout_ready_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_check_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_evidence_execution_closeout_check_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_ready_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_evidence_execution_preflight_ready_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_preflight_check_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_evidence_execution_preflight_check_count"
                    )
                    or 0
                ),
                "authorization_verifier_receipt_closeout_ready_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_verifier_receipt_closeout_ready_count"
                    )
                    or 0
                ),
                "verifier_receipt_closeout_check_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "verifier_receipt_closeout_check_count"
                    )
                    or 0
                ),
                "database_apply_final_verifier_gate_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "database_apply_final_verifier_gate_count"
                    )
                    or 0
                ),
                "database_apply_authorization_final_verifier_gate_ready_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "database_apply_authorization_final_verifier_gate_ready_count"
                    )
                    or 0
                ),
                "controlled_apply_final_preflight_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_count"
                    )
                    or 0
                ),
                "controlled_apply_final_preflight_field_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_field_count"
                    )
                    or 0
                ),
                "controlled_apply_final_preflight_acceptance_gate_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_acceptance_gate_count"
                    )
                    or 0
                ),
                "rollback_binding_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_binding_count"
                    )
                    or 0
                ),
                "rollback_binding_field_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_binding_field_count"
                    )
                    or 0
                ),
                "post_apply_verifier_binding_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "post_apply_verifier_binding_count"
                    )
                    or 0
                ),
                "post_apply_verifier_binding_field_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "post_apply_verifier_binding_field_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_field_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_evidence_execution_closeout_field_count"
                    )
                    or 0
                ),
                "authorization_evidence_execution_closeout_acceptance_gate_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "authorization_evidence_execution_closeout_acceptance_gate_count"
                    )
                    or 0
                ),
                "post_apply_verifier_required_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "post_apply_verifier_required_count"
                    )
                    or 0
                ),
                "same_run_truth_required_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "same_run_truth_required_count"
                    )
                    or 0
                ),
                "reads_secret_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "reads_secret_count"
                    )
                    or 0
                ),
                "executes_script_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_script_count"
                    )
                    or 0
                ),
                "executes_endpoint_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_endpoint_count"
                    )
                    or 0
                ),
                "executes_sql_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_sql_count"
                    )
                    or 0
                ),
                "writes_database_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "writes_database_count"
                    )
                    or 0
                ),
                "signs_database_apply_authorization_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "signs_database_apply_authorization_count"
                    )
                    or 0
                ),
                "primary_human_gate_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "primary_human_gate_count"
                    )
                    or 0
                ),
                "manual_review_required_count": int(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "manual_review_required_count"
                    )
                    or 0
                ),
                "manual_review_mode": (
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "manual_review_mode"
                    )
                ),
                "payload_source": auto_policy_controlled_apply_final_preflight_details.get(
                    "payload_source"
                ),
                "execute_fetch": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "execute_fetch"
                    )
                ),
                "outbound_network": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "outbound_network"
                    )
                ),
                "business_data_source": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "business_data_source"
                    )
                ),
                "ready_for_future_database_apply_controlled_apply_final_preflight": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "ready_for_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_package": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "can_enter_future_database_apply_controlled_dry_run_package"
                    )
                ),
                "controlled_apply_final_preflight_ready": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "controlled_apply_final_preflight_ready"
                    )
                ),
                "rollback_binding_ready": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_binding_ready"
                    )
                ),
                "post_apply_verifier_binding_ready": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "post_apply_verifier_binding_ready"
                    )
                ),
                "rollback_bound": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_bound"
                    )
                ),
                "post_apply_verifier_bound": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "post_apply_verifier_bound"
                    )
                ),
                "dry_run_only": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "dry_run_only"
                    )
                ),
                "check_mode_only": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "check_mode_only"
                    )
                ),
                "rollback_execution_authorized": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_execution_authorized"
                    )
                ),
                "rollback_executes_sql": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_executes_sql"
                    )
                ),
                "rollback_writes_database": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "rollback_writes_database"
                    )
                ),
                "post_apply_verifier_execution_authorized_in_preview": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "post_apply_verifier_execution_authorized_in_preview"
                    )
                ),
                "permits_future_database_apply_controlled_dry_run_package": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "permits_future_database_apply_controlled_dry_run_package"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "accepts_plaintext_secret"
                    )
                ),
                "reads_secret_in_preview": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "reads_secret_in_preview"
                    )
                ),
                "signature_material_included": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "signature_material_included"
                    )
                ),
                "secret_material_included": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "secret_material_included"
                    )
                ),
                "secret_material_required_in_preview": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "secret_material_required_in_preview"
                    )
                ),
                "executes_authorization_evidence": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_authorization_evidence"
                    )
                ),
                "executes_database_apply": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_database_apply"
                    )
                ),
                "executes_endpoint": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_endpoint"
                    )
                ),
                "executes_sql": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "executes_sql"
                    )
                ),
                "ready_for_database_apply_now": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "ready_for_database_apply_now"
                    )
                ),
                "database_apply_authorized": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "database_apply_authorized"
                    )
                ),
                "issues_database_apply_authorization": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "issues_database_apply_authorization"
                    )
                ),
                "signs_database_apply_authorization": bool(
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "signs_database_apply_authorization"
                    )
                ),
                "next_machine_action": (
                    auto_policy_controlled_apply_final_preflight_details.get(
                        "next_machine_action"
                    )
                    or (
                        "continue_pchome_auto_policy_controlled_apply_final_preflight_monitoring"
                        if auto_policy_controlled_apply_final_preflight.get("status")
                        == "ok"
                        else "refresh_pchome_auto_policy_controlled_apply_final_preflight"
                    )
                ),
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_controlled_dry_run_package",
            "label": "PChome auto-policy controlled dry-run package",
            "status": (
                auto_policy_controlled_dry_run_package.get("status")
                or "warning"
            ),
            "summary": (
                auto_policy_controlled_dry_run_package.get("summary")
                or (
                    "PChome auto-policy controlled dry-run package "
                    "has no latest check."
                )
            ),
            "next_machine_action": (
                auto_policy_controlled_dry_run_package_details.get(
                    "next_machine_action"
                )
                or (
                    "continue_pchome_auto_policy_controlled_dry_run_package_monitoring"
                    if auto_policy_controlled_dry_run_package.get("status") == "ok"
                    else "refresh_pchome_auto_policy_controlled_dry_run_package"
                )
            ),
            "details": {
                **auto_policy_controlled_dry_run_package_details,
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_controlled_dry_run_receipt_closeout",
            "label": "PChome auto-policy controlled dry-run receipt closeout",
            "status": (
                auto_policy_controlled_dry_run_receipt_closeout.get("status")
                or "warning"
            ),
            "summary": (
                auto_policy_controlled_dry_run_receipt_closeout.get("summary")
                or (
                    "PChome auto-policy controlled dry-run receipt closeout "
                    "has no latest check."
                )
            ),
            "next_machine_action": (
                auto_policy_controlled_dry_run_receipt_closeout_details.get(
                    "next_machine_action"
                )
                or (
                    "continue_pchome_auto_policy_controlled_dry_run_receipt_closeout_monitoring"
                    if auto_policy_controlled_dry_run_receipt_closeout.get("status")
                    == "ok"
                    else "refresh_pchome_auto_policy_controlled_dry_run_receipt_closeout"
                )
            ),
            "details": {
                **auto_policy_controlled_dry_run_receipt_closeout_details,
                "writes_database": False,
            },
        },
        {
            "key": "pchome_auto_policy_controlled_dry_run_runner_readiness",
            "label": "PChome auto-policy controlled dry-run runner readiness",
            "status": (
                auto_policy_controlled_dry_run_runner_readiness.get("status")
                or "warning"
            ),
            "summary": (
                auto_policy_controlled_dry_run_runner_readiness.get("summary")
                or (
                    "PChome auto-policy controlled dry-run runner readiness "
                    "has no latest check."
                )
            ),
            "next_machine_action": (
                auto_policy_controlled_dry_run_runner_readiness_details.get(
                    "next_machine_action"
                )
                or (
                    "continue_pchome_auto_policy_controlled_dry_run_runner_readiness_monitoring"
                    if auto_policy_controlled_dry_run_runner_readiness.get("status")
                    == "ok"
                    else "refresh_pchome_auto_policy_controlled_dry_run_runner_readiness"
                )
            ),
            "details": {
                **auto_policy_controlled_dry_run_runner_readiness_details,
                "writes_database": False,
            },
        },
        {
            "key": "ai_surface_html_readback",
            "label": "AI surface HTML readback",
            "status": surface_readback.get("status") or "warning",
            "summary": surface_readback.get("summary") or "AI surface HTML readback has no latest check.",
            "next_machine_action": (
                "keep_surface_readback_in_ai_smoke"
                if surface_readback.get("status") == "ok"
                else "repair_ai_surface_html_contract"
            ),
            "details": {
                "policy": surface_details.get("policy"),
                "checked_surface_count": int(surface_details.get("checked_surface_count") or 0),
                "pass_count": int(surface_details.get("pass_count") or 0),
                "failed_count": int(surface_details.get("failed_count") or 0),
                "forbidden_leak_count": int(surface_details.get("forbidden_leak_count") or 0),
                "writes_database": False,
            },
        },
        {
            "key": "sitewide_ui_ux_agent",
            "label": "Sitewide UI/UX Agent",
            "status": sitewide_readback.get("status") or "warning",
            "summary": sitewide_readback.get("summary") or "Sitewide UI/UX Agent has no latest check.",
            "next_machine_action": (
                "keep_sitewide_ui_ux_agent_monitoring"
                if sitewide_readback.get("status") == "ok"
                else "build_sitewide_ui_ux_repair_package"
            ),
            "details": {
                "policy": sitewide_details.get("policy"),
                "template_count": int(sitewide_details.get("template_count") or 0),
                "high_priority_template_count": int(sitewide_details.get("high_priority_template_count") or 0),
                "compact_guardrail_count": int(sitewide_details.get("compact_guardrail_count") or 0),
                "issue_surface_count": int(sitewide_details.get("issue_surface_count") or 0),
                "raw_engineering_issue_count": int(sitewide_details.get("raw_engineering_issue_count") or 0),
                "repair_package_status": sitewide_details.get("repair_package_status"),
                "repair_action_count": int(sitewide_details.get("repair_action_count") or 0),
                "writes_database": False,
            },
        },
        {
            "key": "sitewide_visual_qa",
            "label": "Sitewide visual QA",
            "status": visual_qa_readback.get("status") or "warning",
            "summary": visual_qa_readback.get("summary") or "Sitewide visual QA has no latest check.",
            "next_machine_action": (
                "keep_sitewide_visual_qa_monitoring"
                if visual_qa_readback.get("status") == "ok"
                else "run_sitewide_visual_qa_and_publish_artifact"
            ),
            "details": {
                "policy": visual_qa_details.get("policy"),
                "result_count": int(visual_qa_details.get("result_count") or 0),
                "route_count": int(visual_qa_details.get("route_count") or 0),
                "viewport_count": int(visual_qa_details.get("viewport_count") or 0),
                "failed_count": int(visual_qa_details.get("failed_count") or 0),
                "overflow_issue_count": int(visual_qa_details.get("overflow_issue_count") or 0),
                "visual_offender_count": int(visual_qa_details.get("visual_offender_count") or 0),
                "artifact_path": visual_qa_details.get("artifact_path"),
                "artifact_generated_at": visual_qa_details.get("artifact_generated_at"),
                "stale": bool(visual_qa_details.get("stale")),
                "writes_database": False,
            },
        },
        {
            "key": "external_mcp_rag_integration",
            "label": "External MCP/RAG integration",
            "status": external_mcp_rag.get("status") or "warning",
            "summary": (
                external_mcp_rag.get("summary")
                or "External MCP/RAG integration has no latest readback."
            ),
            "next_machine_action": external_mcp_rag_details.get("next_machine_action")
            or "refresh_external_mcp_rag_integration_readback",
            "details": {
                "policy": external_mcp_rag_details.get("policy"),
                "integration_status": external_mcp_rag_details.get("integration_status"),
                "total_capabilities": int(
                    external_mcp_rag_details.get("total_capabilities") or 0
                ),
                "absorbed_count": int(external_mcp_rag_details.get("absorbed_count") or 0),
                "unresolved_count": int(
                    external_mcp_rag_details.get("unresolved_count") or 0
                ),
                "mcp_router_enabled": bool(
                    external_mcp_rag_details.get("mcp_router_enabled")
                ),
                "rag_enabled": bool(external_mcp_rag_details.get("rag_enabled")),
                "gemini_hard_disabled": bool(
                    external_mcp_rag_details.get("gemini_hard_disabled")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_rag_candidate_replay",
            "label": "PixelRAG RAG candidate replay",
            "status": pixelrag_rag_replay.get("status") or "warning",
            "summary": (
                pixelrag_rag_replay.get("summary")
                or "PixelRAG RAG candidate replay has no latest readback."
            ),
            "next_machine_action": pixelrag_rag_replay_details.get("next_machine_action")
            or "run_pixelrag_rag_candidate_replay_readback",
            "details": {
                "policy": pixelrag_rag_replay_details.get("policy"),
                "receipt_count": int(pixelrag_rag_replay_details.get("receipt_count") or 0),
                "eligible_count": int(pixelrag_rag_replay_details.get("eligible_count") or 0),
                "blocked_count": int(pixelrag_rag_replay_details.get("blocked_count") or 0),
                "invalid_count": int(pixelrag_rag_replay_details.get("invalid_count") or 0),
                "visual_receipt_count": int(
                    pixelrag_rag_replay_details.get("visual_receipt_count") or 0
                ),
                "platform_probe_worker_receipt_count": int(
                    pixelrag_rag_replay_details.get("platform_probe_worker_receipt_count") or 0
                ),
                "source_contract_fallback_count": int(
                    pixelrag_rag_replay_details.get("source_contract_fallback_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_rag_replay_details.get("capture_runtime_gap_count") or 0
                ),
                "visual_barrier_count": int(
                    pixelrag_rag_replay_details.get("visual_barrier_count") or 0
                ),
                "missing_file_count": int(
                    pixelrag_rag_replay_details.get("missing_file_count") or 0
                ),
                "blocked_pages_are_not_product_data": bool(
                    pixelrag_rag_replay_details.get("blocked_pages_are_not_product_data")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_source_contract_replay_worker",
            "label": "PixelRAG source-contract replay worker",
            "status": pixelrag_source_contract_worker.get("status") or "warning",
            "summary": (
                pixelrag_source_contract_worker.get("summary")
                or "PixelRAG source-contract replay worker has no latest readback."
            ),
            "next_machine_action": pixelrag_source_contract_worker_details.get(
                "next_machine_action"
            )
            or "run_pixelrag_source_contract_replay_worker_dry_run",
            "details": {
                "policy": pixelrag_source_contract_worker_details.get("policy"),
                "candidate_count": int(
                    pixelrag_source_contract_worker_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_source_contract_worker_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_source_contract_worker_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_source_contract_worker_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_source_contract_worker_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_source_contract_worker_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_source_contract_worker_details.get("capture_runtime_gap_count") or 0
                ),
                "network_call_performed": bool(
                    pixelrag_source_contract_worker_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_source_contract_worker_details.get("model_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_source_contract_worker_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_marketplace_adapter_preflight",
            "label": "PixelRAG marketplace adapter preflight",
            "status": pixelrag_marketplace_adapter_preflight.get("status") or "warning",
            "summary": (
                pixelrag_marketplace_adapter_preflight.get("summary")
                or "PixelRAG marketplace adapter preflight has no latest readback."
            ),
            "next_machine_action": pixelrag_marketplace_adapter_preflight_details.get(
                "next_machine_action"
            )
            or "run_pixelrag_marketplace_adapter_preflight_dry_run",
            "details": {
                "policy": pixelrag_marketplace_adapter_preflight_details.get("policy"),
                "candidate_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_marketplace_adapter_preflight_details.get("capture_runtime_gap_count") or 0
                ),
                "network_call_performed": bool(
                    pixelrag_marketplace_adapter_preflight_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_marketplace_adapter_preflight_details.get("model_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_marketplace_adapter_preflight_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_marketplace_adapter_dry_run",
            "label": "PixelRAG marketplace adapter dry-run",
            "status": pixelrag_marketplace_adapter_dry_run.get("status") or "warning",
            "summary": (
                pixelrag_marketplace_adapter_dry_run.get("summary")
                or "PixelRAG marketplace adapter dry-run has no latest readback."
            ),
            "next_machine_action": pixelrag_marketplace_adapter_dry_run_details.get(
                "next_machine_action"
            )
            or "run_pixelrag_marketplace_adapter_dry_run",
            "details": {
                "policy": pixelrag_marketplace_adapter_dry_run_details.get("policy"),
                "candidate_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("capture_runtime_gap_count") or 0
                ),
                "field_contract_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("field_contract_count") or 0
                ),
                "dry_run_output_contract_count": int(
                    pixelrag_marketplace_adapter_dry_run_details.get("dry_run_output_contract_count") or 0
                ),
                "network_call_performed": bool(
                    pixelrag_marketplace_adapter_dry_run_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_marketplace_adapter_dry_run_details.get("model_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_marketplace_adapter_dry_run_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_marketplace_identity_matcher_replay",
            "label": "PixelRAG marketplace identity matcher replay",
            "status": pixelrag_marketplace_identity_matcher.get("status") or "warning",
            "summary": (
                pixelrag_marketplace_identity_matcher.get("summary")
                or "PixelRAG marketplace identity matcher replay has no latest readback."
            ),
            "next_machine_action": pixelrag_marketplace_identity_matcher_details.get(
                "next_machine_action"
            )
            or "run_pixelrag_marketplace_identity_matcher_replay",
            "details": {
                "policy": pixelrag_marketplace_identity_matcher_details.get("policy"),
                "candidate_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("capture_runtime_gap_count") or 0
                ),
                "identity_candidate_count": int(
                    pixelrag_marketplace_identity_matcher_details.get("identity_candidate_count") or 0
                ),
                "network_call_performed": bool(
                    pixelrag_marketplace_identity_matcher_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_marketplace_identity_matcher_details.get("model_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_marketplace_identity_matcher_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_marketplace_promotion_gate_replay",
            "label": "PixelRAG marketplace PromotionGate replay",
            "status": pixelrag_marketplace_promotion_gate.get("status") or "warning",
            "summary": (
                pixelrag_marketplace_promotion_gate.get("summary")
                or "PixelRAG marketplace PromotionGate replay has no latest readback."
            ),
            "next_machine_action": pixelrag_marketplace_promotion_gate_details.get(
                "next_machine_action"
            )
            or "run_marketplace_promotion_gate_replay",
            "details": {
                "policy": pixelrag_marketplace_promotion_gate_details.get("policy"),
                "candidate_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("capture_runtime_gap_count") or 0
                ),
                "promotion_candidate_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("promotion_candidate_count") or 0
                ),
                "embedding_signature_guard_ready_count": int(
                    pixelrag_marketplace_promotion_gate_details.get("embedding_signature_guard_ready_count") or 0
                ),
                "network_call_performed": bool(
                    pixelrag_marketplace_promotion_gate_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_marketplace_promotion_gate_details.get("model_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_marketplace_promotion_gate_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_marketplace_embedding_signature_guard_replay",
            "label": "PixelRAG marketplace embedding signature guard replay",
            "status": (
                pixelrag_marketplace_embedding_signature.get("status") or "warning"
            ),
            "summary": (
                pixelrag_marketplace_embedding_signature.get("summary")
                or "PixelRAG marketplace embedding signature guard replay has no latest readback."
            ),
            "next_machine_action": pixelrag_marketplace_embedding_signature_details.get(
                "next_machine_action"
            )
            or "run_marketplace_embedding_signature_guard_replay",
            "details": {
                "policy": pixelrag_marketplace_embedding_signature_details.get("policy"),
                "candidate_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("capture_runtime_gap_count") or 0
                ),
                "signature_guard_candidate_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("signature_guard_candidate_count") or 0
                ),
                "candidate_knowledge_ready_count": int(
                    pixelrag_marketplace_embedding_signature_details.get("candidate_knowledge_ready_count") or 0
                ),
                "expected_embedding_signatures": list(
                    pixelrag_marketplace_embedding_signature_details.get(
                        "expected_embedding_signatures"
                    )
                    or []
                ),
                "network_call_performed": bool(
                    pixelrag_marketplace_embedding_signature_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_marketplace_embedding_signature_details.get("model_call_performed")
                ),
                "embedding_generation_performed": bool(
                    pixelrag_marketplace_embedding_signature_details.get(
                        "embedding_generation_performed"
                    )
                ),
                "artifact_write_performed": bool(
                    pixelrag_marketplace_embedding_signature_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_marketplace_candidate_knowledge_replay",
            "label": "PixelRAG marketplace candidate knowledge replay",
            "status": (
                pixelrag_marketplace_candidate_knowledge.get("status") or "warning"
            ),
            "summary": (
                pixelrag_marketplace_candidate_knowledge.get("summary")
                or "PixelRAG marketplace candidate knowledge replay has no latest readback."
            ),
            "next_machine_action": pixelrag_marketplace_candidate_knowledge_details.get(
                "next_machine_action"
            )
            or "run_marketplace_candidate_knowledge_replay",
            "details": {
                "policy": pixelrag_marketplace_candidate_knowledge_details.get("policy"),
                "candidate_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("ready_count") or 0
                ),
                "blocked_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("blocked_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("dry_run_count") or 0
                ),
                "executed_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("executed_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("receipt_written_count") or 0
                ),
                "capture_runtime_gap_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("capture_runtime_gap_count") or 0
                ),
                "knowledge_candidate_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("knowledge_candidate_count") or 0
                ),
                "internal_rag_ready_count": int(
                    pixelrag_marketplace_candidate_knowledge_details.get("internal_rag_ready_count") or 0
                ),
                "expected_embedding_signatures": list(
                    pixelrag_marketplace_candidate_knowledge_details.get(
                        "expected_embedding_signatures"
                    )
                    or []
                ),
                "network_call_performed": bool(
                    pixelrag_marketplace_candidate_knowledge_details.get("network_call_performed")
                ),
                "model_call_performed": bool(
                    pixelrag_marketplace_candidate_knowledge_details.get("model_call_performed")
                ),
                "embedding_generation_performed": bool(
                    pixelrag_marketplace_candidate_knowledge_details.get(
                        "embedding_generation_performed"
                    )
                ),
                "artifact_write_performed": bool(
                    pixelrag_marketplace_candidate_knowledge_details.get("artifact_write_performed")
                ),
                "writes_ai_insights": bool(
                    pixelrag_marketplace_candidate_knowledge_details.get("writes_ai_insights")
                ),
                "writes_price_tables": bool(
                    pixelrag_marketplace_candidate_knowledge_details.get("writes_price_tables")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_ocr_vlm_replay",
            "label": "PixelRAG OCR/VLM replay contract",
            "status": pixelrag_ocr_vlm_replay.get("status") or "warning",
            "summary": (
                pixelrag_ocr_vlm_replay.get("summary")
                or "PixelRAG OCR/VLM replay contract has no latest readback."
            ),
            "next_machine_action": pixelrag_ocr_vlm_replay_details.get("next_machine_action")
            or "run_pixelrag_ocr_vlm_replay_contract_readback",
            "details": {
                "policy": pixelrag_ocr_vlm_replay_details.get("policy"),
                "receipt_count": int(pixelrag_ocr_vlm_replay_details.get("receipt_count") or 0),
                "replay_ready_count": int(
                    pixelrag_ocr_vlm_replay_details.get("replay_ready_count") or 0
                ),
                "blocked_count": int(pixelrag_ocr_vlm_replay_details.get("blocked_count") or 0),
                "invalid_count": int(pixelrag_ocr_vlm_replay_details.get("invalid_count") or 0),
                "tile_input_count": int(
                    pixelrag_ocr_vlm_replay_details.get("tile_input_count") or 0
                ),
                "field_contract_count": int(
                    pixelrag_ocr_vlm_replay_details.get("field_contract_count") or 0
                ),
                "extraction_execution_performed": bool(
                    pixelrag_ocr_vlm_replay_details.get("extraction_execution_performed")
                ),
                "blocked_pages_are_not_product_data": bool(
                    pixelrag_ocr_vlm_replay_details.get("blocked_pages_are_not_product_data")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_vlm_route_readiness",
            "label": "PixelRAG VLM route readiness",
            "status": pixelrag_vlm_route_readiness.get("status") or "warning",
            "summary": (
                pixelrag_vlm_route_readiness.get("summary")
                or "PixelRAG VLM route readiness has no latest readback."
            ),
            "next_machine_action": pixelrag_vlm_route_readiness_details.get("next_machine_action")
            or "run_pixelrag_vlm_route_readiness_readback",
            "details": {
                "policy": pixelrag_vlm_route_readiness_details.get("policy"),
                "host_count": int(pixelrag_vlm_route_readiness_details.get("host_count") or 0),
                "reachable_host_count": int(
                    pixelrag_vlm_route_readiness_details.get("reachable_host_count") or 0
                ),
                "configured_model": pixelrag_vlm_route_readiness_details.get("configured_model"),
                "configured_model_available_count": int(
                    pixelrag_vlm_route_readiness_details.get("configured_model_available_count") or 0
                ),
                "candidate_model": pixelrag_vlm_route_readiness_details.get("candidate_model"),
                "candidate_host": pixelrag_vlm_route_readiness_details.get("candidate_host"),
                "candidate_provider": pixelrag_vlm_route_readiness_details.get("candidate_provider"),
                "tag_model_route_ready": bool(
                    pixelrag_vlm_route_readiness_details.get("tag_model_route_ready")
                ),
                "model_route_ready": bool(
                    pixelrag_vlm_route_readiness_details.get("model_route_ready")
                ),
                "generate_probe_performed": bool(
                    pixelrag_vlm_route_readiness_details.get("generate_probe_performed")
                ),
                "generate_probe_ok_count": int(
                    pixelrag_vlm_route_readiness_details.get("generate_probe_ok_count") or 0
                ),
                "generate_route_ready": (
                    pixelrag_vlm_route_readiness_details.get("generate_route_ready")
                    if pixelrag_vlm_route_readiness_details.get("generate_probe_performed")
                    else None
                ),
                "generate_ready_model": pixelrag_vlm_route_readiness_details.get("generate_ready_model"),
                "generate_ready_host": pixelrag_vlm_route_readiness_details.get("generate_ready_host"),
                "generate_ready_provider": pixelrag_vlm_route_readiness_details.get("generate_ready_provider"),
                "model_call_performed": bool(
                    pixelrag_vlm_route_readiness_details.get("model_call_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_vlm_replay_worker",
            "label": "PixelRAG VLM replay worker",
            "status": pixelrag_vlm_replay_worker.get("status") or "warning",
            "summary": (
                pixelrag_vlm_replay_worker.get("summary")
                or "PixelRAG VLM replay worker has no latest readback."
            ),
            "next_machine_action": pixelrag_vlm_replay_worker_details.get("next_machine_action")
            or "run_pixelrag_vlm_replay_worker_dry_run",
            "details": {
                "policy": pixelrag_vlm_replay_worker_details.get("policy"),
                "receipt_count": int(pixelrag_vlm_replay_worker_details.get("receipt_count") or 0),
                "ready_count": int(pixelrag_vlm_replay_worker_details.get("ready_count") or 0),
                "dry_run_count": int(pixelrag_vlm_replay_worker_details.get("dry_run_count") or 0),
                "executed_count": int(pixelrag_vlm_replay_worker_details.get("executed_count") or 0),
                "executed_ok_count": int(pixelrag_vlm_replay_worker_details.get("executed_ok_count") or 0),
                "executed_warning_count": int(
                    pixelrag_vlm_replay_worker_details.get("executed_warning_count") or 0
                ),
                "model_error_count": int(pixelrag_vlm_replay_worker_details.get("model_error_count") or 0),
                "model_route_not_ready_count": int(
                    pixelrag_vlm_replay_worker_details.get("model_route_not_ready_count") or 0
                ),
                "parse_error_count": int(pixelrag_vlm_replay_worker_details.get("parse_error_count") or 0),
                "receipt_written_count": int(
                    pixelrag_vlm_replay_worker_details.get("receipt_written_count") or 0
                ),
                "model_call_performed": bool(
                    pixelrag_vlm_replay_worker_details.get("model_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_vlm_replay_worker_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_platform_probe",
            "label": "PixelRAG platform probe readiness",
            "status": pixelrag_platform_probe.get("status") or "warning",
            "summary": (
                pixelrag_platform_probe.get("summary")
                or "PixelRAG platform probe readiness has no latest readback."
            ),
            "next_machine_action": pixelrag_platform_probe_details.get("next_machine_action")
            or "run_pixelrag_platform_probe_readback",
            "details": {
                "policy": pixelrag_platform_probe_details.get("policy"),
                "probe_candidate_count": int(
                    pixelrag_platform_probe_details.get("probe_candidate_count") or 0
                ),
                "ready_for_probe_count": int(
                    pixelrag_platform_probe_details.get("ready_for_probe_count") or 0
                ),
                "shopee_public_context_probe_count": int(
                    pixelrag_platform_probe_details.get("shopee_public_context_probe_count") or 0
                ),
                "language_or_region_interstitial_count": int(
                    pixelrag_platform_probe_details.get("language_or_region_interstitial_count") or 0
                ),
                "traffic_verification_count": int(
                    pixelrag_platform_probe_details.get("traffic_verification_count") or 0
                ),
                "access_denied_count": int(
                    pixelrag_platform_probe_details.get("access_denied_count") or 0
                ),
                "structured_source_fallback_count": int(
                    pixelrag_platform_probe_details.get("structured_source_fallback_count") or 0
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        {
            "key": "pixelrag_platform_probe_worker",
            "label": "PixelRAG platform probe worker",
            "status": pixelrag_platform_probe_worker.get("status") or "warning",
            "summary": (
                pixelrag_platform_probe_worker.get("summary")
                or "PixelRAG platform probe worker has no latest readback."
            ),
            "next_machine_action": pixelrag_platform_probe_worker_details.get("next_machine_action")
            or "run_pixelrag_platform_probe_worker_dry_run",
            "details": {
                "policy": pixelrag_platform_probe_worker_details.get("policy"),
                "probe_candidate_count": int(
                    pixelrag_platform_probe_worker_details.get("probe_candidate_count") or 0
                ),
                "ready_count": int(
                    pixelrag_platform_probe_worker_details.get("ready_count") or 0
                ),
                "dry_run_count": int(
                    pixelrag_platform_probe_worker_details.get("dry_run_count") or 0
                ),
                "capture_ready_count": int(
                    pixelrag_platform_probe_worker_details.get("capture_ready_count") or 0
                ),
                "capture_execute_count": int(
                    pixelrag_platform_probe_worker_details.get("capture_execute_count") or 0
                ),
                "capture_ok_count": int(
                    pixelrag_platform_probe_worker_details.get("capture_ok_count") or 0
                ),
                "capture_error_count": int(
                    pixelrag_platform_probe_worker_details.get("capture_error_count") or 0
                ),
                "structured_fallback_count": int(
                    pixelrag_platform_probe_worker_details.get("structured_fallback_count") or 0
                ),
                "receipt_written_count": int(
                    pixelrag_platform_probe_worker_details.get("receipt_written_count") or 0
                ),
                "network_call_performed": bool(
                    pixelrag_platform_probe_worker_details.get("network_call_performed")
                ),
                "artifact_write_performed": bool(
                    pixelrag_platform_probe_worker_details.get("artifact_write_performed")
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        },
        freshness_family,
        {
            "key": "daily_summary_delivery",
            "label": "Daily summary delivery readiness",
            "status": "ok" if history_count else "warning",
            "summary": (
                f"{len(daily_rows)} daily summary buckets available."
                if history_count
                else "No history is available for a daily summary yet."
            ),
            "next_machine_action": (
                "send_daily_summary_from_history"
                if history_count
                else "collect_smoke_before_daily_summary"
            ),
            "details": {
                "history_record_count": history_count,
                "daily_bucket_count": len(daily_rows),
                "send_endpoint": "/api/ai-automation/smoke/daily-summary/send",
                "writes_database": False,
            },
        },
    ]
    worst = max(families, key=lambda item: STATUS_RANK.get(item["status"], 2))["status"]
    primary_human_gate_count = sum(
        int((item.get("details") or {}).get("primary_human_gate_count") or 0)
        for item in families
    )
    writes_database_count = sum(
        int((item.get("details") or {}).get("writes_database_count") or 0)
        for item in families
    )
    summary = {
        "ok": sum(1 for item in families if item["status"] == "ok"),
        "warning": sum(1 for item in families if item["status"] == "warning"),
        "critical": sum(1 for item in families if item["status"] == "critical"),
        "total": len(families),
        "history_record_count": history_count,
        "primary_human_gate_count": primary_human_gate_count,
        "writes_database_count": writes_database_count,
    }
    problem_families = [
        item for item in families if item.get("status") in {"warning", "critical"}
    ]
    return {
        "policy": SCHEDULED_AUTOMATION_HEALTH_SUMMARY_POLICY,
        "status": worst,
        "version": SYSTEM_VERSION,
        "generated_at": datetime.now().isoformat(timespec="seconds"),
        "summary": summary,
        "families": families,
        "history": {
            "counts": history.get("counts") or {},
            "daily": daily_rows,
            "latest": latest_history,
        },
        "scheduled_outputs": {
            "health_summary_endpoint": "/api/ai-automation/scheduled-health-summary",
            "smoke_endpoint": "/api/ai-automation/smoke",
            "security_governance_endpoint": "/api/ai-automation/security-governance-review",
            "daily_summary_send_endpoint": "/api/ai-automation/smoke/daily-summary/send",
            "telegram_send_in_preview": False,
            "writes_database": False,
        },
        "automation_policy": {
            "primary_flow": "ai_controlled",
            "manual_review_mode": "exception_only",
            "primary_human_gate_count": 0,
            "machine_verifiable_evidence": True,
        },
        "next_machine_actions": [
            item.get("next_machine_action")
            for item in (problem_families or families[:1])
            if item.get("next_machine_action")
        ],
        "safety": {
            "read_only_summary": True,
            "include_current_smoke": bool(include_current_smoke or current_smoke),
            "sends_telegram": False,
            "writes_database": False,
            "writes_database_count": 0,
            "requires_production_version_truth": True,
        },
    }


def _daily_summary(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    by_day: Dict[str, Dict[str, int]] = {}
    for record in records:
        day = str(record.get("generated_at") or "unknown")[:10]
        bucket = by_day.setdefault(day, {"ok": 0, "warning": 0, "critical": 0, "total": 0})
        status = record.get("status", "critical")
        if status in bucket:
            bucket[status] += 1
        bucket["total"] += 1
    return [
        {"date": day, **counts}
        for day, counts in sorted(by_day.items())[-14:]
    ]


def export_smoke_history_jsonl() -> Dict[str, Any]:
    try:
        lines = _read_history_lines()
    except FileNotFoundError:
        lines = []
    return {
        "content": "".join(lines),
        "count": sum(1 for line in lines if line.strip()),
        "path": _HISTORY_PATH,
    }


def clear_smoke_history() -> Dict[str, Any]:
    try:
        cleared = _count_jsonl_lines(_HISTORY_PATH)
        with _HISTORY_LOCK:
            try:
                os.remove(_HISTORY_PATH)
            except FileNotFoundError:
                cleared = 0
        return {"cleared": cleared, "path": _HISTORY_PATH}
    except Exception as exc:
        return {"cleared": 0, "path": _HISTORY_PATH, "error": str(exc)[:300]}


def build_smoke_daily_summary_message(history_limit: int = 200) -> str:
    records = _load_history(limit=history_limit)
    summary = _history_summary(records)
    daily_rows = summary.get("daily", [])
    latest = summary.get("latest") or {}
    counts = summary.get("counts") or {"ok": 0, "warning": 0, "critical": 0}

    lines = [
        "🤖 <b>AI 自動化 Smoke 每日摘要</b>",
        "━━━━━━━━━━━━━━━━━━━━",
        f"版本：<code>{escape(SYSTEM_VERSION)}</code>",
        f"最近狀態：<b>{escape(str(latest.get('status', 'no_data')).upper())}</b>",
        f"最近時間：{escape(str(latest.get('generated_at', '尚無紀錄')))}",
        "",
        "📊 <b>近期統計</b>",
        f"✅ OK：{counts.get('ok', 0)}",
        f"⚠️ Warning：{counts.get('warning', 0)}",
        f"🚨 Critical：{counts.get('critical', 0)}",
    ]

    if daily_rows:
        lines += ["", "🗓️ <b>最近每日摘要</b>"]
        for row in daily_rows[-5:]:
            lines.append(
                f"{escape(str(row.get('date')))}｜"
                f"OK {row.get('ok', 0)} / W {row.get('warning', 0)} / C {row.get('critical', 0)}"
            )
    else:
        lines += ["", "🗓️ 尚無 smoke history；請先開啟 /ai_automation_smoke 執行快檢。"]

    problem_checks = [
        item for item in latest.get("checks", [])
        if item.get("status") in {"warning", "critical"}
    ]
    if problem_checks:
        lines += ["", "🚩 <b>最近異常檢查</b>"]
        for item in problem_checks[:5]:
            lines.append(
                f"{escape(str(item.get('status', '')).upper())}｜"
                f"{escape(str(item.get('name', 'unknown')))}："
                f"{escape(str(item.get('summary', '')))}"
            )

    lines += [
        "━━━━━━━━━━━━━━━━━━━━",
        "入口：/ai_automation_smoke",
    ]
    return "\n".join(lines)


def send_smoke_daily_summary(chat_ids: List[Any] | None = None) -> Dict[str, Any]:
    from services.telegram_templates import send_telegram_with_result

    message = build_smoke_daily_summary_message()
    result = send_telegram_with_result(message, chat_ids=chat_ids)
    return {
        "status": "sent" if result.get("ok") else "failed",
        "telegram": result,
        "message_preview": message[:500],
    }


def _event_router_check() -> Dict[str, Any]:
    try:
        from services import event_router
        from services.ai_automation_metrics import snapshot

        queue_count = _count_jsonl_lines(event_router._QUEUE_PATH)
        metrics = snapshot()
        dispatch_total = sum(
            value for (metric, _labels), value in metrics.get("counters", {}).items()
            if metric == "event_router_dispatch_total"
        )
        status = "warning" if queue_count else "ok"
        summary = "EventRouter 可用，通知 queue 乾淨" if status == "ok" else "EventRouter 可用，但有待回放通知"
        return _check(
            "EventRouter 通知鏈",
            status,
            summary,
            {
                "dispatch_sync": callable(getattr(event_router, "dispatch_sync", None)),
                "notify_failure": callable(getattr(event_router, "notify_failure", None)),
                "queued_deliveries": queue_count,
                "dispatch_metric_total": dispatch_total,
            },
        )
    except Exception as exc:
        return _check("EventRouter 通知鏈", "critical", f"EventRouter smoke 失敗：{exc}")


def _row_mapping(row: Any) -> Dict[str, Any]:
    if row is None:
        return {}
    if isinstance(row, dict):
        return row
    mapping = getattr(row, "_mapping", None)
    if mapping is not None:
        return dict(mapping)
    return {}


def _create_pchome_drift_monitor_engine(database_path: str):
    from sqlalchemy import create_engine

    engine_kwargs: Dict[str, Any] = {}
    if str(database_path).startswith(("postgresql://", "postgresql+psycopg2://", "postgres://")):
        engine_kwargs["connect_args"] = {
            "options": f"-c statement_timeout={_PCHOME_DRIFT_MONITOR_DB_STATEMENT_TIMEOUT_MS}"
        }
    return create_engine(database_path, **engine_kwargs)


def _gemini_egress_check(window_hours: int = 24) -> Dict[str, Any]:
    """Read-only runtime sentinel for unexpected Gemini spend."""
    session = None
    try:
        from services.gemini_guard import gemini_disabled_message, is_gemini_hard_disabled

        session = get_session()
        since_at = datetime.now(timezone.utc) - timedelta(hours=int(window_hours))
        summary_row = session.execute(
            text("""
                SELECT
                    COUNT(*) AS calls,
                    COALESCE(SUM(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0)), 0) AS tokens,
                    COALESCE(SUM(COALESCE(cost_usd, 0)), 0) AS cost_usd,
                    MAX(called_at) AS last_called
                FROM ai_calls
                WHERE lower(provider) = 'gemini'
                  AND called_at >= :since_at
            """),
            {"since_at": since_at},
        ).fetchone()
        summary = _row_mapping(summary_row)
        calls = int(summary.get("calls") or 0)
        tokens = int(summary.get("tokens") or 0)
        cost_usd = float(summary.get("cost_usd") or 0.0)
        hard_disabled = is_gemini_hard_disabled()

        top_rows = []
        if calls:
            top_rows = [
                _row_mapping(row) for row in session.execute(
                    text("""
                        SELECT
                            caller,
                            model,
                            COUNT(*) AS calls,
                            COALESCE(SUM(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0)), 0) AS tokens,
                            COALESCE(SUM(COALESCE(cost_usd, 0)), 0) AS cost_usd,
                            MAX(called_at) AS last_called
                        FROM ai_calls
                        WHERE lower(provider) = 'gemini'
                          AND called_at >= :since_at
                        GROUP BY caller, model
                        ORDER BY calls DESC, last_called DESC
                        LIMIT 5
                    """),
                    {"since_at": since_at},
                ).fetchall()
            ]

        details = {
            "window_hours": int(window_hours),
            "since_at": since_at.isoformat(timespec="seconds"),
            "hard_disabled": hard_disabled,
            "calls": calls,
            "tokens": tokens,
            "cost_usd": round(cost_usd, 6),
            "last_called": str(summary.get("last_called") or ""),
            "top_callers": top_rows,
            "guard_reason": gemini_disabled_message("ai_smoke_gemini_egress"),
        }

        if calls == 0:
            return _check(
                "Gemini 出站費用 sentinel",
                "ok",
                f"最近 {window_hours}h Gemini 出站 0 次，費用 $0",
                details,
            )
        if hard_disabled:
            return _check(
                "Gemini 出站費用 sentinel",
                "critical",
                f"Hard-disabled 狀態仍偵測到 Gemini {calls} 次 / ${cost_usd:.6f}",
                details,
            )
        return _check(
            "Gemini 出站費用 sentinel",
            "warning",
            f"Gemini emergency fallback 近 {window_hours}h 使用 {calls} 次 / ${cost_usd:.6f}",
            details,
        )
    except Exception as exc:
        return _check(
            "Gemini 出站費用 sentinel",
            "warning",
            f"Gemini 出站紀錄無法讀取：{exc}",
        )
    finally:
        if session is not None:
            session.close()


def _autoheal_check() -> Dict[str, Any]:
    try:
        import services.auto_heal_service as autoheal

        protected = set(getattr(autoheal, "_PROTECTED_CONTAINERS", set()))
        required = {"momo-db", "momo-postgres"}
        missing = sorted(required - protected)
        allowed_actions = sorted(getattr(autoheal, "_ALLOWED_ACTION_TYPES", set()))
        status = "critical" if missing else "ok"
        summary = "AutoHeal 保護資料庫容器，安全邊界存在" if status == "ok" else "AutoHeal protected resource 缺漏"
        return _check(
            "AutoHeal 安全邊界",
            status,
            summary,
            {
                "protected_containers": sorted(protected),
                "missing_required_protection": missing,
                "allowed_actions": allowed_actions,
            },
        )
    except Exception as exc:
        return _check("AutoHeal 安全邊界", "critical", f"AutoHeal smoke 失敗：{exc}")


def _nemotron_check() -> Dict[str, Any]:
    try:
        import services.nemoton_dispatcher_service as nemotron

        dispatcher_cls = (
            getattr(nemotron, "NemotronDispatcherService", None)
            or getattr(nemotron, "NemotronDispatcher", None)
        )
        fallback_ready = bool(dispatcher_cls and hasattr(dispatcher_cls, "_hermes_rule_fallback"))
        api_key_configured = bool(getattr(nemotron, "NIM_API_KEY", ""))
        call_count = getattr(nemotron, "_nim_call_count", {}).get("count", 0)
        daily_limit = getattr(nemotron, "NIM_DAILY_LIMIT", 80)
        if not fallback_ready:
            status = "critical"
            summary = "NemoTron Hermes fallback 缺失"
        elif not api_key_configured:
            status = "warning"
            summary = "NemoTron API key 未設定，目前會走 Hermes fallback"
        elif call_count >= daily_limit:
            status = "warning"
            summary = "NemoTron 配額已達上限，會走 Hermes fallback"
        else:
            status = "ok"
            summary = "NemoTron 與 Hermes fallback 機制可用"
        return _check(
            "NemoTron fallback",
            status,
            summary,
            {
                "fallback_ready": fallback_ready,
                "dispatcher_class": getattr(dispatcher_cls, "__name__", None),
                "api_key_configured": api_key_configured,
                "call_count": call_count,
                "daily_limit": daily_limit,
            },
        )
    except Exception as exc:
        return _check("NemoTron fallback", "critical", f"NemoTron smoke 失敗：{exc}")


def _embedding_queue_check() -> Dict[str, Any]:
    session = None
    try:
        session = get_session()
        rows = session.execute(
            text("SELECT status, COUNT(*) AS count FROM embedding_retry_queue GROUP BY status")
        ).fetchall()
        counts = {str(row._mapping["status"]): int(row._mapping["count"]) for row in rows}
        pending = counts.get("pending", 0)
        processing = counts.get("processing", 0)
        if pending > 1000 or processing > 200:
            status = "warning"
            summary = "OpenClaw embedding queue backlog 偏高"
        else:
            status = "ok"
            summary = "OpenClaw embedding queue 可讀取且 backlog 正常"
        return _check(
            "OpenClaw embedding queue",
            status,
            summary,
            {"counts": counts, "pending": pending, "processing": processing},
        )
    except Exception as exc:
        return _check(
            "OpenClaw embedding queue",
            "warning",
            f"Embedding queue 無法讀取，可能是 DB 離線或 migration 未套用：{exc}",
        )
    finally:
        if session is not None:
            session.close()


def _elephant_hitl_check() -> Dict[str, Any]:
    try:
        from services.elephant_alpha_autonomous_engine import ElephantAlphaAutonomousEngine

        has_hitl = hasattr(ElephantAlphaAutonomousEngine, "_escalate_to_human")
        has_timeout_guard = hasattr(ElephantAlphaAutonomousEngine, "_run_with_timeout")
        api_key_configured = bool(os.getenv("OPENROUTER_API_KEY") or os.getenv("NVIDIA_API_KEY"))
        if not has_hitl or not has_timeout_guard:
            status = "critical"
            summary = "ElephantAlpha AI 例外決策或 timeout guard 缺失"
        elif not api_key_configured:
            status = "warning"
            summary = "ElephantAlpha AI 例外決策程式可用，但 API key 未設定"
        else:
            status = "ok"
            summary = "ElephantAlpha AI 例外決策與 timeout guard 可用"
        return _check(
            "ElephantAlpha AI 例外決策",
            status,
            summary,
            {
                "hitl_method": has_hitl,
                "timeout_guard": has_timeout_guard,
                "api_key_configured": api_key_configured,
            },
        )
    except Exception as exc:
        return _check("ElephantAlpha AI 例外決策", "critical", f"ElephantAlpha smoke 失敗：{exc}")


def _pchome_controlled_apply_drift_monitor_check() -> Dict[str, Any]:
    """Read-only monitor that runs the PChome controlled-apply drift verifier."""
    engine = None
    try:
        from config import DATABASE_PATH
        from services import pchome_mapping_backlog_service as backlog

        engine = _create_pchome_drift_monitor_engine(DATABASE_PATH)
        receipt_replay = (
            backlog.build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
                materialize_artifacts=False,
                engine=engine,
            )
        )
        drift_verifier = (
            backlog.build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
                engine=engine,
                source_receipt_replay=receipt_replay,
                materialize_artifacts=False,
            )
        )
        summary = drift_verifier.get("summary") or {}
        drift_count = int(summary.get("drift_count") or 0)
        selector_count = int(summary.get("target_selector_count") or 0)
        pass_count = int(summary.get("post_apply_readback_pass_count") or 0)
        verified_count = int(summary.get("drift_verified_count") or 0)
        artifact_count = int(summary.get("drift_verifier_artifact_materialized_count") or 0)
        artifact_hash_match_count = int(summary.get("drift_verifier_artifact_hash_match_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        result = str(drift_verifier.get("result") or "UNKNOWN")
        receipt_result = str(receipt_replay.get("result") or "UNKNOWN")

        if writes_database_count:
            status = "critical"
            summary_text = "PChome drift monitor 偵測到 verifier 有寫 DB 風險"
        elif drift_count:
            status = "critical"
            summary_text = f"PChome controlled apply 偵測到 {drift_count} 筆 drift"
        elif verified_count and selector_count and pass_count == selector_count:
            status = "ok"
            summary_text = f"PChome controlled apply drift 已驗證 {pass_count}/{selector_count}，目前 0 drift"
        else:
            status = "warning"
            summary_text = "PChome controlled apply drift verifier 尚未達例行監控完成條件"

        return _check(
            "PChome 受控落地 drift monitor",
            status,
            summary_text,
            {
                "result": result,
                "source_receipt_replay_result": receipt_result,
                "selector_count": selector_count,
                "readback_pass_count": pass_count,
                "drift_count": drift_count,
                "drift_verified_count": verified_count,
                "artifact_count": artifact_count,
                "artifact_hash_match_count": artifact_hash_match_count,
                "writes_database_count": writes_database_count,
                "writes_database": False,
                "materialize_artifacts": False,
                "requires_production_version_truth": True,
            },
        )
    except Exception as exc:
        return _check(
            "PChome 受控落地 drift monitor",
            "warning",
            f"PChome drift verifier 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "materialize_artifacts": False,
                "requires_production_version_truth": True,
            },
        )
    finally:
        if engine is not None:
            engine.dispose()


def _pchome_auto_policy_authorization_guard_check() -> Dict[str, Any]:
    """Read-only monitor for the PChome auto-policy DB apply guard lane."""
    engine = None
    try:
        from config import DATABASE_PATH
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )
        from services.pchome_revenue_growth_service import build_pchome_growth_opportunities

        engine = _create_pchome_drift_monitor_engine(DATABASE_PATH)
        payload = build_pchome_growth_opportunities(
            engine,
            limit=max(5, min(_PCHOME_AUTO_POLICY_GUARD_LIMIT, 50)),
        )
        payload["cache_state"] = "smoke_read_only"
        guard = backlog.build_pchome_auto_policy_db_apply_authorization_lane_guard(
            payload,
            batch_size=max(1, min(_PCHOME_AUTO_POLICY_GUARD_BATCH_SIZE, 50)),
            execute_fetch=False,
            timeout_seconds=max(1, min(_PCHOME_AUTO_POLICY_GUARD_TIMEOUT_SECONDS, 30)),
        )
        summary = guard.get("summary") or {}
        lane = guard.get("future_authorization_lane_guard") or {}
        contract = guard.get("lane_transfer_contract") or {}
        safety = guard.get("safety") or {}
        result = str(guard.get("result") or "UNKNOWN")

        guard_ready_count = int(summary.get("authorization_lane_guard_ready_count") or 0)
        check_count = int(summary.get("lane_guard_check_count") or 0)
        pass_count = int(summary.get("lane_guard_pass_count") or 0)
        waiting_count = int(summary.get("lane_guard_waiting_count") or 0)
        request_ready_count = int(summary.get("authorization_request_closeout_ready_count") or 0)
        exact_field_count = int(summary.get("exact_request_payload_field_count") or 0)
        manifest_step_count = int(summary.get("machine_request_manifest_step_count") or 0)
        entry_requirement_count = int(summary.get("lane_entry_requirement_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = reads_secret_count + executes_sql_count + writes_database_count
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                contract.get("writes_database") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                lane.get("ready_for_database_apply_now") is not False,
                lane.get("issues_database_apply_authorization") is not False,
            ]
        )
        guard_contract_present = (
            check_count >= 12
            and pass_count >= max(check_count - 1, 1)
            and waiting_count <= 1
            and exact_field_count == 10
            and manifest_step_count == 6
            and entry_requirement_count == 6
            and contract.get("machine_verifiable") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = "PChome auto-policy guard 偵測到 secret、SQL、DB write 或人工主 gate 風險"
            next_machine_action = "halt_pchome_auto_policy_guard_and_inspect_risk"
        elif guard_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy guard 已自動讀回 no-write/no-secret package，"
                f"{pass_count}/{check_count} guard checks 通過，人工主 gate=0"
            )
            next_machine_action = (
                "collect_machine_fetch_evidence_for_authorization_guard"
                if guard_ready_count == 0 or request_ready_count == 0
                else "continue_pchome_auto_policy_guard_monitoring"
            )
        else:
            status = "warning"
            summary_text = "PChome auto-policy guard 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_authorization_guard"

        return _check(
            "PChome auto-policy authorization guard",
            status,
            summary_text,
            {
                "policy": guard.get("policy"),
                "result": result,
                "source_policy": guard.get("source_policy"),
                "guard_ready_count": guard_ready_count,
                "authorization_request_closeout_ready_count": request_ready_count,
                "lane_guard_check_count": check_count,
                "lane_guard_pass_count": pass_count,
                "lane_guard_waiting_count": waiting_count,
                "exact_request_payload_field_count": exact_field_count,
                "machine_request_manifest_step_count": manifest_step_count,
                "lane_entry_requirement_count": entry_requirement_count,
                "reads_secret_count": reads_secret_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "machine_verifiable": bool(contract.get("machine_verifiable")),
                "ready_for_database_apply_now": bool(lane.get("ready_for_database_apply_now")),
                "issues_database_apply_authorization": bool(
                    lane.get("issues_database_apply_authorization")
                ),
                "requires_fresh_production_truth": bool(
                    lane.get("requires_fresh_production_truth_in_same_run")
                ),
                "execute_fetch": False,
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy authorization guard",
            "warning",
            f"PChome auto-policy guard 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
                "next_machine_action": "refresh_pchome_auto_policy_authorization_guard",
            },
        )
    finally:
        if engine is not None:
            engine.dispose()


class _PChomeMachineFetchEvidenceResponse:
    status_code = 200
    encoding = "utf-8"
    content = b"""
    <html><head>
      <script type="application/ld+json">
        {
          "@context": "https://schema.org",
          "@type": "Product",
          "name": "MOMO Pro machine evidence fixture",
          "image": "https://cdn.example.test/pchome-auto-policy-machine-evidence.jpg",
          "offers": {
            "@type": "Offer",
            "availability": "https://schema.org/InStock"
          }
        }
      </script>
    </head></html>
    """


def _pchome_auto_policy_machine_fetch_evidence_get(url, timeout, headers):
    """Deterministic no-network adapter for schema evidence preflight checks."""
    return _PChomeMachineFetchEvidenceResponse()


def _pchome_auto_policy_decision_preflight_contract_payload() -> Dict[str, Any]:
    return {
        "success": True,
        "system_name": "MOMO Pro",
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "cache_state": "smoke_read_only_machine_evidence_contract_fixture",
        "stats": {
            "candidate_count": 4,
            "mapped_count": 1,
            "mapping_rate": 25.0,
            "needs_mapping_count": 3,
            "review_candidate_count": 1,
            "overall_latest_sales_date": "2026-06-24",
            "overall_sales_7d": 2020234.0,
            "action_counts": {
                "先補商品對應": 2,
                "確認候選": 1,
                "放大價格優勢": 1,
            },
            "action_code_counts": {
                "map_external_product": 2,
                "review_external_candidate": 1,
                "amplify_price_advantage": 1,
            },
        },
        "opportunities": [
            {
                "pchome_product_id": "PCH-1",
                "product_name": "Mapped product",
                "sales_7d": 0,
                "external_price": {"momo_sku": "M-1", "price_basis": "unit_price", "gap_pct": 12.5},
                "recommended_action": {"code": "amplify_price_advantage", "label": "放大價格優勢"},
                "priority_score": 75.0,
            },
            {
                "pchome_product_id": "PCH-2",
                "product_name": "Direct mapping product 40ml x2",
                "sales_7d": 9800,
                "pchome_price": 1200,
                "external_price": None,
                "recommended_action": {"code": "map_external_product", "label": "先補商品對應"},
                "priority_score": 88.0,
                "reason_lines": ["需要補商品對應"],
            },
            {
                "pchome_product_id": "PCH-3",
                "product_name": "Review candidate product",
                "sales_7d": 1200,
                "external_price": None,
                "review_candidate": {
                    "id": 725,
                    "momo_sku": "5868343",
                    "momo_name": "MOMO candidate",
                    "quality_score": 94.8,
                },
                "recommended_action": {"code": "review_external_candidate", "label": "確認候選"},
                "priority_score": 64.0,
            },
            {
                "pchome_product_id": "PCH-4",
                "product_name": "Another direct mapping product",
                "sales_7d": 3100,
                "external_price": None,
                "recommended_action": {"code": "map_external_product", "label": "先補商品對應"},
                "priority_score": 52.0,
            },
        ],
    }


def _pchome_auto_policy_decision_preflight_check() -> Dict[str, Any]:
    """Read-only monitor for machine evidence and decision preflight readiness."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        preflight = backlog.build_pchome_auto_policy_db_apply_authorization_decision_preflight(
            payload,
            batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
            execute_fetch=True,
            timeout_seconds=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30)),
            http_get=_pchome_auto_policy_machine_fetch_evidence_get,
        )
        summary = preflight.get("summary") or {}
        decision = preflight.get("future_authorization_decision_preflight") or {}
        envelope = preflight.get("decision_preflight_envelope") or {}
        safety = preflight.get("safety") or {}
        result = str(preflight.get("result") or "UNKNOWN")

        decision_ready_count = int(
            summary.get("authorization_decision_preflight_ready_count") or 0
        )
        lane_ready_count = int(summary.get("authorization_lane_guard_ready_count") or 0)
        check_count = int(summary.get("decision_preflight_check_count") or 0)
        pass_count = int(summary.get("decision_preflight_pass_count") or 0)
        waiting_count = int(summary.get("decision_preflight_waiting_count") or 0)
        input_requirement_count = int(summary.get("decision_input_requirement_count") or 0)
        rejection_reason_count = int(summary.get("decision_rejection_reason_count") or 0)
        entry_requirement_count = int(summary.get("lane_entry_requirement_count") or 0)
        exact_field_count = int(summary.get("exact_request_payload_field_count") or 0)
        manifest_step_count = int(summary.get("machine_request_manifest_step_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = reads_secret_count + executes_sql_count + writes_database_count
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                envelope.get("issues_database_apply_authorization") is not False,
                envelope.get("ready_for_database_apply_now") is not False,
                decision.get("ready_for_database_apply_now") is not False,
                decision.get("issues_database_apply_authorization") is not False,
            ]
        )
        preflight_contract_present = (
            decision_ready_count == 1
            and lane_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and input_requirement_count == 8
            and rejection_reason_count == 10
            and entry_requirement_count == 6
            and exact_field_count == 10
            and manifest_step_count == 6
            and decision.get("ready_for_future_authorization_decision") is True
            and envelope.get("allows_authorization_decision_in_future_lane") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = "PChome auto-policy decision preflight 偵測到 secret、SQL、DB write 或人工主 gate 風險"
            next_machine_action = "halt_pchome_auto_policy_decision_preflight_and_inspect_risk"
        elif preflight_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy decision preflight 已用本機 machine evidence 自動通過 "
                f"{pass_count}/{check_count} checks，外部網路=0、人工主 gate=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_decision_closeout_lane"
        else:
            status = "warning"
            summary_text = "PChome auto-policy decision preflight 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_machine_fetch_evidence_preflight"

        return _check(
            "PChome auto-policy decision preflight",
            status,
            summary_text,
            {
                "policy": preflight.get("policy"),
                "result": result,
                "source_policy": preflight.get("source_policy"),
                "decision_preflight_ready_count": decision_ready_count,
                "authorization_lane_guard_ready_count": lane_ready_count,
                "decision_preflight_check_count": check_count,
                "decision_preflight_pass_count": pass_count,
                "decision_preflight_waiting_count": waiting_count,
                "decision_input_requirement_count": input_requirement_count,
                "decision_rejection_reason_count": rejection_reason_count,
                "lane_entry_requirement_count": entry_requirement_count,
                "exact_request_payload_field_count": exact_field_count,
                "machine_request_manifest_step_count": manifest_step_count,
                "reads_secret_count": reads_secret_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "machine_fetch_evidence_ready_count": 1 if preflight_contract_present else 0,
                "machine_fetch_evidence_source": "local_schema_fixture",
                "payload_source": "local_contract_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(decision.get("ready_for_database_apply_now")),
                "issues_database_apply_authorization": bool(
                    decision.get("issues_database_apply_authorization")
                ),
                "requires_fresh_production_truth": bool(
                    decision.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy decision preflight",
            "warning",
            f"PChome auto-policy decision preflight 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_machine_fetch_evidence_preflight",
            },
        )


def _pchome_auto_policy_decision_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the future authorization decision closeout package."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = backlog.build_pchome_auto_policy_db_apply_authorization_decision_closeout(
            payload,
            batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
            execute_fetch=True,
            timeout_seconds=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30)),
            http_get=_pchome_auto_policy_machine_fetch_evidence_get,
        )
        summary = closeout.get("summary") or {}
        decision = closeout.get("future_authorization_decision_closeout") or {}
        package = closeout.get("future_authorization_decision_package") or {}
        contract = closeout.get("decision_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        result = str(closeout.get("result") or "UNKNOWN")

        closeout_ready_count = int(summary.get("authorization_decision_closeout_ready_count") or 0)
        preflight_ready_count = int(
            summary.get("authorization_decision_preflight_ready_count") or 0
        )
        check_count = int(summary.get("decision_closeout_check_count") or 0)
        pass_count = int(summary.get("decision_closeout_pass_count") or 0)
        waiting_count = int(summary.get("decision_closeout_waiting_count") or 0)
        input_requirement_count = int(summary.get("decision_input_requirement_count") or 0)
        rejection_reason_count = int(summary.get("decision_rejection_reason_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = reads_secret_count + executes_sql_count + writes_database_count
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("writes_database") is not False,
                package.get("ready_for_database_apply_now") is not False,
                package.get("issues_database_apply_authorization") is not False,
                decision.get("ready_for_database_apply_now") is not False,
                decision.get("issues_database_apply_authorization") is not False,
            ]
        )
        closeout_contract_present = (
            closeout_ready_count == 1
            and preflight_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and input_requirement_count == 8
            and rejection_reason_count == 10
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and decision.get("ready_for_future_authorization_decision_closeout") is True
            and package.get("ready_for_future_authorization_decision_package") is True
            and package.get("requires_post_apply_verifier") is True
            and package.get("requires_fresh_production_truth_in_same_run") is True
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_authorization_decision_lane") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = "PChome auto-policy decision closeout 偵測到 secret、SQL、DB write 或人工主 gate 風險"
            next_machine_action = "halt_pchome_auto_policy_decision_closeout_and_inspect_risk"
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy decision closeout 已自動完成 "
                f"{pass_count}/{check_count} checks，post-apply verifier 已綁定，DB apply authorization=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_authorization_issuer_gate"
        else:
            status = "warning"
            summary_text = "PChome auto-policy decision closeout 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_decision_closeout"

        return _check(
            "PChome auto-policy decision closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "decision_closeout_ready_count": closeout_ready_count,
                "decision_preflight_ready_count": preflight_ready_count,
                "decision_closeout_check_count": check_count,
                "decision_closeout_pass_count": pass_count,
                "decision_closeout_waiting_count": waiting_count,
                "decision_input_requirement_count": input_requirement_count,
                "decision_rejection_reason_count": rejection_reason_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "reads_secret_count": reads_secret_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(package.get("ready_for_database_apply_now")),
                "issues_database_apply_authorization": bool(
                    package.get("issues_database_apply_authorization")
                ),
                "permits_future_authorization_decision_lane": bool(
                    contract.get("permits_future_authorization_decision_lane")
                ),
                "requires_post_apply_verifier": bool(package.get("requires_post_apply_verifier")),
                "requires_fresh_production_truth": bool(
                    package.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy decision closeout",
            "warning",
            f"PChome auto-policy decision closeout 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_decision_closeout",
            },
        )


def _pchome_auto_policy_authorization_issuer_gate_check() -> Dict[str, Any]:
    """Read-only monitor for the no-secret authorization issuer gate envelope."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        gate = backlog.build_pchome_auto_policy_db_apply_authorization_issuer_gate(
            payload,
            batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
            execute_fetch=True,
            timeout_seconds=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30)),
            http_get=_pchome_auto_policy_machine_fetch_evidence_get,
        )
        summary = gate.get("summary") or {}
        issuer = gate.get("future_authorization_issuer_gate") or {}
        envelope = gate.get("final_nonsecret_authorization_envelope") or {}
        contract = gate.get("issuer_gate_contract") or {}
        safety = gate.get("safety") or {}
        result = str(gate.get("result") or "UNKNOWN")

        issuer_ready_count = int(summary.get("authorization_issuer_gate_ready_count") or 0)
        closeout_ready_count = int(
            summary.get("authorization_decision_closeout_ready_count") or 0
        )
        check_count = int(summary.get("issuer_gate_check_count") or 0)
        pass_count = int(summary.get("issuer_gate_pass_count") or 0)
        waiting_count = int(summary.get("issuer_gate_waiting_count") or 0)
        closeout_check_count = int(summary.get("decision_closeout_check_count") or 0)
        required_evidence_count = int(summary.get("required_issuer_evidence_count") or 0)
        nonsecret_claim_count = int(summary.get("nonsecret_authorization_claim_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            reads_secret_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("executes_script") is not False,
                issuer.get("ready_for_database_apply_now") is not False,
                issuer.get("issues_database_apply_authorization") is not False,
                issuer.get("signs_database_apply_authorization") is not False,
                envelope.get("ready_for_database_apply_now") is not False,
                envelope.get("issues_database_apply_authorization") is not False,
                envelope.get("signs_database_apply_authorization") is not False,
                envelope.get("secret_material_included") is not False,
                envelope.get("reads_secret_in_preview") is not False,
                envelope.get("writes_database_in_preview") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
            ]
        )
        issuer_contract_present = (
            issuer_ready_count == 1
            and closeout_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and closeout_check_count == 12
            and required_evidence_count == 9
            and nonsecret_claim_count == 8
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and issuer.get("ready_for_future_authorization_issuer_lane") is True
            and envelope.get("authorization_material_type") == "nonsecret_request_envelope"
            and envelope.get("ready_for_future_authorization_issuer_lane") is True
            and envelope.get("requires_post_apply_verifier") is True
            and envelope.get("requires_fresh_production_truth_in_same_run") is True
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_authorization_issuer_lane") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy authorization issuer gate 偵測到 secret、SQL、DB write、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = "halt_pchome_auto_policy_authorization_issuer_gate_and_inspect_risk"
        elif issuer_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy authorization issuer gate 已自動完成 "
                f"{pass_count}/{check_count} checks，nonsecret envelope 已綁定，DB apply authorization=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signing_decision_preflight_lane"
        else:
            status = "warning"
            summary_text = "PChome auto-policy authorization issuer gate 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_authorization_issuer_gate"

        return _check(
            "PChome auto-policy authorization issuer gate",
            status,
            summary_text,
            {
                "policy": gate.get("policy"),
                "result": result,
                "source_policy": gate.get("source_policy"),
                "issuer_gate_ready_count": issuer_ready_count,
                "decision_closeout_ready_count": closeout_ready_count,
                "issuer_gate_check_count": check_count,
                "issuer_gate_pass_count": pass_count,
                "issuer_gate_waiting_count": waiting_count,
                "decision_closeout_check_count": closeout_check_count,
                "required_issuer_evidence_count": required_evidence_count,
                "nonsecret_authorization_claim_count": nonsecret_claim_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "reads_secret_count": reads_secret_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(
                    issuer.get("ready_for_database_apply_now")
                    or envelope.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    issuer.get("issues_database_apply_authorization")
                    or envelope.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    issuer.get("signs_database_apply_authorization")
                    or envelope.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(envelope.get("secret_material_included")),
                "permits_future_authorization_issuer_lane": bool(
                    contract.get("permits_future_authorization_issuer_lane")
                ),
                "requires_post_apply_verifier": bool(
                    envelope.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    envelope.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy authorization issuer gate",
            "warning",
            f"PChome auto-policy authorization issuer gate 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_authorization_issuer_gate",
            },
        )


def _pchome_auto_policy_signing_decision_preflight_check() -> Dict[str, Any]:
    """Read-only monitor for the no-secret authorization signing decision preflight."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        preflight = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = preflight.get("summary") or {}
        decision = preflight.get("future_authorization_signing_decision_preflight") or {}
        envelope = preflight.get("signing_decision_preflight_envelope") or {}
        safety = preflight.get("safety") or {}
        result = str(preflight.get("result") or "UNKNOWN")

        preflight_ready_count = int(
            summary.get("authorization_signing_decision_preflight_ready_count") or 0
        )
        issuer_ready_count = int(summary.get("authorization_issuer_gate_ready_count") or 0)
        check_count = int(summary.get("signing_decision_preflight_check_count") or 0)
        pass_count = int(summary.get("signing_decision_preflight_pass_count") or 0)
        waiting_count = int(summary.get("signing_decision_preflight_waiting_count") or 0)
        issuer_check_count = int(summary.get("issuer_gate_check_count") or 0)
        required_evidence_count = int(summary.get("required_issuer_evidence_count") or 0)
        nonsecret_claim_count = int(summary.get("nonsecret_authorization_claim_count") or 0)
        input_requirement_count = int(
            summary.get("signing_decision_input_requirement_count") or 0
        )
        rejection_reason_count = int(
            summary.get("signing_decision_rejection_reason_count") or 0
        )
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            reads_secret_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                decision.get("ready_for_database_apply_now") is not False,
                decision.get("issues_database_apply_authorization") is not False,
                decision.get("signs_database_apply_authorization") is not False,
                envelope.get("ready_for_database_apply_now") is not False,
                envelope.get("issues_database_apply_authorization") is not False,
                envelope.get("signs_database_apply_authorization") is not False,
                envelope.get("secret_material_required_in_preview") is not False,
            ]
        )
        preflight_contract_present = (
            preflight_ready_count == 1
            and issuer_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and issuer_check_count == 12
            and required_evidence_count == 9
            and nonsecret_claim_count == 8
            and input_requirement_count == 10
            and rejection_reason_count == 11
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and decision.get("ready_for_future_signing_decision_preflight") is True
            and decision.get("can_enter_authorization_signing_decision_lane") is True
            and envelope.get("machine_verifiable") is True
            and envelope.get("allows_future_authorization_signing_decision_lane") is True
            and envelope.get("rejects_direct_database_apply") is True
            and envelope.get("requires_post_apply_verifier") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signing decision preflight 偵測到 secret、SQL、DB write、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signing_decision_preflight_and_inspect_risk"
            )
        elif preflight_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signing decision preflight 已自動完成 "
                f"{pass_count}/{check_count} checks，signing inputs 已綁定，authorization signing=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_signing_decision_closeout_lane"
            )
        else:
            status = "warning"
            summary_text = "PChome auto-policy signing decision preflight 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_signing_decision_preflight"

        return _check(
            "PChome auto-policy signing decision preflight",
            status,
            summary_text,
            {
                "policy": preflight.get("policy"),
                "result": result,
                "source_policy": preflight.get("source_policy"),
                "signing_decision_preflight_ready_count": preflight_ready_count,
                "authorization_issuer_gate_ready_count": issuer_ready_count,
                "signing_decision_preflight_check_count": check_count,
                "signing_decision_preflight_pass_count": pass_count,
                "signing_decision_preflight_waiting_count": waiting_count,
                "issuer_gate_check_count": issuer_check_count,
                "required_issuer_evidence_count": required_evidence_count,
                "nonsecret_authorization_claim_count": nonsecret_claim_count,
                "signing_decision_input_requirement_count": input_requirement_count,
                "signing_decision_rejection_reason_count": rejection_reason_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "reads_secret_count": reads_secret_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(
                    decision.get("ready_for_database_apply_now")
                    or envelope.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    decision.get("issues_database_apply_authorization")
                    or envelope.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    decision.get("signs_database_apply_authorization")
                    or envelope.get("signs_database_apply_authorization")
                ),
                "secret_material_required_in_preview": bool(
                    envelope.get("secret_material_required_in_preview")
                ),
                "allows_future_authorization_signing_decision_lane": bool(
                    envelope.get("allows_future_authorization_signing_decision_lane")
                ),
                "rejects_direct_database_apply": bool(
                    envelope.get("rejects_direct_database_apply")
                ),
                "requires_post_apply_verifier": bool(
                    envelope.get("requires_post_apply_verifier")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signing decision preflight",
            "warning",
            f"PChome auto-policy signing decision preflight 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_signing_decision_preflight",
            },
        )


def _pchome_auto_policy_signing_decision_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the unsigned signing decision closeout package."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        decision = closeout.get("future_authorization_signing_decision_closeout") or {}
        package = closeout.get("unsigned_signing_decision_package") or {}
        contract = closeout.get("signing_decision_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        result = str(closeout.get("result") or "UNKNOWN")

        closeout_ready_count = int(
            summary.get("authorization_signing_decision_closeout_ready_count") or 0
        )
        preflight_ready_count = int(
            summary.get("authorization_signing_decision_preflight_ready_count") or 0
        )
        check_count = int(summary.get("signing_decision_closeout_check_count") or 0)
        pass_count = int(summary.get("signing_decision_closeout_pass_count") or 0)
        waiting_count = int(summary.get("signing_decision_closeout_waiting_count") or 0)
        preflight_check_count = int(summary.get("signing_decision_preflight_check_count") or 0)
        input_requirement_count = int(
            summary.get("signing_decision_input_requirement_count") or 0
        )
        rejection_reason_count = int(
            summary.get("signing_decision_rejection_reason_count") or 0
        )
        required_evidence_count = int(summary.get("required_issuer_evidence_count") or 0)
        nonsecret_claim_count = int(summary.get("nonsecret_authorization_claim_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            reads_secret_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                decision.get("ready_for_database_apply_now") is not False,
                decision.get("issues_database_apply_authorization") is not False,
                decision.get("signs_database_apply_authorization") is not False,
                package.get("ready_for_database_apply_now") is not False,
                package.get("issues_database_apply_authorization") is not False,
                package.get("signs_database_apply_authorization") is not False,
                package.get("secret_material_included") is not False,
                package.get("secret_material_required_in_preview") is not False,
                package.get("reads_secret_in_preview") is not False,
                package.get("writes_database_in_preview") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            closeout_ready_count == 1
            and preflight_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and preflight_check_count == 12
            and input_requirement_count == 10
            and rejection_reason_count == 11
            and required_evidence_count == 9
            and nonsecret_claim_count == 8
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and decision.get("ready_for_future_signing_decision_closeout") is True
            and decision.get("can_enter_unsigned_signing_decision_package_lane") is True
            and package.get("authorization_material_type") == "unsigned_signing_decision_package"
            and package.get("ready_for_future_unsigned_signing_decision_package") is True
            and package.get("requires_post_apply_verifier") is True
            and package.get("requires_fresh_production_truth_in_same_run") is True
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_unsigned_signing_decision_package_lane") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signing decision closeout 偵測到 secret、SQL、DB write、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signing_decision_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signing decision closeout 已自動完成 "
                f"{pass_count}/{check_count} checks，unsigned package 已綁定，authorization signing=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signing_issuer_guard_lane"
        else:
            status = "warning"
            summary_text = "PChome auto-policy signing decision closeout 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_signing_decision_closeout"

        return _check(
            "PChome auto-policy signing decision closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "signing_decision_closeout_ready_count": closeout_ready_count,
                "signing_decision_preflight_ready_count": preflight_ready_count,
                "signing_decision_closeout_check_count": check_count,
                "signing_decision_closeout_pass_count": pass_count,
                "signing_decision_closeout_waiting_count": waiting_count,
                "signing_decision_preflight_check_count": preflight_check_count,
                "signing_decision_input_requirement_count": input_requirement_count,
                "signing_decision_rejection_reason_count": rejection_reason_count,
                "required_issuer_evidence_count": required_evidence_count,
                "nonsecret_authorization_claim_count": nonsecret_claim_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "reads_secret_count": reads_secret_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(
                    decision.get("ready_for_database_apply_now")
                    or package.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    decision.get("issues_database_apply_authorization")
                    or package.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    decision.get("signs_database_apply_authorization")
                    or package.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(package.get("secret_material_included")),
                "secret_material_required_in_preview": bool(
                    package.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "permits_future_unsigned_signing_decision_package_lane": bool(
                    contract.get("permits_future_unsigned_signing_decision_package_lane")
                ),
                "requires_post_apply_verifier": bool(
                    package.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    package.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signing decision closeout",
            "warning",
            f"PChome auto-policy signing decision closeout 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_signing_decision_closeout",
            },
        )


def _pchome_auto_policy_signing_issuer_guard_check() -> Dict[str, Any]:
    """Read-only monitor for the future signing issuer guard boundary."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        guard = backlog.build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard(
            payload,
            batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
            execute_fetch=True,
            timeout_seconds=max(
                1,
                min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
            ),
            http_get=_pchome_auto_policy_machine_fetch_evidence_get,
        )
        summary = guard.get("summary") or {}
        issuer_guard = guard.get("future_authorization_signing_issuer_guard") or {}
        boundary = guard.get("signable_request_boundary") or {}
        contract = guard.get("signing_issuer_guard_contract") or {}
        safety = guard.get("safety") or {}
        result = str(guard.get("result") or "UNKNOWN")

        guard_ready_count = int(
            summary.get("authorization_signing_issuer_guard_ready_count") or 0
        )
        check_count = int(summary.get("signing_issuer_guard_check_count") or 0)
        pass_count = int(summary.get("signing_issuer_guard_pass_count") or 0)
        waiting_count = int(summary.get("signing_issuer_guard_waiting_count") or 0)
        closeout_ready_count = int(
            summary.get("authorization_signing_decision_closeout_ready_count") or 0
        )
        closeout_check_count = int(summary.get("signing_decision_closeout_check_count") or 0)
        input_requirement_count = int(
            summary.get("signing_decision_input_requirement_count") or 0
        )
        rejection_reason_count = int(
            summary.get("signing_decision_rejection_reason_count") or 0
        )
        required_evidence_count = int(summary.get("required_issuer_evidence_count") or 0)
        nonsecret_claim_count = int(summary.get("nonsecret_authorization_claim_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            reads_secret_count
            + executes_script_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                issuer_guard.get("ready_for_database_apply_now") is not False,
                issuer_guard.get("issues_database_apply_authorization") is not False,
                issuer_guard.get("signs_database_apply_authorization") is not False,
                boundary.get("ready_for_database_apply_now") is not False,
                boundary.get("issues_database_apply_authorization") is not False,
                boundary.get("signs_database_apply_authorization") is not False,
                boundary.get("secret_material_included") is not False,
                boundary.get("secret_material_required_in_preview") is not False,
                boundary.get("reads_secret_in_preview") is not False,
                boundary.get("executes_sql_in_preview") is not False,
                boundary.get("writes_database_in_preview") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        guard_contract_present = (
            guard_ready_count == 1
            and closeout_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and closeout_check_count == 12
            and input_requirement_count == 10
            and rejection_reason_count == 11
            and required_evidence_count == 9
            and nonsecret_claim_count == 8
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and issuer_guard.get("ready_for_future_signing_issuer_guard") is True
            and issuer_guard.get("can_enter_future_authorization_signing_issuer_lane") is True
            and boundary.get("request_boundary_type") == "future_signable_request_boundary"
            and boundary.get("ready_for_future_signable_request_boundary") is True
            and boundary.get("can_enter_future_authorization_signing_issuer_lane") is True
            and boundary.get("hash_matches") is True
            and boundary.get("requires_post_apply_verifier") is True
            and boundary.get("requires_fresh_production_truth_in_same_run") is True
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_authorization_signing_issuer_lane") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signing issuer guard 偵測到 secret、SQL、DB write、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = "halt_pchome_auto_policy_signing_issuer_guard_and_inspect_risk"
        elif guard_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signing issuer guard 已自動完成 "
                f"{pass_count}/{check_count} checks，signable boundary 已綁定，authorization signing=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signing_issuer_closeout_lane"
        else:
            status = "warning"
            summary_text = "PChome auto-policy signing issuer guard 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_signing_issuer_guard"

        return _check(
            "PChome auto-policy signing issuer guard",
            status,
            summary_text,
            {
                "policy": guard.get("policy"),
                "result": result,
                "source_policy": guard.get("source_policy"),
                "signing_issuer_guard_ready_count": guard_ready_count,
                "signing_issuer_guard_check_count": check_count,
                "signing_issuer_guard_pass_count": pass_count,
                "signing_issuer_guard_waiting_count": waiting_count,
                "signing_decision_closeout_ready_count": closeout_ready_count,
                "signing_decision_closeout_check_count": closeout_check_count,
                "signing_decision_input_requirement_count": input_requirement_count,
                "signing_decision_rejection_reason_count": rejection_reason_count,
                "required_issuer_evidence_count": required_evidence_count,
                "nonsecret_authorization_claim_count": nonsecret_claim_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(
                    issuer_guard.get("ready_for_database_apply_now")
                    or boundary.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    issuer_guard.get("issues_database_apply_authorization")
                    or boundary.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    issuer_guard.get("signs_database_apply_authorization")
                    or boundary.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(boundary.get("secret_material_included")),
                "secret_material_required_in_preview": bool(
                    boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "ready_for_future_signable_request_boundary": bool(
                    boundary.get("ready_for_future_signable_request_boundary")
                ),
                "permits_future_authorization_signing_issuer_lane": bool(
                    contract.get("permits_future_authorization_signing_issuer_lane")
                ),
                "requires_post_apply_verifier": bool(
                    boundary.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    boundary.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signing issuer guard",
            "warning",
            f"PChome auto-policy signing issuer guard 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_signing_issuer_guard",
            },
        )


def _pchome_auto_policy_signing_issuer_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the final signable request closeout package."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        issuer_closeout = closeout.get("future_authorization_signing_issuer_closeout") or {}
        package = closeout.get("final_signable_request_package") or {}
        contract = closeout.get("signing_issuer_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        result = str(closeout.get("result") or "UNKNOWN")

        closeout_ready_count = int(
            summary.get("authorization_signing_issuer_closeout_ready_count") or 0
        )
        check_count = int(summary.get("signing_issuer_closeout_check_count") or 0)
        pass_count = int(summary.get("signing_issuer_closeout_pass_count") or 0)
        waiting_count = int(summary.get("signing_issuer_closeout_waiting_count") or 0)
        guard_ready_count = int(
            summary.get("authorization_signing_issuer_guard_ready_count") or 0
        )
        guard_check_count = int(summary.get("signing_issuer_guard_check_count") or 0)
        input_requirement_count = int(
            summary.get("signing_decision_input_requirement_count") or 0
        )
        rejection_reason_count = int(
            summary.get("signing_decision_rejection_reason_count") or 0
        )
        required_evidence_count = int(summary.get("required_issuer_evidence_count") or 0)
        nonsecret_claim_count = int(summary.get("nonsecret_authorization_claim_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            reads_secret_count
            + executes_script_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                issuer_closeout.get("ready_for_database_apply_now") is not False,
                issuer_closeout.get("issues_database_apply_authorization") is not False,
                issuer_closeout.get("signs_database_apply_authorization") is not False,
                package.get("ready_for_database_apply_now") is not False,
                package.get("issues_database_apply_authorization") is not False,
                package.get("signs_database_apply_authorization") is not False,
                package.get("secret_material_included") is not False,
                package.get("secret_material_required_in_preview") is not False,
                package.get("reads_secret_in_preview") is not False,
                package.get("executes_sql_in_preview") is not False,
                package.get("writes_database_in_preview") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            closeout_ready_count == 1
            and guard_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and guard_check_count == 12
            and input_requirement_count == 10
            and rejection_reason_count == 11
            and required_evidence_count == 9
            and nonsecret_claim_count == 8
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and issuer_closeout.get("ready_for_future_signing_issuer_closeout") is True
            and (
                issuer_closeout.get("can_enter_future_final_signable_request_package_lane")
                is True
            )
            and package.get("authorization_material_type") == "final_signable_request_package"
            and package.get("ready_for_future_final_signable_request_package") is True
            and package.get("hash_matches") is True
            and package.get("requires_post_apply_verifier") is True
            and package.get("requires_fresh_production_truth_in_same_run") is True
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_final_signable_request_package_lane") is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signing issuer closeout 偵測到 secret、SQL、DB write、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signing_issuer_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signing issuer closeout 已自動完成 "
                f"{pass_count}/{check_count} checks，final signable package 已綁定，authorization signing=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signing_execution_preflight_lane"
        else:
            status = "warning"
            summary_text = "PChome auto-policy signing issuer closeout 尚未達自動監控契約"
            next_machine_action = "refresh_pchome_auto_policy_signing_issuer_closeout"

        return _check(
            "PChome auto-policy signing issuer closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "signing_issuer_closeout_ready_count": closeout_ready_count,
                "signing_issuer_closeout_check_count": check_count,
                "signing_issuer_closeout_pass_count": pass_count,
                "signing_issuer_closeout_waiting_count": waiting_count,
                "signing_issuer_guard_ready_count": guard_ready_count,
                "signing_issuer_guard_check_count": guard_check_count,
                "signing_decision_input_requirement_count": input_requirement_count,
                "signing_decision_rejection_reason_count": rejection_reason_count,
                "required_issuer_evidence_count": required_evidence_count,
                "nonsecret_authorization_claim_count": nonsecret_claim_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_database_apply_now": bool(
                    issuer_closeout.get("ready_for_database_apply_now")
                    or package.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    issuer_closeout.get("issues_database_apply_authorization")
                    or package.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    issuer_closeout.get("signs_database_apply_authorization")
                    or package.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(package.get("secret_material_included")),
                "secret_material_required_in_preview": bool(
                    package.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "ready_for_future_final_signable_request_package": bool(
                    package.get("ready_for_future_final_signable_request_package")
                ),
                "permits_future_final_signable_request_package_lane": bool(
                    contract.get("permits_future_final_signable_request_package_lane")
                ),
                "requires_post_apply_verifier": bool(
                    package.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    package.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signing issuer closeout",
            "warning",
            f"PChome auto-policy signing issuer closeout 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": "refresh_pchome_auto_policy_signing_issuer_closeout",
            },
        )


def _pchome_auto_policy_signing_execution_preflight_check() -> Dict[str, Any]:
    """Read-only monitor for future signing execution preflight readiness."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        preflight = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = preflight.get("summary") or {}
        future_preflight = (
            preflight.get("future_authorization_signing_execution_preflight") or {}
        )
        package = preflight.get("signing_execution_preflight_package") or {}
        boundary = preflight.get("operator_held_secret_boundary_contract") or {}
        contract = preflight.get("signing_execution_preflight_contract") or {}
        safety = preflight.get("safety") or {}
        command_preview = package.get("command_preview") or {}
        result = str(preflight.get("result") or "UNKNOWN")

        preflight_ready_count = int(
            summary.get("authorization_signing_execution_preflight_ready_count") or 0
        )
        check_count = int(summary.get("signing_execution_preflight_check_count") or 0)
        pass_count = int(summary.get("signing_execution_preflight_pass_count") or 0)
        waiting_count = int(summary.get("signing_execution_preflight_waiting_count") or 0)
        closeout_ready_count = int(
            summary.get("authorization_signing_issuer_closeout_ready_count") or 0
        )
        closeout_check_count = int(summary.get("signing_issuer_closeout_check_count") or 0)
        closeout_pass_count = int(summary.get("signing_issuer_closeout_pass_count") or 0)
        final_package_ready_count = int(
            summary.get("final_signable_request_package_ready_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        input_requirement_count = int(
            summary.get("signing_execution_input_requirement_count") or 0
        )
        abort_condition_count = int(
            summary.get("signing_execution_abort_condition_count") or 0
        )
        rollback_boundary_count = int(summary.get("rollback_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                future_preflight.get("ready_for_database_apply_now") is not False,
                future_preflight.get("issues_database_apply_authorization") is not False,
                future_preflight.get("signs_database_apply_authorization") is not False,
                future_preflight.get("secret_material_included") is not False,
                future_preflight.get("secret_material_required_in_preview") is not False,
                future_preflight.get("reads_secret_in_preview") is not False,
                package.get("ready_for_database_apply_now") is not False,
                package.get("issues_database_apply_authorization") is not False,
                package.get("signs_database_apply_authorization") is not False,
                package.get("secret_material_included") is not False,
                package.get("secret_material_required_in_preview") is not False,
                package.get("reads_secret_in_preview") is not False,
                package.get("executes_shell_in_preview") is not False,
                package.get("executes_sql_in_preview") is not False,
                package.get("writes_database_in_preview") is not False,
                boundary.get("secret_material_included") is not False,
                boundary.get("secret_material_required_in_preview") is not False,
                boundary.get("reads_secret_in_preview") is not False,
                boundary.get("accepts_plaintext_secret") is not False,
                boundary.get("permits_secret_value_logging") is not False,
                command_preview.get("executes_in_preview") is not False,
                command_preview.get("signs_database_apply_authorization") is not False,
                command_preview.get("writes_database") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        preflight_contract_present = (
            preflight_ready_count == 1
            and closeout_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and closeout_check_count == 12
            and final_package_ready_count == 1
            and secret_boundary_count == 1
            and input_requirement_count == 10
            and abort_condition_count == 8
            and rollback_boundary_count == 4
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_preflight.get("ready_for_future_signing_execution_preflight")
            is True
            and (
                future_preflight.get(
                    "can_enter_future_authorization_signing_execution_lane"
                )
                is True
            )
            and package.get("authorization_material_type")
            == "signing_execution_preflight_package"
            and package.get("ready_for_future_signing_execution_preflight") is True
            and int(package.get("required_nonsecret_input_count") or 0) == 10
            and package.get("hash_matches") is True
            and package.get("requires_post_apply_verifier") is True
            and package.get("requires_fresh_production_truth_in_same_run") is True
            and boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and command_preview.get("mode") == "future_command_shape_only"
            and command_preview.get("redacts_secret_values") is True
            and command_preview.get("executes_in_preview") is False
            and command_preview.get("signs_database_apply_authorization") is False
            and command_preview.get("writes_database") is False
            and contract.get("machine_verifiable") is True
            and (
                contract.get(
                    "permits_future_explicit_authorization_signing_execution_lane"
                )
                is True
            )
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signing execution preflight 偵測到 secret、SQL、"
                "DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signing_execution_preflight_and_inspect_risk"
            )
        elif preflight_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signing execution preflight 已自動完成 "
                f"{pass_count}/{check_count} checks，operator-held secret boundary 已外部化，authorization signing=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signing_execution_closeout_lane"
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy signing execution preflight 尚未達自動監控契約"
            )
            next_machine_action = "refresh_pchome_auto_policy_signing_execution_preflight"

        return _check(
            "PChome auto-policy signing execution preflight",
            status,
            summary_text,
            {
                "policy": preflight.get("policy"),
                "result": result,
                "source_policy": preflight.get("source_policy"),
                "signing_execution_preflight_ready_count": preflight_ready_count,
                "signing_execution_preflight_check_count": check_count,
                "signing_execution_preflight_pass_count": pass_count,
                "signing_execution_preflight_waiting_count": waiting_count,
                "signing_issuer_closeout_ready_count": closeout_ready_count,
                "signing_issuer_closeout_check_count": closeout_check_count,
                "signing_issuer_closeout_pass_count": closeout_pass_count,
                "final_signable_request_package_ready_count": (
                    final_package_ready_count
                ),
                "operator_held_secret_boundary_count": secret_boundary_count,
                "signing_execution_input_requirement_count": input_requirement_count,
                "signing_execution_abort_condition_count": abort_condition_count,
                "rollback_boundary_count": rollback_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": boundary.get("secret_reference_mode"),
                "command_preview_redacts_secret_values": bool(
                    command_preview.get("redacts_secret_values")
                ),
                "command_preview_executes_in_preview": bool(
                    command_preview.get("executes_in_preview")
                ),
                "ready_for_database_apply_now": bool(
                    future_preflight.get("ready_for_database_apply_now")
                    or package.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_preflight.get("issues_database_apply_authorization")
                    or package.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_preflight.get("signs_database_apply_authorization")
                    or package.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_preflight.get("secret_material_included")
                    or package.get("secret_material_included")
                    or boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_preflight.get("secret_material_required_in_preview")
                    or package.get("secret_material_required_in_preview")
                    or boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "ready_for_future_signing_execution_preflight": bool(
                    future_preflight.get("ready_for_future_signing_execution_preflight")
                ),
                "permits_future_explicit_authorization_signing_execution_lane": bool(
                    contract.get(
                        "permits_future_explicit_authorization_signing_execution_lane"
                    )
                ),
                "requires_post_apply_verifier": bool(
                    package.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    package.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signing execution preflight",
            "warning",
            f"PChome auto-policy signing execution preflight 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_signing_execution_preflight"
                ),
            },
        )


def _pchome_auto_policy_signing_execution_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the unsigned signed-authorization receipt boundary."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        future_closeout = closeout.get("future_authorization_signing_execution_closeout") or {}
        unsigned_boundary = closeout.get("unsigned_signed_authorization_receipt_boundary") or {}
        boundary = unsigned_boundary.get("operator_held_secret_boundary_contract") or {}
        command_preview = unsigned_boundary.get("command_preview") or {}
        contract = closeout.get("signing_execution_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        result = str(closeout.get("result") or "UNKNOWN")

        closeout_ready_count = int(
            summary.get("authorization_signing_execution_closeout_ready_count") or 0
        )
        check_count = int(summary.get("signing_execution_closeout_check_count") or 0)
        pass_count = int(summary.get("signing_execution_closeout_pass_count") or 0)
        waiting_count = int(summary.get("signing_execution_closeout_waiting_count") or 0)
        preflight_ready_count = int(
            summary.get("authorization_signing_execution_preflight_ready_count") or 0
        )
        preflight_check_count = int(
            summary.get("signing_execution_preflight_check_count") or 0
        )
        preflight_pass_count = int(
            summary.get("signing_execution_preflight_pass_count") or 0
        )
        unsigned_boundary_count = int(
            summary.get("unsigned_signed_authorization_receipt_boundary_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        input_requirement_count = int(
            summary.get("signing_execution_input_requirement_count") or 0
        )
        abort_condition_count = int(
            summary.get("signing_execution_abort_condition_count") or 0
        )
        rollback_boundary_count = int(summary.get("rollback_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                future_closeout.get("ready_for_database_apply_now") is not False,
                future_closeout.get("issues_database_apply_authorization") is not False,
                future_closeout.get("signs_database_apply_authorization") is not False,
                future_closeout.get("secret_material_included") is not False,
                future_closeout.get("secret_material_required_in_preview") is not False,
                future_closeout.get("reads_secret_in_preview") is not False,
                unsigned_boundary.get("ready_for_database_apply_now") is not False,
                unsigned_boundary.get("issues_database_apply_authorization") is not False,
                unsigned_boundary.get("signs_database_apply_authorization") is not False,
                unsigned_boundary.get("signed_authorization_receipt_included") is not False,
                unsigned_boundary.get("signature_material_included") is not False,
                unsigned_boundary.get("secret_material_included") is not False,
                unsigned_boundary.get("secret_material_required_in_preview") is not False,
                unsigned_boundary.get("reads_secret_in_preview") is not False,
                unsigned_boundary.get("executes_shell_in_preview") is not False,
                unsigned_boundary.get("executes_sql_in_preview") is not False,
                unsigned_boundary.get("writes_database_in_preview") is not False,
                boundary.get("secret_material_included") is not False,
                boundary.get("secret_material_required_in_preview") is not False,
                boundary.get("reads_secret_in_preview") is not False,
                boundary.get("accepts_plaintext_secret") is not False,
                boundary.get("permits_secret_value_logging") is not False,
                command_preview.get("executes_in_preview") is not False,
                command_preview.get("signs_database_apply_authorization") is not False,
                command_preview.get("writes_database") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            closeout_ready_count == 1
            and preflight_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and preflight_check_count == 12
            and unsigned_boundary_count == 1
            and secret_boundary_count == 1
            and input_requirement_count == 10
            and abort_condition_count == 8
            and rollback_boundary_count == 4
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_closeout.get("ready_for_future_signing_execution_closeout")
            is True
            and (
                future_closeout.get(
                    "can_enter_future_unsigned_signed_authorization_receipt_boundary"
                )
                is True
            )
            and unsigned_boundary.get("authorization_material_type")
            == "unsigned_signed_authorization_receipt_boundary"
            and (
                unsigned_boundary.get(
                    "ready_for_future_unsigned_signed_authorization_receipt_boundary"
                )
                is True
            )
            and unsigned_boundary.get("ready_for_future_signed_authorization_receipt_lane")
            is True
            and unsigned_boundary.get("signed_authorization_receipt_included") is False
            and unsigned_boundary.get("signature_material_included") is False
            and unsigned_boundary.get("hash_matches") is True
            and unsigned_boundary.get("requires_post_apply_verifier") is True
            and unsigned_boundary.get("requires_fresh_production_truth_in_same_run")
            is True
            and boundary.get("secret_reference_mode") == "external_runtime_reference_only"
            and command_preview.get("mode") == "future_command_shape_only"
            and command_preview.get("redacts_secret_values") is True
            and command_preview.get("executes_in_preview") is False
            and command_preview.get("signs_database_apply_authorization") is False
            and command_preview.get("writes_database") is False
            and contract.get("machine_verifiable") is True
            and (
                contract.get(
                    "permits_future_unsigned_signed_authorization_receipt_boundary"
                )
                is True
            )
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signing execution closeout 偵測到 secret、SQL、"
                "DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signing_execution_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signing execution closeout 已自動完成 "
                f"{pass_count}/{check_count} checks，unsigned receipt boundary 已綁定，authorization signing=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signed_receipt_preflight_lane"
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy signing execution closeout 尚未達自動監控契約"
            )
            next_machine_action = "refresh_pchome_auto_policy_signing_execution_closeout"

        return _check(
            "PChome auto-policy signing execution closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "signing_execution_closeout_ready_count": closeout_ready_count,
                "signing_execution_closeout_check_count": check_count,
                "signing_execution_closeout_pass_count": pass_count,
                "signing_execution_closeout_waiting_count": waiting_count,
                "signing_execution_preflight_ready_count": preflight_ready_count,
                "signing_execution_preflight_check_count": preflight_check_count,
                "signing_execution_preflight_pass_count": preflight_pass_count,
                "unsigned_signed_authorization_receipt_boundary_count": (
                    unsigned_boundary_count
                ),
                "operator_held_secret_boundary_count": secret_boundary_count,
                "signing_execution_input_requirement_count": input_requirement_count,
                "signing_execution_abort_condition_count": abort_condition_count,
                "rollback_boundary_count": rollback_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": boundary.get("secret_reference_mode"),
                "command_preview_redacts_secret_values": bool(
                    command_preview.get("redacts_secret_values")
                ),
                "command_preview_executes_in_preview": bool(
                    command_preview.get("executes_in_preview")
                ),
                "signed_authorization_receipt_included": bool(
                    unsigned_boundary.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    unsigned_boundary.get("signature_material_included")
                ),
                "ready_for_database_apply_now": bool(
                    future_closeout.get("ready_for_database_apply_now")
                    or unsigned_boundary.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_closeout.get("issues_database_apply_authorization")
                    or unsigned_boundary.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_closeout.get("signs_database_apply_authorization")
                    or unsigned_boundary.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_closeout.get("secret_material_included")
                    or unsigned_boundary.get("secret_material_included")
                    or boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_closeout.get("secret_material_required_in_preview")
                    or unsigned_boundary.get("secret_material_required_in_preview")
                    or boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "ready_for_future_signing_execution_closeout": bool(
                    future_closeout.get("ready_for_future_signing_execution_closeout")
                ),
                "ready_for_future_unsigned_signed_authorization_receipt_boundary": bool(
                    unsigned_boundary.get(
                        "ready_for_future_unsigned_signed_authorization_receipt_boundary"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_lane": bool(
                    unsigned_boundary.get("ready_for_future_signed_authorization_receipt_lane")
                ),
                "permits_future_unsigned_signed_authorization_receipt_boundary": bool(
                    contract.get(
                        "permits_future_unsigned_signed_authorization_receipt_boundary"
                    )
                ),
                "requires_post_apply_verifier": bool(
                    unsigned_boundary.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    unsigned_boundary.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signing execution closeout",
            "warning",
            f"PChome auto-policy signing execution closeout 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_signing_execution_closeout"
                ),
            },
        )


def _pchome_auto_policy_signed_receipt_preflight_check() -> Dict[str, Any]:
    """Read-only monitor for external signed-receipt evidence boundary preflight."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        preflight = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = preflight.get("summary") or {}
        future_preflight = (
            preflight.get("future_authorization_signed_receipt_preflight") or {}
        )
        evidence_boundary = (
            preflight.get("external_signing_receipt_evidence_boundary") or {}
        )
        boundary = evidence_boundary.get("operator_held_secret_boundary_contract") or {}
        contract = preflight.get("signed_receipt_preflight_contract") or {}
        safety = preflight.get("safety") or {}
        required_evidence = list(
            evidence_boundary.get("required_external_receipt_evidence") or []
        )
        result = str(preflight.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("authorization_signed_receipt_preflight_ready_count") or 0
        )
        check_count = int(summary.get("signed_receipt_preflight_check_count") or 0)
        pass_count = int(summary.get("signed_receipt_preflight_pass_count") or 0)
        waiting_count = int(summary.get("signed_receipt_preflight_waiting_count") or 0)
        closeout_ready_count = int(
            summary.get("authorization_signing_execution_closeout_ready_count") or 0
        )
        closeout_check_count = int(
            summary.get("signing_execution_closeout_check_count") or 0
        )
        unsigned_boundary_count = int(
            summary.get("unsigned_signed_authorization_receipt_boundary_count") or 0
        )
        evidence_boundary_count = int(
            summary.get("external_signing_receipt_evidence_boundary_count") or 0
        )
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        acceptance_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        input_requirement_count = int(
            summary.get("signing_execution_input_requirement_count") or 0
        )
        abort_condition_count = int(
            summary.get("signing_execution_abort_condition_count") or 0
        )
        rollback_boundary_count = int(summary.get("rollback_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("persists_receipt") is not False,
                safety.get("updates_mapping") is not False,
                safety.get("dispatches_telegram") is not False,
                safety.get("llm_calls_in_gate") is not False,
                future_preflight.get("ready_for_database_apply_now") is not False,
                future_preflight.get("issues_database_apply_authorization") is not False,
                future_preflight.get("signs_database_apply_authorization") is not False,
                future_preflight.get("signed_authorization_receipt_included") is not False,
                future_preflight.get("signature_material_included") is not False,
                future_preflight.get("secret_material_included") is not False,
                future_preflight.get("secret_material_required_in_preview") is not False,
                future_preflight.get("reads_secret_in_preview") is not False,
                evidence_boundary.get("external_signed_authorization_receipt_included")
                is not False,
                evidence_boundary.get("signed_authorization_receipt_included") is not False,
                evidence_boundary.get("signature_material_included") is not False,
                evidence_boundary.get("secret_material_included") is not False,
                evidence_boundary.get("secret_material_required_in_preview") is not False,
                evidence_boundary.get("reads_secret_in_preview") is not False,
                evidence_boundary.get("executes_shell_in_preview") is not False,
                evidence_boundary.get("executes_sql_in_preview") is not False,
                evidence_boundary.get("writes_database_in_preview") is not False,
                evidence_boundary.get("ready_for_database_apply_now") is not False,
                evidence_boundary.get("issues_database_apply_authorization") is not False,
                evidence_boundary.get("signs_database_apply_authorization") is not False,
                boundary.get("secret_material_included") is not False,
                boundary.get("secret_material_required_in_preview") is not False,
                boundary.get("reads_secret_in_preview") is not False,
                boundary.get("accepts_plaintext_secret") is not False,
                boundary.get("permits_secret_value_logging") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        preflight_contract_present = (
            ready_count == 1
            and closeout_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and closeout_check_count == 12
            and unsigned_boundary_count == 1
            and evidence_boundary_count == 1
            and required_evidence_count == 10
            and acceptance_gate_count == 8
            and secret_boundary_count == 1
            and input_requirement_count == 10
            and abort_condition_count == 8
            and rollback_boundary_count == 4
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_preflight.get(
                "ready_for_future_signed_authorization_receipt_preflight"
            )
            is True
            and future_preflight.get(
                "can_enter_future_external_signing_receipt_evidence_boundary"
            )
            is True
            and evidence_boundary.get("authorization_material_type")
            == "external_signing_receipt_evidence_boundary"
            and evidence_boundary.get(
                "ready_for_future_external_signing_receipt_evidence_boundary"
            )
            is True
            and evidence_boundary.get("ready_for_future_signed_authorization_receipt_lane")
            is True
            and evidence_boundary.get("external_signed_authorization_receipt_required_in_future")
            is True
            and evidence_boundary.get("external_signed_authorization_receipt_included")
            is False
            and evidence_boundary.get("signed_authorization_receipt_included") is False
            and evidence_boundary.get("signature_material_included") is False
            and evidence_boundary.get("signer_key_id_reference_only") is True
            and evidence_boundary.get("signature_algorithm_reference_only") is True
            and "detached_signature_verification_status" in required_evidence
            and evidence_boundary.get("hash_matches") is True
            and evidence_boundary.get("requires_post_apply_verifier") is True
            and evidence_boundary.get("requires_fresh_production_truth_in_same_run")
            is True
            and boundary.get("secret_reference_mode") == "external_runtime_reference_only"
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_external_signing_receipt_evidence_boundary"
            )
            is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signed receipt preflight 偵測到 secret、signature、"
                "SQL、DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signed_receipt_preflight_and_inspect_risk"
            )
        elif preflight_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signed receipt preflight 已自動完成 "
                f"{pass_count}/{check_count} checks，external receipt evidence boundary 已綁定，signed receipt payload=0"
            )
            next_machine_action = "continue_to_pchome_auto_policy_signed_receipt_closeout_lane"
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy signed receipt preflight 尚未達自動監控契約"
            )
            next_machine_action = "refresh_pchome_auto_policy_signed_receipt_preflight"

        return _check(
            "PChome auto-policy signed receipt preflight",
            status,
            summary_text,
            {
                "policy": preflight.get("policy"),
                "result": result,
                "source_policy": preflight.get("source_policy"),
                "signed_receipt_preflight_ready_count": ready_count,
                "signed_receipt_preflight_check_count": check_count,
                "signed_receipt_preflight_pass_count": pass_count,
                "signed_receipt_preflight_waiting_count": waiting_count,
                "signing_execution_closeout_ready_count": closeout_ready_count,
                "signing_execution_closeout_check_count": closeout_check_count,
                "unsigned_signed_authorization_receipt_boundary_count": (
                    unsigned_boundary_count
                ),
                "external_signing_receipt_evidence_boundary_count": (
                    evidence_boundary_count
                ),
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": acceptance_gate_count,
                "operator_held_secret_boundary_count": secret_boundary_count,
                "signing_execution_input_requirement_count": input_requirement_count,
                "signing_execution_abort_condition_count": abort_condition_count,
                "rollback_boundary_count": rollback_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": boundary.get("secret_reference_mode"),
                "external_signed_authorization_receipt_required_in_future": bool(
                    evidence_boundary.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    evidence_boundary.get("external_signed_authorization_receipt_included")
                ),
                "signed_authorization_receipt_included": bool(
                    future_preflight.get("signed_authorization_receipt_included")
                    or evidence_boundary.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    future_preflight.get("signature_material_included")
                    or evidence_boundary.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    evidence_boundary.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    evidence_boundary.get("signature_algorithm_reference_only")
                ),
                "detached_signature_verification_required": (
                    "detached_signature_verification_status" in required_evidence
                ),
                "ready_for_database_apply_now": bool(
                    future_preflight.get("ready_for_database_apply_now")
                    or evidence_boundary.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_preflight.get("issues_database_apply_authorization")
                    or evidence_boundary.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_preflight.get("signs_database_apply_authorization")
                    or evidence_boundary.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_preflight.get("secret_material_included")
                    or evidence_boundary.get("secret_material_included")
                    or boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_preflight.get("secret_material_required_in_preview")
                    or evidence_boundary.get("secret_material_required_in_preview")
                    or boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "ready_for_future_signed_authorization_receipt_preflight": bool(
                    future_preflight.get(
                        "ready_for_future_signed_authorization_receipt_preflight"
                    )
                ),
                "can_enter_future_external_signing_receipt_evidence_boundary": bool(
                    future_preflight.get(
                        "can_enter_future_external_signing_receipt_evidence_boundary"
                    )
                ),
                "ready_for_future_external_signing_receipt_evidence_boundary": bool(
                    evidence_boundary.get(
                        "ready_for_future_external_signing_receipt_evidence_boundary"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_lane": bool(
                    evidence_boundary.get("ready_for_future_signed_authorization_receipt_lane")
                ),
                "permits_future_external_signing_receipt_evidence_boundary": bool(
                    contract.get(
                        "permits_future_external_signing_receipt_evidence_boundary"
                    )
                ),
                "requires_post_apply_verifier": bool(
                    evidence_boundary.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    evidence_boundary.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signed receipt preflight",
            "warning",
            f"PChome auto-policy signed receipt preflight 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_signed_receipt_preflight"
                ),
            },
        )


def _pchome_auto_policy_signed_receipt_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the detached receipt verification boundary closeout."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        future_closeout = (
            closeout.get("future_authorization_signed_receipt_closeout") or {}
        )
        detached_boundary = closeout.get("detached_receipt_verification_boundary") or {}
        operator_boundary = (
            detached_boundary.get("operator_held_secret_boundary_contract") or {}
        )
        contract = closeout.get("signed_receipt_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        detached_checks = list(
            detached_boundary.get("detached_receipt_verification_checks") or []
        )
        result = str(closeout.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("authorization_signed_receipt_closeout_ready_count") or 0
        )
        check_count = int(summary.get("signed_receipt_closeout_check_count") or 0)
        pass_count = int(summary.get("signed_receipt_closeout_pass_count") or 0)
        waiting_count = int(summary.get("signed_receipt_closeout_waiting_count") or 0)
        preflight_ready_count = int(
            summary.get("authorization_signed_receipt_preflight_ready_count") or 0
        )
        preflight_check_count = int(summary.get("signed_receipt_preflight_check_count") or 0)
        evidence_boundary_count = int(
            summary.get("external_signing_receipt_evidence_boundary_count") or 0
        )
        detached_boundary_count = int(
            summary.get("detached_receipt_verification_boundary_count") or 0
        )
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        acceptance_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        detached_check_count = int(
            summary.get("detached_receipt_verification_check_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        input_requirement_count = int(
            summary.get("signing_execution_input_requirement_count") or 0
        )
        abort_condition_count = int(
            summary.get("signing_execution_abort_condition_count") or 0
        )
        rollback_boundary_count = int(summary.get("rollback_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("persists_receipt") is not False,
                safety.get("updates_mapping") is not False,
                safety.get("dispatches_telegram") is not False,
                safety.get("llm_calls_in_gate") is not False,
                future_closeout.get("ready_for_database_apply_now") is not False,
                future_closeout.get("issues_database_apply_authorization") is not False,
                future_closeout.get("signs_database_apply_authorization") is not False,
                future_closeout.get("external_signed_authorization_receipt_included")
                is not False,
                future_closeout.get("signed_authorization_receipt_included") is not False,
                future_closeout.get("signature_material_included") is not False,
                future_closeout.get("secret_material_included") is not False,
                future_closeout.get("secret_material_required_in_preview") is not False,
                future_closeout.get("reads_secret_in_preview") is not False,
                detached_boundary.get("detached_signature_verification_performed")
                is not False,
                detached_boundary.get("external_signed_authorization_receipt_included")
                is not False,
                detached_boundary.get("signed_authorization_receipt_included") is not False,
                detached_boundary.get("signature_material_included") is not False,
                detached_boundary.get("secret_material_included") is not False,
                detached_boundary.get("secret_material_required_in_preview") is not False,
                detached_boundary.get("reads_secret_in_preview") is not False,
                detached_boundary.get("executes_shell_in_preview") is not False,
                detached_boundary.get("executes_sql_in_preview") is not False,
                detached_boundary.get("writes_database_in_preview") is not False,
                detached_boundary.get("ready_for_database_apply_now") is not False,
                detached_boundary.get("issues_database_apply_authorization") is not False,
                detached_boundary.get("signs_database_apply_authorization") is not False,
                operator_boundary.get("secret_material_included") is not False,
                operator_boundary.get("secret_material_required_in_preview") is not False,
                operator_boundary.get("reads_secret_in_preview") is not False,
                operator_boundary.get("accepts_plaintext_secret") is not False,
                operator_boundary.get("permits_secret_value_logging") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            ready_count == 1
            and preflight_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and preflight_check_count == 12
            and evidence_boundary_count == 1
            and detached_boundary_count == 1
            and required_evidence_count == 10
            and acceptance_gate_count == 8
            and detached_check_count == 10
            and secret_boundary_count == 1
            and input_requirement_count == 10
            and abort_condition_count == 8
            and rollback_boundary_count == 4
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_closeout.get(
                "ready_for_future_signed_authorization_receipt_closeout"
            )
            is True
            and future_closeout.get(
                "can_enter_future_detached_receipt_verification_boundary"
            )
            is True
            and detached_boundary.get("authorization_material_type")
            == "detached_receipt_verification_boundary"
            and detached_boundary.get(
                "ready_for_future_detached_receipt_verification_boundary"
            )
            is True
            and detached_boundary.get(
                "ready_for_future_signed_authorization_receipt_verification_lane"
            )
            is True
            and "detached_signature_verification_status_passed" in detached_checks
            and detached_boundary.get("requires_detached_signature_verification") is True
            and detached_boundary.get("detached_signature_verification_performed") is False
            and detached_boundary.get("external_signed_authorization_receipt_required_in_future")
            is True
            and detached_boundary.get("external_signed_authorization_receipt_included")
            is False
            and detached_boundary.get("signed_authorization_receipt_included") is False
            and detached_boundary.get("signature_material_included") is False
            and detached_boundary.get("signer_key_id_reference_only") is True
            and detached_boundary.get("signature_algorithm_reference_only") is True
            and detached_boundary.get("hash_matches") is True
            and detached_boundary.get("requires_post_apply_verifier") is True
            and detached_boundary.get("requires_fresh_production_truth_in_same_run")
            is True
            and operator_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_detached_receipt_verification_boundary")
            is True
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signed receipt closeout 偵測到 secret、signature、"
                "detached verification execution、SQL、DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signed_receipt_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signed receipt closeout 已自動完成 "
                f"{pass_count}/{check_count} checks，detached verification boundary 已綁定，signed receipt payload=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_signed_receipt_evidence_intake_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy signed receipt closeout 尚未達自動監控契約"
            )
            next_machine_action = "refresh_pchome_auto_policy_signed_receipt_closeout"

        return _check(
            "PChome auto-policy signed receipt closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "signed_receipt_closeout_ready_count": ready_count,
                "signed_receipt_closeout_check_count": check_count,
                "signed_receipt_closeout_pass_count": pass_count,
                "signed_receipt_closeout_waiting_count": waiting_count,
                "signed_receipt_preflight_ready_count": preflight_ready_count,
                "signed_receipt_preflight_check_count": preflight_check_count,
                "external_signing_receipt_evidence_boundary_count": (
                    evidence_boundary_count
                ),
                "detached_receipt_verification_boundary_count": detached_boundary_count,
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": acceptance_gate_count,
                "detached_receipt_verification_check_count": detached_check_count,
                "operator_held_secret_boundary_count": secret_boundary_count,
                "signing_execution_input_requirement_count": input_requirement_count,
                "signing_execution_abort_condition_count": abort_condition_count,
                "rollback_boundary_count": rollback_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": operator_boundary.get("secret_reference_mode"),
                "requires_detached_signature_verification": bool(
                    detached_boundary.get("requires_detached_signature_verification")
                ),
                "detached_signature_verification_performed": bool(
                    detached_boundary.get("detached_signature_verification_performed")
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    detached_boundary.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    future_closeout.get(
                        "external_signed_authorization_receipt_included"
                    )
                    or detached_boundary.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    future_closeout.get("signed_authorization_receipt_included")
                    or detached_boundary.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    future_closeout.get("signature_material_included")
                    or detached_boundary.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    detached_boundary.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    detached_boundary.get("signature_algorithm_reference_only")
                ),
                "ready_for_database_apply_now": bool(
                    future_closeout.get("ready_for_database_apply_now")
                    or detached_boundary.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_closeout.get("issues_database_apply_authorization")
                    or detached_boundary.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_closeout.get("signs_database_apply_authorization")
                    or detached_boundary.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_closeout.get("secret_material_included")
                    or detached_boundary.get("secret_material_included")
                    or operator_boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_closeout.get("secret_material_required_in_preview")
                    or detached_boundary.get("secret_material_required_in_preview")
                    or operator_boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "ready_for_future_signed_authorization_receipt_closeout": bool(
                    future_closeout.get(
                        "ready_for_future_signed_authorization_receipt_closeout"
                    )
                ),
                "can_enter_future_detached_receipt_verification_boundary": bool(
                    future_closeout.get(
                        "can_enter_future_detached_receipt_verification_boundary"
                    )
                ),
                "ready_for_future_detached_receipt_verification_boundary": bool(
                    detached_boundary.get(
                        "ready_for_future_detached_receipt_verification_boundary"
                    )
                ),
                "ready_for_future_signed_authorization_receipt_verification_lane": bool(
                    detached_boundary.get(
                        "ready_for_future_signed_authorization_receipt_verification_lane"
                    )
                ),
                "permits_future_detached_receipt_verification_boundary": bool(
                    contract.get("permits_future_detached_receipt_verification_boundary")
                ),
                "requires_post_apply_verifier": bool(
                    detached_boundary.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    detached_boundary.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signed receipt closeout",
            "warning",
            f"PChome auto-policy signed receipt closeout 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_signed_receipt_closeout"
                ),
            },
        )


def _pchome_auto_policy_signed_receipt_evidence_intake_check() -> Dict[str, Any]:
    """Read-only monitor for the future detached verification evidence intake schema."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        intake = (
            backlog.build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = intake.get("summary") or {}
        future_intake = (
            intake.get("future_signed_authorization_receipt_evidence_intake") or {}
        )
        schema = intake.get("detached_verification_evidence_schema") or {}
        operator_boundary = (
            schema.get("operator_held_secret_boundary_contract") or {}
        )
        contract = intake.get("signed_receipt_evidence_intake_contract") or {}
        safety = intake.get("safety") or {}
        evidence_fields = list(schema.get("detached_verification_evidence_fields") or [])
        evidence_gates = list(
            schema.get("detached_verification_acceptance_gates") or []
        )
        result = str(intake.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("authorization_signed_receipt_evidence_intake_ready_count")
            or 0
        )
        check_count = int(summary.get("signed_receipt_evidence_intake_check_count") or 0)
        pass_count = int(summary.get("signed_receipt_evidence_intake_pass_count") or 0)
        waiting_count = int(
            summary.get("signed_receipt_evidence_intake_waiting_count") or 0
        )
        closeout_ready_count = int(
            summary.get("authorization_signed_receipt_closeout_ready_count") or 0
        )
        closeout_check_count = int(summary.get("signed_receipt_closeout_check_count") or 0)
        preflight_ready_count = int(
            summary.get("authorization_signed_receipt_preflight_ready_count") or 0
        )
        preflight_check_count = int(summary.get("signed_receipt_preflight_check_count") or 0)
        evidence_boundary_count = int(
            summary.get("external_signing_receipt_evidence_boundary_count") or 0
        )
        detached_boundary_count = int(
            summary.get("detached_receipt_verification_boundary_count") or 0
        )
        schema_count = int(summary.get("detached_verification_evidence_schema_count") or 0)
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        acceptance_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        detached_check_count = int(
            summary.get("detached_receipt_verification_check_count") or 0
        )
        evidence_field_count = int(
            summary.get("detached_verification_evidence_field_count") or 0
        )
        evidence_acceptance_gate_count = int(
            summary.get("detached_verification_acceptance_gate_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        rollback_boundary_count = int(summary.get("rollback_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_receipt") is not False,
                safety.get("updates_mapping") is not False,
                safety.get("dispatches_telegram") is not False,
                safety.get("llm_calls_in_gate") is not False,
                future_intake.get("ready_for_database_apply_now") is not False,
                future_intake.get("issues_database_apply_authorization") is not False,
                future_intake.get("signs_database_apply_authorization") is not False,
                future_intake.get("detached_signature_verification_performed")
                is not False,
                future_intake.get("external_signed_authorization_receipt_included")
                is not False,
                future_intake.get("signed_authorization_receipt_included") is not False,
                future_intake.get("signature_material_included") is not False,
                future_intake.get("secret_material_included") is not False,
                future_intake.get("secret_material_required_in_preview") is not False,
                future_intake.get("reads_secret_in_preview") is not False,
                schema.get("detached_signature_verification_performed") is not False,
                schema.get("external_signed_authorization_receipt_included") is not False,
                schema.get("signed_authorization_receipt_included") is not False,
                schema.get("signature_material_included") is not False,
                schema.get("secret_material_included") is not False,
                schema.get("secret_material_required_in_preview") is not False,
                schema.get("accepts_plaintext_secret") is not False,
                schema.get("reads_secret_in_preview") is not False,
                schema.get("executes_shell_in_preview") is not False,
                schema.get("executes_sql_in_preview") is not False,
                schema.get("writes_database_in_preview") is not False,
                schema.get("ready_for_database_apply_now") is not False,
                schema.get("issues_database_apply_authorization") is not False,
                schema.get("signs_database_apply_authorization") is not False,
                operator_boundary.get("secret_material_included") is not False,
                operator_boundary.get("secret_material_required_in_preview") is not False,
                operator_boundary.get("reads_secret_in_preview") is not False,
                operator_boundary.get("accepts_plaintext_secret") is not False,
                operator_boundary.get("permits_secret_value_logging") is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("detached_signature_verification_performed") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        intake_contract_present = (
            ready_count == 1
            and closeout_ready_count == 1
            and preflight_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and closeout_check_count == 12
            and preflight_check_count == 12
            and evidence_boundary_count == 1
            and detached_boundary_count == 1
            and schema_count == 1
            and required_evidence_count == 10
            and acceptance_gate_count == 8
            and detached_check_count == 10
            and evidence_field_count == 12
            and evidence_acceptance_gate_count == 10
            and secret_boundary_count == 1
            and rollback_boundary_count == 4
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_intake.get(
                "ready_for_future_signed_authorization_receipt_evidence_intake"
            )
            is True
            and future_intake.get(
                "can_enter_future_detached_verification_evidence_validation"
            )
            is True
            and future_intake.get(
                "external_signed_authorization_receipt_evidence_schema_ready"
            )
            is True
            and schema.get("authorization_material_type")
            == "detached_verification_evidence_schema"
            and schema.get("ready_for_future_detached_verification_evidence_schema")
            is True
            and "verifier_receipt_sha256" in evidence_fields
            and "detached_signature_verification_status_is_passed" in evidence_gates
            and schema.get("requires_detached_signature_verification") is True
            and schema.get("detached_signature_verification_performed") is False
            and schema.get("external_signed_authorization_receipt_required_in_future")
            is True
            and schema.get("external_signed_authorization_receipt_included") is False
            and schema.get("signed_authorization_receipt_included") is False
            and schema.get("signature_material_included") is False
            and schema.get("signer_key_id_reference_only") is True
            and schema.get("signature_algorithm_reference_only") is True
            and schema.get("accepts_plaintext_secret") is False
            and schema.get("hash_matches") is True
            and schema.get("requires_post_apply_verifier") is True
            and schema.get("requires_fresh_production_truth_in_same_run") is True
            and operator_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_detached_verification_evidence_validation")
            is True
            and contract.get("accepts_plaintext_secret") is False
            and contract.get("detached_signature_verification_performed") is False
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy signed receipt evidence intake 偵測到 secret、"
                "signed material、verification execution、SQL、DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_signed_receipt_evidence_intake_and_inspect_risk"
            )
        elif intake_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy signed receipt evidence intake 已自動完成 "
                f"{pass_count}/{check_count} checks，detached evidence schema 已綁定，signed receipt payload=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_detached_verification_evidence_validation_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy signed receipt evidence intake 尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_signed_receipt_evidence_intake"
            )

        return _check(
            "PChome auto-policy signed receipt evidence intake",
            status,
            summary_text,
            {
                "policy": intake.get("policy"),
                "result": result,
                "source_policy": intake.get("source_policy"),
                "signed_receipt_evidence_intake_ready_count": ready_count,
                "signed_receipt_evidence_intake_check_count": check_count,
                "signed_receipt_evidence_intake_pass_count": pass_count,
                "signed_receipt_evidence_intake_waiting_count": waiting_count,
                "signed_receipt_closeout_ready_count": closeout_ready_count,
                "signed_receipt_closeout_check_count": closeout_check_count,
                "signed_receipt_preflight_ready_count": preflight_ready_count,
                "signed_receipt_preflight_check_count": preflight_check_count,
                "external_signing_receipt_evidence_boundary_count": (
                    evidence_boundary_count
                ),
                "detached_receipt_verification_boundary_count": detached_boundary_count,
                "detached_verification_evidence_schema_count": schema_count,
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": acceptance_gate_count,
                "detached_receipt_verification_check_count": detached_check_count,
                "detached_verification_evidence_field_count": evidence_field_count,
                "detached_verification_acceptance_gate_count": (
                    evidence_acceptance_gate_count
                ),
                "operator_held_secret_boundary_count": secret_boundary_count,
                "rollback_boundary_count": rollback_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": operator_boundary.get("secret_reference_mode"),
                "requires_detached_signature_verification": bool(
                    schema.get("requires_detached_signature_verification")
                ),
                "detached_signature_verification_performed": bool(
                    schema.get("detached_signature_verification_performed")
                    or future_intake.get("detached_signature_verification_performed")
                    or safety.get("performs_detached_signature_verification")
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    schema.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    future_intake.get(
                        "external_signed_authorization_receipt_included"
                    )
                    or schema.get("external_signed_authorization_receipt_included")
                ),
                "signed_authorization_receipt_included": bool(
                    future_intake.get("signed_authorization_receipt_included")
                    or schema.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    future_intake.get("signature_material_included")
                    or schema.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    schema.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    schema.get("signature_algorithm_reference_only")
                ),
                "ready_for_database_apply_now": bool(
                    future_intake.get("ready_for_database_apply_now")
                    or schema.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_intake.get("issues_database_apply_authorization")
                    or schema.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_intake.get("signs_database_apply_authorization")
                    or schema.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_intake.get("secret_material_included")
                    or schema.get("secret_material_included")
                    or operator_boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_intake.get("secret_material_required_in_preview")
                    or schema.get("secret_material_required_in_preview")
                    or operator_boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "accepts_plaintext_secret": bool(
                    schema.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                    or operator_boundary.get("accepts_plaintext_secret")
                ),
                "ready_for_future_signed_authorization_receipt_evidence_intake": bool(
                    future_intake.get(
                        "ready_for_future_signed_authorization_receipt_evidence_intake"
                    )
                ),
                "can_enter_future_detached_verification_evidence_validation": bool(
                    future_intake.get(
                        "can_enter_future_detached_verification_evidence_validation"
                    )
                ),
                "external_signed_authorization_receipt_evidence_schema_ready": bool(
                    future_intake.get(
                        "external_signed_authorization_receipt_evidence_schema_ready"
                    )
                ),
                "ready_for_future_detached_verification_evidence_schema": bool(
                    schema.get("ready_for_future_detached_verification_evidence_schema")
                ),
                "permits_future_detached_verification_evidence_validation": bool(
                    contract.get(
                        "permits_future_detached_verification_evidence_validation"
                    )
                ),
                "performs_detached_signature_verification": bool(
                    safety.get("performs_detached_signature_verification")
                ),
                "requires_post_apply_verifier": bool(
                    schema.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    schema.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy signed receipt evidence intake",
            "warning",
            (
                "PChome auto-policy signed receipt evidence intake "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_signed_receipt_evidence_intake"
                ),
            },
        )


def _pchome_auto_policy_detached_verification_evidence_validation_check() -> Dict[str, Any]:
    """Read-only monitor for the future verifier receipt closeout boundary."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        validation = (
            backlog.build_pchome_auto_policy_db_apply_authorization_detached_verification_evidence_validation(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = validation.get("summary") or {}
        future_validation = (
            validation.get("future_detached_verification_evidence_validation") or {}
        )
        boundary = validation.get("verifier_receipt_closeout_boundary") or {}
        operator_boundary = (
            boundary.get("operator_held_secret_boundary_contract") or {}
        )
        contract = (
            validation.get("detached_verification_evidence_validation_contract") or {}
        )
        safety = validation.get("safety") or {}
        verifier_fields = list(boundary.get("verifier_receipt_fields") or [])
        verifier_gates = list(boundary.get("verifier_receipt_acceptance_gates") or [])
        result = str(validation.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get(
                "authorization_detached_verification_evidence_validation_ready_count"
            )
            or 0
        )
        check_count = int(
            summary.get("detached_verification_evidence_validation_check_count") or 0
        )
        pass_count = int(
            summary.get("detached_verification_evidence_validation_pass_count") or 0
        )
        waiting_count = int(
            summary.get("detached_verification_evidence_validation_waiting_count") or 0
        )
        intake_ready_count = int(
            summary.get("authorization_signed_receipt_evidence_intake_ready_count") or 0
        )
        intake_check_count = int(
            summary.get("signed_receipt_evidence_intake_check_count") or 0
        )
        closeout_check_count = int(summary.get("signed_receipt_closeout_check_count") or 0)
        schema_count = int(summary.get("detached_verification_evidence_schema_count") or 0)
        verifier_boundary_count = int(
            summary.get("verifier_receipt_closeout_boundary_count") or 0
        )
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        acceptance_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        detached_check_count = int(
            summary.get("detached_receipt_verification_check_count") or 0
        )
        evidence_field_count = int(
            summary.get("detached_verification_evidence_field_count") or 0
        )
        evidence_acceptance_gate_count = int(
            summary.get("detached_verification_acceptance_gate_count") or 0
        )
        verifier_field_count = int(summary.get("verifier_receipt_field_count") or 0)
        verifier_acceptance_gate_count = int(
            summary.get("verifier_receipt_acceptance_gate_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("updates_mapping") is not False,
                safety.get("dispatches_telegram") is not False,
                safety.get("llm_calls_in_gate") is not False,
                future_validation.get("ready_for_database_apply_now") is not False,
                future_validation.get("issues_database_apply_authorization") is not False,
                future_validation.get("signs_database_apply_authorization") is not False,
                future_validation.get("detached_signature_verification_performed")
                is not False,
                future_validation.get("verifier_receipt_persisted") is not False,
                future_validation.get("external_signed_authorization_receipt_included")
                is not False,
                future_validation.get("signed_authorization_receipt_included") is not False,
                future_validation.get("signature_material_included") is not False,
                future_validation.get("secret_material_included") is not False,
                future_validation.get("secret_material_required_in_preview") is not False,
                future_validation.get("reads_secret_in_preview") is not False,
                boundary.get("detached_signature_verification_performed") is not False,
                boundary.get("verifier_receipt_persisted") is not False,
                boundary.get("external_signed_authorization_receipt_included") is not False,
                boundary.get("signed_authorization_receipt_included") is not False,
                boundary.get("signature_material_included") is not False,
                boundary.get("secret_material_included") is not False,
                boundary.get("secret_material_required_in_preview") is not False,
                boundary.get("accepts_plaintext_secret") is not False,
                boundary.get("reads_secret_in_preview") is not False,
                boundary.get("executes_shell_in_preview") is not False,
                boundary.get("executes_sql_in_preview") is not False,
                boundary.get("writes_database_in_preview") is not False,
                boundary.get("ready_for_database_apply_now") is not False,
                boundary.get("issues_database_apply_authorization") is not False,
                boundary.get("signs_database_apply_authorization") is not False,
                operator_boundary.get("secret_material_included") is not False,
                operator_boundary.get("secret_material_required_in_preview") is not False,
                operator_boundary.get("reads_secret_in_preview") is not False,
                operator_boundary.get("accepts_plaintext_secret") is not False,
                operator_boundary.get("permits_secret_value_logging") is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        validation_contract_present = (
            ready_count == 1
            and intake_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and intake_check_count == 12
            and closeout_check_count == 12
            and schema_count == 1
            and verifier_boundary_count == 1
            and required_evidence_count == 10
            and acceptance_gate_count == 8
            and detached_check_count == 10
            and evidence_field_count == 12
            and evidence_acceptance_gate_count == 10
            and verifier_field_count == 12
            and verifier_acceptance_gate_count == 10
            and "verifier_receipt_sha256" in verifier_fields
            and "detached_signature_verification_status_passed" in verifier_gates
            and secret_boundary_count == 1
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_validation.get(
                "ready_for_future_detached_verification_evidence_validation"
            )
            is True
            and future_validation.get("can_enter_future_verifier_receipt_closeout")
            is True
            and future_validation.get("verifier_receipt_closeout_boundary_ready")
            is True
            and boundary.get("authorization_material_type")
            == "verifier_receipt_closeout_boundary"
            and boundary.get("ready_for_future_verifier_receipt_closeout_boundary")
            is True
            and boundary.get("requires_detached_signature_verification") is True
            and boundary.get("detached_signature_verification_performed") is False
            and boundary.get("verifier_receipt_persisted") is False
            and boundary.get("external_signed_authorization_receipt_required_in_future")
            is True
            and boundary.get("external_signed_authorization_receipt_included") is False
            and boundary.get("signed_authorization_receipt_included") is False
            and boundary.get("signature_material_included") is False
            and boundary.get("signer_key_id_reference_only") is True
            and boundary.get("signature_algorithm_reference_only") is True
            and boundary.get("accepts_plaintext_secret") is False
            and boundary.get("hash_matches") is True
            and boundary.get("requires_post_apply_verifier") is True
            and boundary.get("requires_fresh_production_truth_in_same_run") is True
            and operator_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_verifier_receipt_closeout") is True
            and contract.get("accepts_plaintext_secret") is False
            and contract.get("performs_detached_signature_verification") is False
            and contract.get("persists_verifier_receipt") is False
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy detached verification evidence validation "
                "偵測到 secret、signed material、verification execution、verifier receipt persist、SQL、DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_detached_verification_evidence_validation_and_inspect_risk"
            )
        elif validation_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy detached verification evidence validation 已自動完成 "
                f"{pass_count}/{check_count} checks，verifier receipt closeout boundary 已綁定，verification/persist=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_verifier_receipt_closeout_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy detached verification evidence validation 尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_detached_verification_evidence_validation"
            )

        return _check(
            "PChome auto-policy detached verification evidence validation",
            status,
            summary_text,
            {
                "policy": validation.get("policy"),
                "result": result,
                "source_policy": validation.get("source_policy"),
                "detached_verification_evidence_validation_ready_count": ready_count,
                "detached_verification_evidence_validation_check_count": check_count,
                "detached_verification_evidence_validation_pass_count": pass_count,
                "detached_verification_evidence_validation_waiting_count": waiting_count,
                "signed_receipt_evidence_intake_ready_count": intake_ready_count,
                "signed_receipt_evidence_intake_check_count": intake_check_count,
                "signed_receipt_closeout_check_count": closeout_check_count,
                "detached_verification_evidence_schema_count": schema_count,
                "verifier_receipt_closeout_boundary_count": verifier_boundary_count,
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": acceptance_gate_count,
                "detached_receipt_verification_check_count": detached_check_count,
                "detached_verification_evidence_field_count": evidence_field_count,
                "detached_verification_acceptance_gate_count": (
                    evidence_acceptance_gate_count
                ),
                "verifier_receipt_field_count": verifier_field_count,
                "verifier_receipt_acceptance_gate_count": (
                    verifier_acceptance_gate_count
                ),
                "operator_held_secret_boundary_count": secret_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": operator_boundary.get("secret_reference_mode"),
                "requires_detached_signature_verification": bool(
                    boundary.get("requires_detached_signature_verification")
                ),
                "detached_signature_verification_performed": bool(
                    future_validation.get("detached_signature_verification_performed")
                    or boundary.get("detached_signature_verification_performed")
                    or safety.get("performs_detached_signature_verification")
                ),
                "verifier_receipt_persisted": bool(
                    future_validation.get("verifier_receipt_persisted")
                    or boundary.get("verifier_receipt_persisted")
                    or safety.get("persists_verifier_receipt")
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    boundary.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    future_validation.get(
                        "external_signed_authorization_receipt_included"
                    )
                    or boundary.get("external_signed_authorization_receipt_included")
                ),
                "signed_authorization_receipt_included": bool(
                    future_validation.get("signed_authorization_receipt_included")
                    or boundary.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    future_validation.get("signature_material_included")
                    or boundary.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    boundary.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    boundary.get("signature_algorithm_reference_only")
                ),
                "ready_for_database_apply_now": bool(
                    future_validation.get("ready_for_database_apply_now")
                    or boundary.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_validation.get("issues_database_apply_authorization")
                    or boundary.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_validation.get("signs_database_apply_authorization")
                    or boundary.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_validation.get("secret_material_included")
                    or boundary.get("secret_material_included")
                    or operator_boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_validation.get("secret_material_required_in_preview")
                    or boundary.get("secret_material_required_in_preview")
                    or operator_boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "accepts_plaintext_secret": bool(
                    boundary.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                    or operator_boundary.get("accepts_plaintext_secret")
                ),
                "ready_for_future_detached_verification_evidence_validation": bool(
                    future_validation.get(
                        "ready_for_future_detached_verification_evidence_validation"
                    )
                ),
                "can_enter_future_verifier_receipt_closeout": bool(
                    future_validation.get("can_enter_future_verifier_receipt_closeout")
                ),
                "verifier_receipt_closeout_boundary_ready": bool(
                    future_validation.get("verifier_receipt_closeout_boundary_ready")
                ),
                "ready_for_future_verifier_receipt_closeout_boundary": bool(
                    boundary.get("ready_for_future_verifier_receipt_closeout_boundary")
                ),
                "permits_future_verifier_receipt_closeout": bool(
                    contract.get("permits_future_verifier_receipt_closeout")
                ),
                "persists_verifier_receipt": bool(
                    contract.get("persists_verifier_receipt")
                    or safety.get("persists_verifier_receipt")
                ),
                "performs_detached_signature_verification": bool(
                    contract.get("performs_detached_signature_verification")
                    or safety.get("performs_detached_signature_verification")
                ),
                "requires_post_apply_verifier": bool(
                    boundary.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    boundary.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy detached verification evidence validation",
            "warning",
            (
                "PChome auto-policy detached verification evidence validation "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_detached_verification_evidence_validation"
                ),
            },
        )


def _pchome_auto_policy_verifier_receipt_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the future database apply verifier handoff."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_authorization_verifier_receipt_closeout(
                payload,
                batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        future_closeout = closeout.get("future_verifier_receipt_closeout") or {}
        handoff = closeout.get("verifier_receipt_evidence_handoff") or {}
        operator_boundary = handoff.get("operator_held_secret_boundary_contract") or {}
        contract = closeout.get("verifier_receipt_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        handoff_fields = list(handoff.get("verifier_receipt_evidence_handoff_fields") or [])
        handoff_gates = list(
            handoff.get("verifier_receipt_handoff_acceptance_gates") or []
        )
        result = str(closeout.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("authorization_verifier_receipt_closeout_ready_count") or 0
        )
        check_count = int(summary.get("verifier_receipt_closeout_check_count") or 0)
        pass_count = int(summary.get("verifier_receipt_closeout_pass_count") or 0)
        waiting_count = int(summary.get("verifier_receipt_closeout_waiting_count") or 0)
        validation_ready_count = int(
            summary.get("authorization_detached_verification_evidence_validation_ready_count")
            or 0
        )
        validation_check_count = int(
            summary.get("detached_verification_evidence_validation_check_count") or 0
        )
        intake_ready_count = int(
            summary.get("authorization_signed_receipt_evidence_intake_ready_count") or 0
        )
        intake_check_count = int(
            summary.get("signed_receipt_evidence_intake_check_count") or 0
        )
        boundary_count = int(summary.get("verifier_receipt_closeout_boundary_count") or 0)
        handoff_count = int(summary.get("verifier_receipt_evidence_handoff_count") or 0)
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        acceptance_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        verifier_field_count = int(summary.get("verifier_receipt_field_count") or 0)
        verifier_acceptance_gate_count = int(
            summary.get("verifier_receipt_acceptance_gate_count") or 0
        )
        handoff_field_count = int(
            summary.get("verifier_receipt_evidence_handoff_field_count") or 0
        )
        handoff_acceptance_gate_count = int(
            summary.get("verifier_receipt_handoff_acceptance_gate_count") or 0
        )
        evidence_field_count = int(
            summary.get("detached_verification_evidence_field_count") or 0
        )
        evidence_acceptance_gate_count = int(
            summary.get("detached_verification_acceptance_gate_count") or 0
        )
        secret_boundary_count = int(summary.get("operator_held_secret_boundary_count") or 0)
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("updates_mapping") is not False,
                safety.get("dispatches_telegram") is not False,
                safety.get("llm_calls_in_gate") is not False,
                future_closeout.get("ready_for_database_apply_now") is not False,
                future_closeout.get("issues_database_apply_authorization") is not False,
                future_closeout.get("signs_database_apply_authorization") is not False,
                future_closeout.get("detached_signature_verification_performed")
                is not False,
                future_closeout.get("verifier_receipt_persisted") is not False,
                future_closeout.get("external_signed_authorization_receipt_included")
                is not False,
                future_closeout.get("signed_authorization_receipt_included") is not False,
                future_closeout.get("signature_material_included") is not False,
                future_closeout.get("secret_material_included") is not False,
                future_closeout.get("secret_material_required_in_preview") is not False,
                future_closeout.get("reads_secret_in_preview") is not False,
                handoff.get("detached_signature_verification_performed") is not False,
                handoff.get("verifier_receipt_persisted") is not False,
                handoff.get("external_signed_authorization_receipt_included") is not False,
                handoff.get("signed_authorization_receipt_included") is not False,
                handoff.get("signature_material_included") is not False,
                handoff.get("secret_material_included") is not False,
                handoff.get("secret_material_required_in_preview") is not False,
                handoff.get("accepts_plaintext_secret") is not False,
                handoff.get("reads_secret_in_preview") is not False,
                handoff.get("executes_shell_in_preview") is not False,
                handoff.get("executes_sql_in_preview") is not False,
                handoff.get("writes_database_in_preview") is not False,
                handoff.get("ready_for_database_apply_now") is not False,
                handoff.get("issues_database_apply_authorization") is not False,
                handoff.get("signs_database_apply_authorization") is not False,
                operator_boundary.get("secret_material_included") is not False,
                operator_boundary.get("secret_material_required_in_preview") is not False,
                operator_boundary.get("reads_secret_in_preview") is not False,
                operator_boundary.get("accepts_plaintext_secret") is not False,
                operator_boundary.get("permits_secret_value_logging") is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            ready_count == 1
            and validation_ready_count == 1
            and intake_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and validation_check_count == 12
            and intake_check_count == 12
            and boundary_count == 1
            and handoff_count == 1
            and required_evidence_count == 10
            and acceptance_gate_count == 8
            and verifier_field_count == 12
            and verifier_acceptance_gate_count == 10
            and handoff_field_count == 12
            and handoff_acceptance_gate_count == 10
            and evidence_field_count == 12
            and evidence_acceptance_gate_count == 10
            and "verifier_receipt_sha256" in handoff_fields
            and "verifier_receipt_not_persisted_by_preview" in handoff_gates
            and secret_boundary_count == 1
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_closeout.get("ready_for_future_verifier_receipt_closeout")
            is True
            and future_closeout.get(
                "can_enter_future_database_apply_authorization_verifier_handoff"
            )
            is True
            and future_closeout.get("verifier_receipt_evidence_handoff_ready")
            is True
            and handoff.get("authorization_material_type")
            == "verifier_receipt_evidence_handoff"
            and handoff.get("ready_for_future_verifier_receipt_evidence_handoff")
            is True
            and handoff.get("requires_detached_signature_verification") is True
            and handoff.get("detached_signature_verification_performed") is False
            and handoff.get("verifier_receipt_persisted") is False
            and handoff.get("external_signed_authorization_receipt_required_in_future")
            is True
            and handoff.get("external_signed_authorization_receipt_included") is False
            and handoff.get("signed_authorization_receipt_included") is False
            and handoff.get("signature_material_included") is False
            and handoff.get("signer_key_id_reference_only") is True
            and handoff.get("signature_algorithm_reference_only") is True
            and handoff.get("accepts_plaintext_secret") is False
            and handoff.get("hash_matches") is True
            and handoff.get("requires_post_apply_verifier") is True
            and handoff.get("requires_fresh_production_truth_in_same_run") is True
            and operator_boundary.get("secret_reference_mode")
            == "external_runtime_reference_only"
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_database_apply_authorization_verifier_handoff"
            )
            is True
            and contract.get("accepts_plaintext_secret") is False
            and contract.get("performs_detached_signature_verification") is False
            and contract.get("persists_verifier_receipt") is False
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy verifier receipt closeout 偵測到 secret、"
                "signed material、verification execution、verifier receipt persist、SQL、DB write、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_verifier_receipt_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy verifier receipt closeout 已自動完成 "
                f"{pass_count}/{check_count} checks，verifier handoff 已綁定，verification/persist=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_database_apply_authorization_verifier_handoff_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy verifier receipt closeout 尚未達自動監控契約"
            )
            next_machine_action = "refresh_pchome_auto_policy_verifier_receipt_closeout"

        return _check(
            "PChome auto-policy verifier receipt closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "verifier_receipt_closeout_ready_count": ready_count,
                "verifier_receipt_closeout_check_count": check_count,
                "verifier_receipt_closeout_pass_count": pass_count,
                "verifier_receipt_closeout_waiting_count": waiting_count,
                "detached_verification_evidence_validation_ready_count": (
                    validation_ready_count
                ),
                "detached_verification_evidence_validation_check_count": (
                    validation_check_count
                ),
                "signed_receipt_evidence_intake_ready_count": intake_ready_count,
                "signed_receipt_evidence_intake_check_count": intake_check_count,
                "verifier_receipt_closeout_boundary_count": boundary_count,
                "verifier_receipt_evidence_handoff_count": handoff_count,
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": acceptance_gate_count,
                "verifier_receipt_field_count": verifier_field_count,
                "verifier_receipt_acceptance_gate_count": verifier_acceptance_gate_count,
                "verifier_receipt_evidence_handoff_field_count": handoff_field_count,
                "verifier_receipt_handoff_acceptance_gate_count": (
                    handoff_acceptance_gate_count
                ),
                "detached_verification_evidence_field_count": evidence_field_count,
                "detached_verification_acceptance_gate_count": (
                    evidence_acceptance_gate_count
                ),
                "operator_held_secret_boundary_count": secret_boundary_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "secret_reference_mode": operator_boundary.get("secret_reference_mode"),
                "requires_detached_signature_verification": bool(
                    handoff.get("requires_detached_signature_verification")
                ),
                "detached_signature_verification_performed": bool(
                    future_closeout.get("detached_signature_verification_performed")
                    or handoff.get("detached_signature_verification_performed")
                    or safety.get("performs_detached_signature_verification")
                ),
                "verifier_receipt_persisted": bool(
                    future_closeout.get("verifier_receipt_persisted")
                    or handoff.get("verifier_receipt_persisted")
                    or safety.get("persists_verifier_receipt")
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    handoff.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    future_closeout.get(
                        "external_signed_authorization_receipt_included"
                    )
                    or handoff.get("external_signed_authorization_receipt_included")
                ),
                "signed_authorization_receipt_included": bool(
                    future_closeout.get("signed_authorization_receipt_included")
                    or handoff.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    future_closeout.get("signature_material_included")
                    or handoff.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    handoff.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    handoff.get("signature_algorithm_reference_only")
                ),
                "ready_for_database_apply_now": bool(
                    future_closeout.get("ready_for_database_apply_now")
                    or handoff.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    future_closeout.get("issues_database_apply_authorization")
                    or handoff.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_closeout.get("signs_database_apply_authorization")
                    or handoff.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "secret_material_included": bool(
                    future_closeout.get("secret_material_included")
                    or handoff.get("secret_material_included")
                    or operator_boundary.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    future_closeout.get("secret_material_required_in_preview")
                    or handoff.get("secret_material_required_in_preview")
                    or operator_boundary.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "accepts_plaintext_secret": bool(
                    handoff.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                    or operator_boundary.get("accepts_plaintext_secret")
                ),
                "ready_for_future_verifier_receipt_closeout": bool(
                    future_closeout.get("ready_for_future_verifier_receipt_closeout")
                ),
                "can_enter_future_database_apply_authorization_verifier_handoff": bool(
                    future_closeout.get(
                        "can_enter_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "verifier_receipt_evidence_handoff_ready": bool(
                    future_closeout.get("verifier_receipt_evidence_handoff_ready")
                ),
                "ready_for_future_verifier_receipt_evidence_handoff": bool(
                    handoff.get("ready_for_future_verifier_receipt_evidence_handoff")
                ),
                "permits_future_database_apply_authorization_verifier_handoff": bool(
                    contract.get(
                        "permits_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "persists_verifier_receipt": bool(
                    contract.get("persists_verifier_receipt")
                    or safety.get("persists_verifier_receipt")
                ),
                "performs_detached_signature_verification": bool(
                    contract.get("performs_detached_signature_verification")
                    or safety.get("performs_detached_signature_verification")
                ),
                "requires_post_apply_verifier": bool(
                    handoff.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    handoff.get("requires_fresh_production_truth_in_same_run")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy verifier receipt closeout",
            "warning",
            f"PChome auto-policy verifier receipt closeout 例行監控暫時無法讀取：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_verifier_receipt_closeout"
                ),
            },
        )


def _pchome_auto_policy_authorization_evidence_execution_preflight_check() -> Dict[str, Any]:
    """Read-only monitor for the future authorization evidence execution preflight."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        preflight = (
            backlog.build_pchome_auto_policy_db_apply_authorization_evidence_execution_preflight(
                payload,
                batch_size=max(
                    1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)
                ),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = preflight.get("summary") or {}
        verifier_handoff = (
            preflight.get("future_database_apply_authorization_verifier_handoff")
            or {}
        )
        execution_preflight = (
            preflight.get("authorization_evidence_execution_preflight") or {}
        )
        contract = (
            preflight.get("authorization_evidence_execution_preflight_contract")
            or {}
        )
        safety = preflight.get("safety") or {}
        execution_fields = list(
            execution_preflight.get("authorization_evidence_execution_fields") or []
        )
        execution_gates = list(
            execution_preflight.get(
                "authorization_evidence_execution_acceptance_gates"
            )
            or []
        )
        result = str(preflight.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("authorization_evidence_execution_preflight_ready_count")
            or 0
        )
        check_count = int(
            summary.get("authorization_evidence_execution_preflight_check_count")
            or 0
        )
        pass_count = int(
            summary.get("authorization_evidence_execution_preflight_pass_count") or 0
        )
        waiting_count = int(
            summary.get("authorization_evidence_execution_preflight_waiting_count")
            or 0
        )
        closeout_ready_count = int(
            summary.get("authorization_verifier_receipt_closeout_ready_count") or 0
        )
        closeout_check_count = int(
            summary.get("verifier_receipt_closeout_check_count") or 0
        )
        detached_validation_ready_count = int(
            summary.get(
                "authorization_detached_verification_evidence_validation_ready_count"
            )
            or 0
        )
        detached_validation_check_count = int(
            summary.get("detached_verification_evidence_validation_check_count") or 0
        )
        verifier_handoff_count = int(
            summary.get("verifier_receipt_evidence_handoff_count") or 0
        )
        execution_preflight_count = int(
            summary.get("authorization_evidence_execution_preflight_count") or 0
        )
        execution_field_count = int(
            summary.get("authorization_evidence_execution_field_count") or 0
        )
        execution_gate_count = int(
            summary.get("authorization_evidence_execution_acceptance_gate_count") or 0
        )
        verifier_field_count = int(summary.get("verifier_receipt_field_count") or 0)
        verifier_acceptance_gate_count = int(
            summary.get("verifier_receipt_acceptance_gate_count") or 0
        )
        handoff_field_count = int(
            summary.get("verifier_receipt_evidence_handoff_field_count") or 0
        )
        handoff_acceptance_gate_count = int(
            summary.get("verifier_receipt_handoff_acceptance_gate_count") or 0
        )
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        external_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        verifier_required_count = int(summary.get("post_apply_verifier_required_count") or 0)
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(
            summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0
        )
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("executes_authorization_evidence") is not False,
                verifier_handoff.get("ready_for_database_apply_now") is not False,
                verifier_handoff.get("issues_database_apply_authorization") is not False,
                verifier_handoff.get("signs_database_apply_authorization") is not False,
                verifier_handoff.get("executes_authorization_evidence") is not False,
                verifier_handoff.get("detached_signature_verification_performed")
                is not False,
                verifier_handoff.get("verifier_receipt_persisted") is not False,
                verifier_handoff.get("external_signed_authorization_receipt_included")
                is not False,
                verifier_handoff.get("signed_authorization_receipt_included") is not False,
                verifier_handoff.get("signature_material_included") is not False,
                verifier_handoff.get("secret_material_included") is not False,
                verifier_handoff.get("secret_material_required_in_preview") is not False,
                verifier_handoff.get("reads_secret_in_preview") is not False,
                execution_preflight.get("detached_signature_verification_performed")
                is not False,
                execution_preflight.get("verifier_receipt_persisted") is not False,
                execution_preflight.get("external_signed_authorization_receipt_included")
                is not False,
                execution_preflight.get("signed_authorization_receipt_included")
                is not False,
                execution_preflight.get("signature_material_included") is not False,
                execution_preflight.get("secret_material_included") is not False,
                execution_preflight.get("secret_material_required_in_preview")
                is not False,
                execution_preflight.get("accepts_plaintext_secret") is not False,
                execution_preflight.get("reads_secret_in_preview") is not False,
                execution_preflight.get("executes_shell_in_preview") is not False,
                execution_preflight.get("executes_sql_in_preview") is not False,
                execution_preflight.get("writes_database_in_preview") is not False,
                execution_preflight.get("executes_authorization_evidence") is not False,
                execution_preflight.get("ready_for_database_apply_now") is not False,
                execution_preflight.get("issues_database_apply_authorization") is not False,
                execution_preflight.get("signs_database_apply_authorization")
                is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("executes_authorization_evidence") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        preflight_contract_present = (
            result == "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_READY"
            and ready_count == 1
            and closeout_ready_count == 1
            and detached_validation_ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and closeout_check_count == 12
            and detached_validation_check_count == 12
            and verifier_handoff_count == 1
            and execution_preflight_count == 1
            and execution_field_count == 12
            and execution_gate_count == 10
            and verifier_field_count == 12
            and verifier_acceptance_gate_count == 10
            and handoff_field_count == 12
            and handoff_acceptance_gate_count == 10
            and required_evidence_count == 10
            and external_gate_count == 8
            and "verifier_receipt_sha256" in execution_fields
            and "no_secret_signature_or_database_write_in_preflight" in execution_gates
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and verifier_handoff.get(
                "ready_for_future_database_apply_authorization_verifier_handoff"
            )
            is True
            and verifier_handoff.get(
                "can_enter_future_authorization_evidence_execution_closeout"
            )
            is True
            and verifier_handoff.get("authorization_evidence_execution_preflight_ready")
            is True
            and execution_preflight.get("authorization_material_type")
            == "authorization_evidence_execution_preflight"
            and execution_preflight.get(
                "ready_for_future_authorization_evidence_execution_preflight"
            )
            is True
            and execution_preflight.get("requires_detached_signature_verification")
            is True
            and execution_preflight.get("detached_signature_verification_performed")
            is False
            and execution_preflight.get("verifier_receipt_persisted") is False
            and execution_preflight.get(
                "external_signed_authorization_receipt_required_in_future"
            )
            is True
            and execution_preflight.get("external_signed_authorization_receipt_included")
            is False
            and execution_preflight.get("signed_authorization_receipt_included")
            is False
            and execution_preflight.get("signature_material_included") is False
            and execution_preflight.get("signer_key_id_reference_only") is True
            and execution_preflight.get("signature_algorithm_reference_only") is True
            and execution_preflight.get("accepts_plaintext_secret") is False
            and execution_preflight.get("hash_matches") is True
            and execution_preflight.get("requires_post_apply_verifier") is True
            and execution_preflight.get(
                "requires_fresh_production_truth_in_same_run"
            )
            is True
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_authorization_evidence_execution_closeout"
            )
            is True
            and contract.get("accepts_plaintext_secret") is False
            and contract.get("performs_detached_signature_verification") is False
            and contract.get("persists_verifier_receipt") is False
            and contract.get("executes_authorization_evidence") is False
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy authorization evidence execution preflight "
                "偵測到 secret、signed material、verification execution、"
                "verifier receipt persist、SQL、DB write、evidence execution、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_authorization_evidence_execution_preflight_and_inspect_risk"
            )
        elif preflight_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy authorization evidence execution preflight "
                f"已自動完成 {pass_count}/{check_count} checks，verifier handoff 已綁定，execution/write/sign=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_authorization_evidence_execution_closeout_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy authorization evidence execution preflight "
                "尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_authorization_evidence_execution_preflight"
            )

        return _check(
            "PChome auto-policy authorization evidence execution preflight",
            status,
            summary_text,
            {
                "policy": preflight.get("policy"),
                "result": result,
                "source_policy": preflight.get("source_policy"),
                "authorization_evidence_execution_preflight_ready_count": ready_count,
                "authorization_evidence_execution_preflight_check_count": check_count,
                "authorization_evidence_execution_preflight_pass_count": pass_count,
                "authorization_evidence_execution_preflight_waiting_count": (
                    waiting_count
                ),
                "authorization_verifier_receipt_closeout_ready_count": (
                    closeout_ready_count
                ),
                "verifier_receipt_closeout_check_count": closeout_check_count,
                "detached_verification_evidence_validation_ready_count": (
                    detached_validation_ready_count
                ),
                "detached_verification_evidence_validation_check_count": (
                    detached_validation_check_count
                ),
                "verifier_receipt_evidence_handoff_count": verifier_handoff_count,
                "authorization_evidence_execution_preflight_count": (
                    execution_preflight_count
                ),
                "authorization_evidence_execution_field_count": execution_field_count,
                "authorization_evidence_execution_acceptance_gate_count": (
                    execution_gate_count
                ),
                "verifier_receipt_field_count": verifier_field_count,
                "verifier_receipt_acceptance_gate_count": (
                    verifier_acceptance_gate_count
                ),
                "verifier_receipt_evidence_handoff_field_count": handoff_field_count,
                "verifier_receipt_handoff_acceptance_gate_count": (
                    handoff_acceptance_gate_count
                ),
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": external_gate_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_future_database_apply_authorization_verifier_handoff": bool(
                    verifier_handoff.get(
                        "ready_for_future_database_apply_authorization_verifier_handoff"
                    )
                ),
                "can_enter_future_authorization_evidence_execution_closeout": bool(
                    verifier_handoff.get(
                        "can_enter_future_authorization_evidence_execution_closeout"
                    )
                ),
                "authorization_evidence_execution_preflight_ready": bool(
                    verifier_handoff.get(
                        "authorization_evidence_execution_preflight_ready"
                    )
                ),
                "ready_for_future_authorization_evidence_execution_preflight": bool(
                    execution_preflight.get(
                        "ready_for_future_authorization_evidence_execution_preflight"
                    )
                ),
                "permits_future_authorization_evidence_execution_closeout": bool(
                    contract.get(
                        "permits_future_authorization_evidence_execution_closeout"
                    )
                ),
                "requires_detached_signature_verification": bool(
                    execution_preflight.get("requires_detached_signature_verification")
                ),
                "detached_signature_verification_performed": bool(
                    verifier_handoff.get("detached_signature_verification_performed")
                    or execution_preflight.get(
                        "detached_signature_verification_performed"
                    )
                    or safety.get("performs_detached_signature_verification")
                ),
                "verifier_receipt_persisted": bool(
                    verifier_handoff.get("verifier_receipt_persisted")
                    or execution_preflight.get("verifier_receipt_persisted")
                    or safety.get("persists_verifier_receipt")
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    execution_preflight.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    verifier_handoff.get(
                        "external_signed_authorization_receipt_included"
                    )
                    or execution_preflight.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    verifier_handoff.get("signed_authorization_receipt_included")
                    or execution_preflight.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    verifier_handoff.get("signature_material_included")
                    or execution_preflight.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    execution_preflight.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    execution_preflight.get("signature_algorithm_reference_only")
                ),
                "secret_material_included": bool(
                    verifier_handoff.get("secret_material_included")
                    or execution_preflight.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    verifier_handoff.get("secret_material_required_in_preview")
                    or execution_preflight.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "accepts_plaintext_secret": bool(
                    execution_preflight.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                ),
                "reads_secret_in_preview": bool(
                    verifier_handoff.get("reads_secret_in_preview")
                    or execution_preflight.get("reads_secret_in_preview")
                    or safety.get("reads_secret_in_preview")
                ),
                "executes_authorization_evidence": bool(
                    verifier_handoff.get("executes_authorization_evidence")
                    or execution_preflight.get("executes_authorization_evidence")
                    or contract.get("executes_authorization_evidence")
                    or safety.get("executes_authorization_evidence")
                ),
                "ready_for_database_apply_now": bool(
                    verifier_handoff.get("ready_for_database_apply_now")
                    or execution_preflight.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "issues_database_apply_authorization": bool(
                    verifier_handoff.get("issues_database_apply_authorization")
                    or execution_preflight.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    verifier_handoff.get("signs_database_apply_authorization")
                    or execution_preflight.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "requires_post_apply_verifier": bool(
                    execution_preflight.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    execution_preflight.get(
                        "requires_fresh_production_truth_in_same_run"
                    )
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy authorization evidence execution preflight",
            "warning",
            (
                "PChome auto-policy authorization evidence execution preflight "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_authorization_evidence_execution_preflight"
                ),
            },
        )


def _pchome_auto_policy_authorization_evidence_execution_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the future authorization evidence execution closeout."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_authorization_evidence_execution_closeout(
                payload,
                batch_size=max(
                    1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)
                ),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        final_gate = (
            closeout.get("future_database_apply_authorization_final_verifier_gate")
            or {}
        )
        evidence_closeout = (
            closeout.get("authorization_evidence_execution_closeout") or {}
        )
        contract = (
            closeout.get("authorization_evidence_execution_closeout_contract") or {}
        )
        safety = closeout.get("safety") or {}
        closeout_fields = list(
            evidence_closeout.get(
                "authorization_evidence_execution_closeout_fields"
            )
            or []
        )
        closeout_gates = list(
            evidence_closeout.get(
                "authorization_evidence_execution_closeout_acceptance_gates"
            )
            or []
        )
        execution_fields = list(
            evidence_closeout.get("authorization_evidence_execution_fields") or []
        )
        result = str(closeout.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("authorization_evidence_execution_closeout_ready_count") or 0
        )
        check_count = int(
            summary.get("authorization_evidence_execution_closeout_check_count") or 0
        )
        pass_count = int(
            summary.get("authorization_evidence_execution_closeout_pass_count") or 0
        )
        waiting_count = int(
            summary.get("authorization_evidence_execution_closeout_waiting_count")
            or 0
        )
        preflight_ready_count = int(
            summary.get("authorization_evidence_execution_preflight_ready_count") or 0
        )
        preflight_check_count = int(
            summary.get("authorization_evidence_execution_preflight_check_count") or 0
        )
        closeout_ready_count = int(
            summary.get("authorization_verifier_receipt_closeout_ready_count") or 0
        )
        verifier_closeout_check_count = int(
            summary.get("verifier_receipt_closeout_check_count") or 0
        )
        detached_validation_ready_count = int(
            summary.get(
                "authorization_detached_verification_evidence_validation_ready_count"
            )
            or 0
        )
        detached_validation_check_count = int(
            summary.get("detached_verification_evidence_validation_check_count") or 0
        )
        verifier_handoff_count = int(
            summary.get("verifier_receipt_evidence_handoff_count") or 0
        )
        execution_preflight_count = int(
            summary.get("authorization_evidence_execution_preflight_count") or 0
        )
        evidence_closeout_count = int(
            summary.get("authorization_evidence_execution_closeout_count") or 0
        )
        final_gate_count = int(
            summary.get("database_apply_final_verifier_gate_count") or 0
        )
        final_gate_ready_count = int(
            summary.get("database_apply_authorization_final_verifier_gate_ready_count")
            or 0
        )
        closeout_field_count = int(
            summary.get("authorization_evidence_execution_closeout_field_count") or 0
        )
        closeout_gate_count = int(
            summary.get(
                "authorization_evidence_execution_closeout_acceptance_gate_count"
            )
            or 0
        )
        execution_field_count = int(
            summary.get("authorization_evidence_execution_field_count") or 0
        )
        execution_gate_count = int(
            summary.get("authorization_evidence_execution_acceptance_gate_count") or 0
        )
        verifier_field_count = int(summary.get("verifier_receipt_field_count") or 0)
        verifier_acceptance_gate_count = int(
            summary.get("verifier_receipt_acceptance_gate_count") or 0
        )
        handoff_field_count = int(
            summary.get("verifier_receipt_evidence_handoff_field_count") or 0
        )
        handoff_acceptance_gate_count = int(
            summary.get("verifier_receipt_handoff_acceptance_gate_count") or 0
        )
        required_evidence_count = int(
            summary.get("required_external_receipt_evidence_count") or 0
        )
        external_gate_count = int(
            summary.get("external_receipt_acceptance_gate_count") or 0
        )
        verifier_required_count = int(
            summary.get("post_apply_verifier_required_count") or 0
        )
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(
            summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0
        )
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("executes_authorization_evidence") is not False,
                safety.get("executes_database_apply") is not False,
                final_gate.get("ready_for_database_apply_now") is not False,
                final_gate.get("database_apply_authorized") is not False,
                final_gate.get("issues_database_apply_authorization") is not False,
                final_gate.get("signs_database_apply_authorization") is not False,
                final_gate.get("executes_authorization_evidence") is not False,
                final_gate.get("executes_database_apply") is not False,
                final_gate.get("detached_signature_verification_performed")
                is not False,
                final_gate.get("verifier_receipt_persisted") is not False,
                final_gate.get("external_signed_authorization_receipt_included")
                is not False,
                final_gate.get("signed_authorization_receipt_included") is not False,
                final_gate.get("signature_material_included") is not False,
                final_gate.get("secret_material_included") is not False,
                final_gate.get("secret_material_required_in_preview") is not False,
                final_gate.get("reads_secret_in_preview") is not False,
                evidence_closeout.get("detached_signature_verification_performed")
                is not False,
                evidence_closeout.get("verifier_receipt_persisted") is not False,
                evidence_closeout.get(
                    "external_signed_authorization_receipt_included"
                )
                is not False,
                evidence_closeout.get("signed_authorization_receipt_included")
                is not False,
                evidence_closeout.get("signature_material_included") is not False,
                evidence_closeout.get("secret_material_included") is not False,
                evidence_closeout.get("secret_material_required_in_preview")
                is not False,
                evidence_closeout.get("accepts_plaintext_secret") is not False,
                evidence_closeout.get("reads_secret_in_preview") is not False,
                evidence_closeout.get("executes_shell_in_preview") is not False,
                evidence_closeout.get("executes_endpoint_in_preview") is not False,
                evidence_closeout.get("executes_sql_in_preview") is not False,
                evidence_closeout.get("writes_database_in_preview") is not False,
                evidence_closeout.get("executes_authorization_evidence") is not False,
                evidence_closeout.get("executes_database_apply") is not False,
                evidence_closeout.get("ready_for_database_apply_now") is not False,
                evidence_closeout.get("database_apply_authorized") is not False,
                evidence_closeout.get("issues_database_apply_authorization")
                is not False,
                evidence_closeout.get("signs_database_apply_authorization")
                is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("executes_authorization_evidence") is not False,
                contract.get("executes_database_apply") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("database_apply_authorized") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            result == "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_READY"
            and ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and preflight_ready_count == 1
            and preflight_check_count == 12
            and closeout_ready_count == 1
            and verifier_closeout_check_count == 12
            and detached_validation_ready_count == 1
            and detached_validation_check_count == 12
            and verifier_handoff_count == 1
            and execution_preflight_count == 1
            and evidence_closeout_count == 1
            and final_gate_count == 1
            and final_gate_ready_count == 1
            and closeout_field_count == 12
            and closeout_gate_count == 10
            and execution_field_count == 12
            and execution_gate_count == 10
            and verifier_field_count == 12
            and verifier_acceptance_gate_count == 10
            and handoff_field_count == 12
            and handoff_acceptance_gate_count == 10
            and required_evidence_count == 10
            and external_gate_count == 8
            and "final_verifier_gate_endpoint" in closeout_fields
            and "no_database_apply_authorized_by_closeout" in closeout_gates
            and "verifier_receipt_sha256" in execution_fields
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and final_gate.get(
                "ready_for_future_database_apply_authorization_final_verifier_gate"
            )
            is True
            and final_gate.get(
                "can_enter_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and final_gate.get("authorization_evidence_execution_closeout_ready")
            is True
            and final_gate.get("final_verifier_gate_ready") is True
            and final_gate.get("ready_for_database_apply_now") is False
            and final_gate.get("database_apply_authorized") is False
            and evidence_closeout.get("authorization_material_type")
            == "authorization_evidence_execution_closeout"
            and evidence_closeout.get(
                "ready_for_future_authorization_evidence_execution_closeout"
            )
            is True
            and evidence_closeout.get("requires_detached_signature_verification")
            is True
            and evidence_closeout.get("detached_signature_verification_performed")
            is False
            and evidence_closeout.get("verifier_receipt_persisted") is False
            and evidence_closeout.get(
                "external_signed_authorization_receipt_required_in_future"
            )
            is True
            and evidence_closeout.get("external_signed_authorization_receipt_included")
            is False
            and evidence_closeout.get("signed_authorization_receipt_included")
            is False
            and evidence_closeout.get("signature_material_included") is False
            and evidence_closeout.get("signer_key_id_reference_only") is True
            and evidence_closeout.get("signature_algorithm_reference_only") is True
            and evidence_closeout.get("accepts_plaintext_secret") is False
            and evidence_closeout.get("hash_matches") is True
            and evidence_closeout.get("requires_post_apply_verifier") is True
            and evidence_closeout.get(
                "requires_fresh_production_truth_in_same_run"
            )
            is True
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_database_apply_authorization_final_verifier_gate"
            )
            is True
            and contract.get(
                "permits_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and contract.get("accepts_plaintext_secret") is False
            and contract.get("performs_detached_signature_verification") is False
            and contract.get("persists_verifier_receipt") is False
            and contract.get("executes_authorization_evidence") is False
            and contract.get("executes_database_apply") is False
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy authorization evidence execution closeout "
                "偵測到 secret、signed material、verification execution、"
                "verifier receipt persist、SQL、DB write、database apply、"
                "簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_authorization_evidence_execution_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy authorization evidence execution closeout "
                f"已自動完成 {pass_count}/{check_count} checks，final verifier gate 已綁定，apply/write/sign=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_database_apply_controlled_apply_final_preflight_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy authorization evidence execution closeout "
                "尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_authorization_evidence_execution_closeout"
            )

        return _check(
            "PChome auto-policy authorization evidence execution closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "authorization_evidence_execution_closeout_ready_count": ready_count,
                "authorization_evidence_execution_closeout_check_count": check_count,
                "authorization_evidence_execution_closeout_pass_count": pass_count,
                "authorization_evidence_execution_closeout_waiting_count": (
                    waiting_count
                ),
                "authorization_evidence_execution_preflight_ready_count": (
                    preflight_ready_count
                ),
                "authorization_evidence_execution_preflight_check_count": (
                    preflight_check_count
                ),
                "authorization_verifier_receipt_closeout_ready_count": (
                    closeout_ready_count
                ),
                "verifier_receipt_closeout_check_count": (
                    verifier_closeout_check_count
                ),
                "detached_verification_evidence_validation_ready_count": (
                    detached_validation_ready_count
                ),
                "detached_verification_evidence_validation_check_count": (
                    detached_validation_check_count
                ),
                "verifier_receipt_evidence_handoff_count": verifier_handoff_count,
                "authorization_evidence_execution_preflight_count": (
                    execution_preflight_count
                ),
                "authorization_evidence_execution_closeout_count": (
                    evidence_closeout_count
                ),
                "database_apply_final_verifier_gate_count": final_gate_count,
                "database_apply_authorization_final_verifier_gate_ready_count": (
                    final_gate_ready_count
                ),
                "authorization_evidence_execution_closeout_field_count": (
                    closeout_field_count
                ),
                "authorization_evidence_execution_closeout_acceptance_gate_count": (
                    closeout_gate_count
                ),
                "authorization_evidence_execution_field_count": execution_field_count,
                "authorization_evidence_execution_acceptance_gate_count": (
                    execution_gate_count
                ),
                "verifier_receipt_field_count": verifier_field_count,
                "verifier_receipt_acceptance_gate_count": (
                    verifier_acceptance_gate_count
                ),
                "verifier_receipt_evidence_handoff_field_count": handoff_field_count,
                "verifier_receipt_handoff_acceptance_gate_count": (
                    handoff_acceptance_gate_count
                ),
                "required_external_receipt_evidence_count": required_evidence_count,
                "external_receipt_acceptance_gate_count": external_gate_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_future_database_apply_authorization_final_verifier_gate": bool(
                    final_gate.get(
                        "ready_for_future_database_apply_authorization_final_verifier_gate"
                    )
                ),
                "can_enter_future_database_apply_controlled_apply_final_preflight": bool(
                    final_gate.get(
                        "can_enter_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "authorization_evidence_execution_closeout_ready": bool(
                    final_gate.get("authorization_evidence_execution_closeout_ready")
                ),
                "ready_for_future_authorization_evidence_execution_closeout": bool(
                    evidence_closeout.get(
                        "ready_for_future_authorization_evidence_execution_closeout"
                    )
                ),
                "permits_future_database_apply_authorization_final_verifier_gate": bool(
                    contract.get(
                        "permits_future_database_apply_authorization_final_verifier_gate"
                    )
                ),
                "permits_future_database_apply_controlled_apply_final_preflight": bool(
                    contract.get(
                        "permits_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "requires_detached_signature_verification": bool(
                    evidence_closeout.get("requires_detached_signature_verification")
                ),
                "detached_signature_verification_performed": bool(
                    final_gate.get("detached_signature_verification_performed")
                    or evidence_closeout.get(
                        "detached_signature_verification_performed"
                    )
                    or safety.get("performs_detached_signature_verification")
                ),
                "verifier_receipt_persisted": bool(
                    final_gate.get("verifier_receipt_persisted")
                    or evidence_closeout.get("verifier_receipt_persisted")
                    or safety.get("persists_verifier_receipt")
                ),
                "external_signed_authorization_receipt_required_in_future": bool(
                    evidence_closeout.get(
                        "external_signed_authorization_receipt_required_in_future"
                    )
                ),
                "external_signed_authorization_receipt_included": bool(
                    final_gate.get("external_signed_authorization_receipt_included")
                    or evidence_closeout.get(
                        "external_signed_authorization_receipt_included"
                    )
                ),
                "signed_authorization_receipt_included": bool(
                    final_gate.get("signed_authorization_receipt_included")
                    or evidence_closeout.get("signed_authorization_receipt_included")
                ),
                "signature_material_included": bool(
                    final_gate.get("signature_material_included")
                    or evidence_closeout.get("signature_material_included")
                ),
                "signer_key_id_reference_only": bool(
                    evidence_closeout.get("signer_key_id_reference_only")
                ),
                "signature_algorithm_reference_only": bool(
                    evidence_closeout.get("signature_algorithm_reference_only")
                ),
                "secret_material_included": bool(
                    final_gate.get("secret_material_included")
                    or evidence_closeout.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    final_gate.get("secret_material_required_in_preview")
                    or evidence_closeout.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "accepts_plaintext_secret": bool(
                    evidence_closeout.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                ),
                "reads_secret_in_preview": bool(
                    final_gate.get("reads_secret_in_preview")
                    or evidence_closeout.get("reads_secret_in_preview")
                    or safety.get("reads_secret_in_preview")
                ),
                "executes_authorization_evidence": bool(
                    final_gate.get("executes_authorization_evidence")
                    or evidence_closeout.get("executes_authorization_evidence")
                    or contract.get("executes_authorization_evidence")
                    or safety.get("executes_authorization_evidence")
                ),
                "executes_database_apply": bool(
                    final_gate.get("executes_database_apply")
                    or evidence_closeout.get("executes_database_apply")
                    or contract.get("executes_database_apply")
                    or safety.get("executes_database_apply")
                ),
                "ready_for_database_apply_now": bool(
                    final_gate.get("ready_for_database_apply_now")
                    or evidence_closeout.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "database_apply_authorized": bool(
                    final_gate.get("database_apply_authorized")
                    or evidence_closeout.get("database_apply_authorized")
                    or contract.get("database_apply_authorized")
                ),
                "issues_database_apply_authorization": bool(
                    final_gate.get("issues_database_apply_authorization")
                    or evidence_closeout.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    final_gate.get("signs_database_apply_authorization")
                    or evidence_closeout.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "requires_post_apply_verifier": bool(
                    evidence_closeout.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    evidence_closeout.get(
                        "requires_fresh_production_truth_in_same_run"
                    )
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy authorization evidence execution closeout",
            "warning",
            (
                "PChome auto-policy authorization evidence execution closeout "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_authorization_evidence_execution_closeout"
                ),
            },
        )


def _pchome_auto_policy_controlled_apply_final_preflight_check() -> Dict[str, Any]:
    """Read-only monitor for the future controlled-apply final preflight."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        preflight = (
            backlog.build_pchome_auto_policy_db_apply_controlled_apply_final_preflight(
                payload,
                batch_size=max(
                    1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)
                ),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = preflight.get("summary") or {}
        future_preflight = (
            preflight.get("future_database_apply_controlled_apply_final_preflight")
            or {}
        )
        final_preflight = preflight.get("controlled_apply_final_preflight") or {}
        contract = preflight.get("controlled_apply_final_preflight_contract") or {}
        safety = preflight.get("safety") or {}
        rollback_binding = final_preflight.get("rollback_binding") or {}
        verifier_binding = (
            final_preflight.get("post_apply_verifier_binding") or {}
        )
        preflight_fields = list(
            final_preflight.get("controlled_apply_final_preflight_fields") or []
        )
        preflight_gates = list(
            final_preflight.get("controlled_apply_final_preflight_acceptance_gates")
            or []
        )
        result = str(preflight.get("result") or "UNKNOWN")

        ready_count = int(
            summary.get("controlled_apply_final_preflight_ready_count") or 0
        )
        check_count = int(
            summary.get("controlled_apply_final_preflight_check_count") or 0
        )
        pass_count = int(
            summary.get("controlled_apply_final_preflight_pass_count") or 0
        )
        waiting_count = int(
            summary.get("controlled_apply_final_preflight_waiting_count") or 0
        )
        evidence_closeout_ready_count = int(
            summary.get("authorization_evidence_execution_closeout_ready_count") or 0
        )
        evidence_closeout_check_count = int(
            summary.get("authorization_evidence_execution_closeout_check_count") or 0
        )
        evidence_preflight_ready_count = int(
            summary.get("authorization_evidence_execution_preflight_ready_count") or 0
        )
        evidence_preflight_check_count = int(
            summary.get("authorization_evidence_execution_preflight_check_count") or 0
        )
        verifier_closeout_ready_count = int(
            summary.get("authorization_verifier_receipt_closeout_ready_count") or 0
        )
        verifier_closeout_check_count = int(
            summary.get("verifier_receipt_closeout_check_count") or 0
        )
        final_verifier_gate_count = int(
            summary.get("database_apply_final_verifier_gate_count") or 0
        )
        final_verifier_gate_ready_count = int(
            summary.get("database_apply_authorization_final_verifier_gate_ready_count")
            or 0
        )
        final_preflight_count = int(
            summary.get("controlled_apply_final_preflight_count") or 0
        )
        final_preflight_field_count = int(
            summary.get("controlled_apply_final_preflight_field_count") or 0
        )
        final_preflight_gate_count = int(
            summary.get("controlled_apply_final_preflight_acceptance_gate_count") or 0
        )
        rollback_binding_count = int(summary.get("rollback_binding_count") or 0)
        rollback_binding_field_count = int(
            summary.get("rollback_binding_field_count") or 0
        )
        verifier_binding_count = int(
            summary.get("post_apply_verifier_binding_count") or 0
        )
        verifier_binding_field_count = int(
            summary.get("post_apply_verifier_binding_field_count") or 0
        )
        evidence_closeout_field_count = int(
            summary.get("authorization_evidence_execution_closeout_field_count") or 0
        )
        evidence_closeout_gate_count = int(
            summary.get(
                "authorization_evidence_execution_closeout_acceptance_gate_count"
            )
            or 0
        )
        verifier_required_count = int(
            summary.get("post_apply_verifier_required_count") or 0
        )
        same_run_truth_count = int(summary.get("same_run_truth_required_count") or 0)
        writes_script_count = int(summary.get("writes_script_count") or 0)
        writes_artifact_count = int(summary.get("writes_artifact_count") or 0)
        reads_secret_count = int(summary.get("reads_secret_count") or 0)
        executes_script_count = int(summary.get("executes_script_count") or 0)
        executes_migration_count = int(summary.get("executes_migration_count") or 0)
        executes_endpoint_count = int(summary.get("executes_endpoint_count") or 0)
        executes_sql_count = int(summary.get("executes_sql_count") or 0)
        writes_database_count = int(summary.get("writes_database_count") or 0)
        signs_database_apply_authorization_count = int(
            summary.get("signs_database_apply_authorization_count") or 0
        )
        primary_human_gate_count = int(summary.get(PRIMARY_HUMAN_GATE_COUNT_KEY) or 0)
        manual_review_required_count = int(
            summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY) or 0
        )
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("executes_authorization_evidence") is not False,
                safety.get("executes_database_apply") is not False,
                future_preflight.get("ready_for_database_apply_now") is not False,
                future_preflight.get("database_apply_authorized") is not False,
                future_preflight.get("issues_database_apply_authorization") is not False,
                future_preflight.get("signs_database_apply_authorization") is not False,
                future_preflight.get("executes_authorization_evidence") is not False,
                future_preflight.get("executes_database_apply") is not False,
                future_preflight.get("executes_endpoint") is not False,
                future_preflight.get("executes_sql") is not False,
                future_preflight.get("writes_database") is not False,
                future_preflight.get("reads_secret_in_preview") is not False,
                final_preflight.get("ready_for_database_apply_now") is not False,
                final_preflight.get("database_apply_authorized") is not False,
                final_preflight.get("issues_database_apply_authorization")
                is not False,
                final_preflight.get("signs_database_apply_authorization")
                is not False,
                final_preflight.get("executes_authorization_evidence") is not False,
                final_preflight.get("executes_database_apply") is not False,
                final_preflight.get("executes_endpoint_in_preview") is not False,
                final_preflight.get("executes_sql_in_preview") is not False,
                final_preflight.get("writes_database_in_preview") is not False,
                final_preflight.get("accepts_plaintext_secret") is not False,
                final_preflight.get("reads_secret_in_preview") is not False,
                final_preflight.get("signature_material_included") is not False,
                final_preflight.get("secret_material_included") is not False,
                final_preflight.get("secret_material_required_in_preview")
                is not False,
                rollback_binding.get("rollback_execution_authorized") is not False,
                rollback_binding.get("rollback_executes_sql") is not False,
                rollback_binding.get("rollback_writes_database") is not False,
                rollback_binding.get("rollback_reads_secret") is not False,
                verifier_binding.get("verifier_execution_authorized_in_preview")
                is not False,
                verifier_binding.get("database_apply_authorized") is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("executes_authorization_evidence") is not False,
                contract.get("executes_database_apply") is not False,
                contract.get("executes_endpoint") is not False,
                contract.get("executes_sql") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("database_apply_authorized") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        final_preflight_contract_present = (
            result == "DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_READY"
            and ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and evidence_closeout_ready_count == 1
            and evidence_closeout_check_count == 12
            and evidence_preflight_ready_count == 1
            and evidence_preflight_check_count == 12
            and verifier_closeout_ready_count == 1
            and verifier_closeout_check_count == 12
            and final_verifier_gate_count == 1
            and final_verifier_gate_ready_count == 1
            and final_preflight_count == 1
            and final_preflight_field_count == 12
            and final_preflight_gate_count == 10
            and rollback_binding_count == 1
            and rollback_binding_field_count == 8
            and verifier_binding_count == 1
            and verifier_binding_field_count == 8
            and evidence_closeout_field_count == 12
            and evidence_closeout_gate_count == 10
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and "rollback_binding_id" in preflight_fields
            and "post_apply_verifier_bound" in preflight_gates
            and future_preflight.get(
                "ready_for_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and future_preflight.get(
                "can_enter_future_database_apply_controlled_dry_run_package"
            )
            is True
            and future_preflight.get("controlled_apply_final_preflight_ready")
            is True
            and future_preflight.get("rollback_binding_ready") is True
            and future_preflight.get("post_apply_verifier_binding_ready") is True
            and final_preflight.get("authorization_material_type")
            == "controlled_apply_final_preflight"
            and final_preflight.get(
                "ready_for_future_database_apply_controlled_apply_final_preflight"
            )
            is True
            and final_preflight.get("dry_run_only") is True
            and final_preflight.get("check_mode_only") is True
            and final_preflight.get("rollback_bound") is True
            and final_preflight.get("post_apply_verifier_bound") is True
            and final_preflight.get("requires_fresh_production_truth_in_same_run")
            is True
            and final_preflight.get("requires_post_apply_verifier") is True
            and final_preflight.get("hash_matches") is True
            and rollback_binding.get("rollback_execution_authorized") is False
            and rollback_binding.get("rollback_executes_sql") is False
            and rollback_binding.get("rollback_writes_database") is False
            and rollback_binding.get("rollback_reads_secret") is False
            and rollback_binding.get("rollback_requires_same_run_truth") is True
            and verifier_binding.get("verifier_must_run_after_apply") is True
            and verifier_binding.get("same_run_production_truth_required") is True
            and verifier_binding.get("verifier_execution_authorized_in_preview")
            is False
            and verifier_binding.get("database_apply_authorized") is False
            and contract.get("machine_verifiable") is True
            and contract.get("permits_future_database_apply_controlled_dry_run_package")
            is True
            and contract.get("accepts_plaintext_secret") is False
            and contract.get("executes_authorization_evidence") is False
            and contract.get("executes_database_apply") is False
            and contract.get("executes_endpoint") is False
            and contract.get("executes_sql") is False
            and contract.get("writes_database") is False
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy controlled apply final preflight "
                "偵測到 secret、execution、SQL、DB write、rollback execution、"
                "database apply、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_controlled_apply_final_preflight_and_inspect_risk"
            )
        elif final_preflight_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy controlled apply final preflight "
                f"已自動完成 {pass_count}/{check_count} checks，rollback/verifier binding 已綁定，apply/write/sign=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_controlled_dry_run_package_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy controlled apply final preflight "
                "尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_controlled_apply_final_preflight"
            )

        return _check(
            "PChome auto-policy controlled apply final preflight",
            status,
            summary_text,
            {
                "policy": preflight.get("policy"),
                "result": result,
                "source_policy": preflight.get("source_policy"),
                "controlled_apply_final_preflight_ready_count": ready_count,
                "controlled_apply_final_preflight_check_count": check_count,
                "controlled_apply_final_preflight_pass_count": pass_count,
                "controlled_apply_final_preflight_waiting_count": waiting_count,
                "authorization_evidence_execution_closeout_ready_count": (
                    evidence_closeout_ready_count
                ),
                "authorization_evidence_execution_closeout_check_count": (
                    evidence_closeout_check_count
                ),
                "authorization_evidence_execution_preflight_ready_count": (
                    evidence_preflight_ready_count
                ),
                "authorization_evidence_execution_preflight_check_count": (
                    evidence_preflight_check_count
                ),
                "authorization_verifier_receipt_closeout_ready_count": (
                    verifier_closeout_ready_count
                ),
                "verifier_receipt_closeout_check_count": (
                    verifier_closeout_check_count
                ),
                "database_apply_final_verifier_gate_count": final_verifier_gate_count,
                "database_apply_authorization_final_verifier_gate_ready_count": (
                    final_verifier_gate_ready_count
                ),
                "controlled_apply_final_preflight_count": final_preflight_count,
                "controlled_apply_final_preflight_field_count": (
                    final_preflight_field_count
                ),
                "controlled_apply_final_preflight_acceptance_gate_count": (
                    final_preflight_gate_count
                ),
                "rollback_binding_count": rollback_binding_count,
                "rollback_binding_field_count": rollback_binding_field_count,
                "post_apply_verifier_binding_count": verifier_binding_count,
                "post_apply_verifier_binding_field_count": (
                    verifier_binding_field_count
                ),
                "authorization_evidence_execution_closeout_field_count": (
                    evidence_closeout_field_count
                ),
                "authorization_evidence_execution_closeout_acceptance_gate_count": (
                    evidence_closeout_gate_count
                ),
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_future_database_apply_controlled_apply_final_preflight": bool(
                    future_preflight.get(
                        "ready_for_future_database_apply_controlled_apply_final_preflight"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_package": bool(
                    future_preflight.get(
                        "can_enter_future_database_apply_controlled_dry_run_package"
                    )
                ),
                "controlled_apply_final_preflight_ready": bool(
                    future_preflight.get("controlled_apply_final_preflight_ready")
                ),
                "rollback_binding_ready": bool(
                    future_preflight.get("rollback_binding_ready")
                ),
                "post_apply_verifier_binding_ready": bool(
                    future_preflight.get("post_apply_verifier_binding_ready")
                ),
                "rollback_bound": bool(final_preflight.get("rollback_bound")),
                "post_apply_verifier_bound": bool(
                    final_preflight.get("post_apply_verifier_bound")
                ),
                "dry_run_only": bool(final_preflight.get("dry_run_only")),
                "check_mode_only": bool(final_preflight.get("check_mode_only")),
                "rollback_execution_authorized": bool(
                    rollback_binding.get("rollback_execution_authorized")
                ),
                "rollback_executes_sql": bool(
                    rollback_binding.get("rollback_executes_sql")
                ),
                "rollback_writes_database": bool(
                    rollback_binding.get("rollback_writes_database")
                ),
                "rollback_reads_secret": bool(
                    rollback_binding.get("rollback_reads_secret")
                ),
                "rollback_requires_same_run_truth": bool(
                    rollback_binding.get("rollback_requires_same_run_truth")
                ),
                "post_apply_verifier_must_run_after_apply": bool(
                    verifier_binding.get("verifier_must_run_after_apply")
                ),
                "post_apply_verifier_execution_authorized_in_preview": bool(
                    verifier_binding.get("verifier_execution_authorized_in_preview")
                ),
                "permits_future_database_apply_controlled_dry_run_package": bool(
                    contract.get(
                        "permits_future_database_apply_controlled_dry_run_package"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    final_preflight.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                ),
                "reads_secret_in_preview": bool(
                    future_preflight.get("reads_secret_in_preview")
                    or final_preflight.get("reads_secret_in_preview")
                    or safety.get("reads_secret_in_preview")
                ),
                "signature_material_included": bool(
                    final_preflight.get("signature_material_included")
                ),
                "secret_material_included": bool(
                    final_preflight.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    final_preflight.get("secret_material_required_in_preview")
                    or contract.get("secret_material_required_in_preview")
                ),
                "executes_authorization_evidence": bool(
                    future_preflight.get("executes_authorization_evidence")
                    or final_preflight.get("executes_authorization_evidence")
                    or contract.get("executes_authorization_evidence")
                    or safety.get("executes_authorization_evidence")
                ),
                "executes_database_apply": bool(
                    future_preflight.get("executes_database_apply")
                    or final_preflight.get("executes_database_apply")
                    or contract.get("executes_database_apply")
                    or safety.get("executes_database_apply")
                ),
                "executes_endpoint": bool(
                    future_preflight.get("executes_endpoint")
                    or contract.get("executes_endpoint")
                    or safety.get("executes_endpoint")
                ),
                "executes_sql": bool(
                    future_preflight.get("executes_sql")
                    or contract.get("executes_sql")
                    or safety.get("executes_sql")
                ),
                "ready_for_database_apply_now": bool(
                    future_preflight.get("ready_for_database_apply_now")
                    or final_preflight.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "database_apply_authorized": bool(
                    future_preflight.get("database_apply_authorized")
                    or final_preflight.get("database_apply_authorized")
                    or verifier_binding.get("database_apply_authorized")
                    or contract.get("database_apply_authorized")
                ),
                "issues_database_apply_authorization": bool(
                    future_preflight.get("issues_database_apply_authorization")
                    or final_preflight.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_preflight.get("signs_database_apply_authorization")
                    or final_preflight.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "requires_post_apply_verifier": bool(
                    final_preflight.get("requires_post_apply_verifier")
                ),
                "requires_fresh_production_truth": bool(
                    final_preflight.get(
                        "requires_fresh_production_truth_in_same_run"
                    )
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy controlled apply final preflight",
            "warning",
            (
                "PChome auto-policy controlled apply final preflight "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_controlled_apply_final_preflight"
                ),
            },
        )


def _pchome_auto_policy_controlled_dry_run_package_check() -> Dict[str, Any]:
    """Read-only monitor for the future controlled dry-run package."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        package = backlog.build_pchome_auto_policy_db_apply_controlled_dry_run_package(
            payload,
            batch_size=max(1, min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50)),
            execute_fetch=True,
            timeout_seconds=max(
                1,
                min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
            ),
            http_get=_pchome_auto_policy_machine_fetch_evidence_get,
        )
        summary = package.get("summary") or {}
        future_receipt = (
            package.get("future_database_apply_controlled_dry_run_execution_receipt")
            or {}
        )
        dry_run_package = package.get("controlled_dry_run_package") or {}
        contract = package.get("controlled_dry_run_package_contract") or {}
        safety = package.get("safety") or {}
        receipt_preview = dry_run_package.get("dry_run_execution_receipt_preview") or {}
        result_parser = dry_run_package.get("dry_run_result_parser") or {}
        command_shape = dry_run_package.get("dry_run_command_shape") or {}
        result = str(package.get("result") or "UNKNOWN")

        def _count(key: str) -> int:
            return int(summary.get(key) or 0)

        ready_count = _count("controlled_dry_run_package_ready_count")
        check_count = _count("controlled_dry_run_package_check_count")
        pass_count = _count("controlled_dry_run_package_pass_count")
        waiting_count = _count("controlled_dry_run_package_waiting_count")
        controlled_apply_ready_count = _count(
            "controlled_apply_final_preflight_ready_count"
        )
        controlled_apply_check_count = _count(
            "controlled_apply_final_preflight_check_count"
        )
        evidence_closeout_ready_count = _count(
            "authorization_evidence_execution_closeout_ready_count"
        )
        evidence_closeout_check_count = _count(
            "authorization_evidence_execution_closeout_check_count"
        )
        evidence_preflight_ready_count = _count(
            "authorization_evidence_execution_preflight_ready_count"
        )
        evidence_preflight_check_count = _count(
            "authorization_evidence_execution_preflight_check_count"
        )
        verifier_closeout_ready_count = _count(
            "authorization_verifier_receipt_closeout_ready_count"
        )
        verifier_closeout_check_count = _count("verifier_receipt_closeout_check_count")
        final_verifier_gate_count = _count("database_apply_final_verifier_gate_count")
        final_verifier_gate_ready_count = _count(
            "database_apply_authorization_final_verifier_gate_ready_count"
        )
        package_count = _count("controlled_dry_run_package_count")
        package_field_count = _count("controlled_dry_run_package_field_count")
        package_gate_count = _count("controlled_dry_run_acceptance_gate_count")
        receipt_preview_count = _count("dry_run_execution_receipt_preview_count")
        receipt_field_count = _count("dry_run_execution_receipt_field_count")
        parser_count = _count("dry_run_result_parser_count")
        parser_field_count = _count("dry_run_result_parser_field_count")
        final_preflight_count = _count("controlled_apply_final_preflight_count")
        final_preflight_field_count = _count(
            "controlled_apply_final_preflight_field_count"
        )
        final_preflight_gate_count = _count(
            "controlled_apply_final_preflight_acceptance_gate_count"
        )
        rollback_binding_count = _count("rollback_binding_count")
        rollback_binding_field_count = _count("rollback_binding_field_count")
        verifier_binding_count = _count("post_apply_verifier_binding_count")
        verifier_binding_field_count = _count("post_apply_verifier_binding_field_count")
        verifier_required_count = _count("post_apply_verifier_required_count")
        same_run_truth_count = _count("same_run_truth_required_count")
        writes_script_count = _count("writes_script_count")
        writes_artifact_count = _count("writes_artifact_count")
        reads_secret_count = _count("reads_secret_count")
        executes_script_count = _count("executes_script_count")
        executes_migration_count = _count("executes_migration_count")
        executes_endpoint_count = _count("executes_endpoint_count")
        executes_sql_count = _count("executes_sql_count")
        writes_database_count = _count("writes_database_count")
        signs_database_apply_authorization_count = _count(
            "signs_database_apply_authorization_count"
        )
        primary_human_gate_count = _count(PRIMARY_HUMAN_GATE_COUNT_KEY)
        manual_review_required_count = _count(LEGACY_REVIEW_REQUIRED_COUNT_KEY)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("executes_authorization_evidence") is not False,
                safety.get("executes_database_apply") is not False,
                future_receipt.get("dry_run_execution_performed") is not False,
                future_receipt.get("ready_for_database_apply_now") is not False,
                future_receipt.get("database_apply_authorized") is not False,
                future_receipt.get("issues_database_apply_authorization") is not False,
                future_receipt.get("signs_database_apply_authorization") is not False,
                future_receipt.get("executes_authorization_evidence") is not False,
                future_receipt.get("executes_database_apply") is not False,
                future_receipt.get("executes_endpoint") is not False,
                future_receipt.get("executes_sql") is not False,
                future_receipt.get("writes_database") is not False,
                future_receipt.get("reads_secret_in_preview") is not False,
                dry_run_package.get("ready_for_database_apply_now") is not False,
                dry_run_package.get("database_apply_authorized") is not False,
                dry_run_package.get("issues_database_apply_authorization") is not False,
                dry_run_package.get("signs_database_apply_authorization") is not False,
                dry_run_package.get("accepts_plaintext_secret") is not False,
                dry_run_package.get("reads_secret_in_preview") is not False,
                dry_run_package.get("signature_material_included") is not False,
                dry_run_package.get("secret_material_included") is not False,
                dry_run_package.get("executes_authorization_evidence") is not False,
                dry_run_package.get("executes_database_apply") is not False,
                dry_run_package.get("executes_endpoint_in_preview") is not False,
                dry_run_package.get("executes_sql_in_preview") is not False,
                dry_run_package.get("writes_database_in_preview") is not False,
                command_shape.get("execution_allowed") is not False,
                command_shape.get("shell_command_included") is not False,
                command_shape.get("sql_included") is not False,
                command_shape.get("endpoint_execution_included") is not False,
                command_shape.get("database_write_included") is not False,
                receipt_preview.get("execution_performed") is not False,
                receipt_preview.get("stdout_included") is not False,
                receipt_preview.get("stderr_included") is not False,
                receipt_preview.get("database_apply_authorized") is not False,
                receipt_preview.get("executes_shell") is not False,
                receipt_preview.get("executes_endpoint") is not False,
                receipt_preview.get("executes_sql") is not False,
                receipt_preview.get("writes_database") is not False,
                receipt_preview.get("reads_secret") is not False,
                result_parser.get("execution_required") is not False,
                result_parser.get("stdout_allowed") is not False,
                result_parser.get("stderr_allowed") is not False,
                result_parser.get("database_apply_authorized") is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("executes_authorization_evidence") is not False,
                contract.get("executes_database_apply") is not False,
                contract.get("executes_endpoint") is not False,
                contract.get("executes_sql") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("database_apply_authorized") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        package_contract_present = (
            result == "DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_READY"
            and ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and controlled_apply_ready_count == 1
            and controlled_apply_check_count == 12
            and evidence_closeout_ready_count == 1
            and evidence_closeout_check_count == 12
            and evidence_preflight_ready_count == 1
            and evidence_preflight_check_count == 12
            and verifier_closeout_ready_count == 1
            and verifier_closeout_check_count == 12
            and final_verifier_gate_count == 1
            and final_verifier_gate_ready_count == 1
            and package_count == 1
            and package_field_count == 12
            and package_gate_count == 10
            and receipt_preview_count == 1
            and receipt_field_count == 8
            and parser_count == 1
            and parser_field_count == 10
            and final_preflight_count == 1
            and final_preflight_field_count == 12
            and final_preflight_gate_count == 10
            and rollback_binding_count == 1
            and rollback_binding_field_count == 8
            and verifier_binding_count == 1
            and verifier_binding_field_count == 8
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_receipt.get(
                "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
            )
            is True
            and future_receipt.get(
                "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
            )
            is True
            and future_receipt.get("controlled_dry_run_package_ready") is True
            and dry_run_package.get("authorization_material_type")
            == "controlled_dry_run_package"
            and dry_run_package.get(
                "ready_for_future_database_apply_controlled_dry_run_package"
            )
            is True
            and dry_run_package.get("target_migration_hash_locked") is True
            and dry_run_package.get("dry_run_only") is True
            and dry_run_package.get("check_mode_only") is True
            and dry_run_package.get("requires_fresh_production_truth_in_same_run")
            is True
            and dry_run_package.get("requires_post_apply_verifier") is True
            and command_shape.get("dry_run_only") is True
            and command_shape.get("check_mode_only") is True
            and command_shape.get("execution_allowed") is False
            and command_shape.get("requires_rollback_binding") is True
            and command_shape.get("requires_post_apply_verifier_binding") is True
            and receipt_preview.get("dry_run_status") == "preview_only_not_executed"
            and receipt_preview.get("receipt_field_count") == 8
            and receipt_preview.get("execution_performed") is False
            and receipt_preview.get("stdout_included") is False
            and receipt_preview.get("stderr_included") is False
            and receipt_preview.get("database_apply_authorized") is False
            and result_parser.get("expected_receipt_status")
            == "preview_only_not_executed"
            and result_parser.get("execution_required") is False
            and result_parser.get("parser_verification_status")
            == "schema_preview_ready"
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_database_apply_controlled_dry_run_execution_receipt"
            )
            is True
            and contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy controlled dry-run package "
                "偵測到 secret、execution、stdout/stderr、SQL、DB write、"
                "database apply、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_controlled_dry_run_package_and_inspect_risk"
            )
        elif package_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy controlled dry-run package "
                f"已自動完成 {pass_count}/{check_count} checks，receipt preview/parser 已綁定，execution/write/apply=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_controlled_dry_run_receipt_closeout_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy controlled dry-run package "
                "尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_controlled_dry_run_package"
            )

        return _check(
            "PChome auto-policy controlled dry-run package",
            status,
            summary_text,
            {
                "policy": package.get("policy"),
                "result": result,
                "source_policy": package.get("source_policy"),
                "controlled_dry_run_package_ready_count": ready_count,
                "controlled_dry_run_package_check_count": check_count,
                "controlled_dry_run_package_pass_count": pass_count,
                "controlled_dry_run_package_waiting_count": waiting_count,
                "controlled_apply_final_preflight_ready_count": (
                    controlled_apply_ready_count
                ),
                "controlled_apply_final_preflight_check_count": (
                    controlled_apply_check_count
                ),
                "authorization_evidence_execution_closeout_ready_count": (
                    evidence_closeout_ready_count
                ),
                "authorization_evidence_execution_closeout_check_count": (
                    evidence_closeout_check_count
                ),
                "authorization_evidence_execution_preflight_ready_count": (
                    evidence_preflight_ready_count
                ),
                "authorization_evidence_execution_preflight_check_count": (
                    evidence_preflight_check_count
                ),
                "authorization_verifier_receipt_closeout_ready_count": (
                    verifier_closeout_ready_count
                ),
                "verifier_receipt_closeout_check_count": (
                    verifier_closeout_check_count
                ),
                "database_apply_final_verifier_gate_count": final_verifier_gate_count,
                "database_apply_authorization_final_verifier_gate_ready_count": (
                    final_verifier_gate_ready_count
                ),
                "controlled_dry_run_package_count": package_count,
                "controlled_dry_run_package_field_count": package_field_count,
                "controlled_dry_run_acceptance_gate_count": package_gate_count,
                "dry_run_execution_receipt_preview_count": receipt_preview_count,
                "dry_run_execution_receipt_field_count": receipt_field_count,
                "dry_run_result_parser_count": parser_count,
                "dry_run_result_parser_field_count": parser_field_count,
                "controlled_apply_final_preflight_count": final_preflight_count,
                "controlled_apply_final_preflight_field_count": (
                    final_preflight_field_count
                ),
                "controlled_apply_final_preflight_acceptance_gate_count": (
                    final_preflight_gate_count
                ),
                "rollback_binding_count": rollback_binding_count,
                "rollback_binding_field_count": rollback_binding_field_count,
                "post_apply_verifier_binding_count": verifier_binding_count,
                "post_apply_verifier_binding_field_count": (
                    verifier_binding_field_count
                ),
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_future_database_apply_controlled_dry_run_execution_receipt": bool(
                    future_receipt.get(
                        "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_receipt_closeout": bool(
                    future_receipt.get(
                        "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
                    )
                ),
                "controlled_dry_run_package_ready": bool(
                    future_receipt.get("controlled_dry_run_package_ready")
                ),
                "dry_run_execution_performed": bool(
                    future_receipt.get("dry_run_execution_performed")
                ),
                "ready_for_future_database_apply_controlled_dry_run_package": bool(
                    dry_run_package.get(
                        "ready_for_future_database_apply_controlled_dry_run_package"
                    )
                ),
                "target_migration_hash_locked": bool(
                    dry_run_package.get("target_migration_hash_locked")
                ),
                "dry_run_only": bool(dry_run_package.get("dry_run_only")),
                "check_mode_only": bool(dry_run_package.get("check_mode_only")),
                "requires_fresh_production_truth": bool(
                    dry_run_package.get("requires_fresh_production_truth_in_same_run")
                ),
                "requires_post_apply_verifier": bool(
                    dry_run_package.get("requires_post_apply_verifier")
                ),
                "command_shape_dry_run_only": bool(
                    command_shape.get("dry_run_only")
                ),
                "command_shape_check_mode_only": bool(
                    command_shape.get("check_mode_only")
                ),
                "command_shape_execution_allowed": bool(
                    command_shape.get("execution_allowed")
                ),
                "command_shape_shell_command_included": bool(
                    command_shape.get("shell_command_included")
                ),
                "command_shape_sql_included": bool(command_shape.get("sql_included")),
                "command_shape_endpoint_execution_included": bool(
                    command_shape.get("endpoint_execution_included")
                ),
                "command_shape_database_write_included": bool(
                    command_shape.get("database_write_included")
                ),
                "receipt_dry_run_status": receipt_preview.get("dry_run_status"),
                "receipt_execution_performed": bool(
                    receipt_preview.get("execution_performed")
                ),
                "receipt_stdout_included": bool(
                    receipt_preview.get("stdout_included")
                ),
                "receipt_stderr_included": bool(
                    receipt_preview.get("stderr_included")
                ),
                "receipt_database_apply_authorized": bool(
                    receipt_preview.get("database_apply_authorized")
                ),
                "receipt_executes_shell": bool(receipt_preview.get("executes_shell")),
                "receipt_executes_endpoint": bool(
                    receipt_preview.get("executes_endpoint")
                ),
                "receipt_executes_sql": bool(receipt_preview.get("executes_sql")),
                "receipt_writes_database": bool(receipt_preview.get("writes_database")),
                "receipt_reads_secret": bool(receipt_preview.get("reads_secret")),
                "parser_expected_receipt_status": result_parser.get(
                    "expected_receipt_status"
                ),
                "parser_execution_required": bool(
                    result_parser.get("execution_required")
                ),
                "parser_stdout_allowed": bool(result_parser.get("stdout_allowed")),
                "parser_stderr_allowed": bool(result_parser.get("stderr_allowed")),
                "parser_database_apply_authorized": bool(
                    result_parser.get("database_apply_authorized")
                ),
                "parser_verification_status": result_parser.get(
                    "parser_verification_status"
                ),
                "permits_future_database_apply_controlled_dry_run_execution_receipt": bool(
                    contract.get(
                        "permits_future_database_apply_controlled_dry_run_execution_receipt"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    dry_run_package.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                ),
                "reads_secret_in_preview": bool(
                    dry_run_package.get("reads_secret_in_preview")
                    or safety.get("reads_secret_in_preview")
                ),
                "signature_material_included": bool(
                    dry_run_package.get("signature_material_included")
                ),
                "secret_material_included": bool(
                    dry_run_package.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    contract.get("secret_material_required_in_preview")
                ),
                "executes_authorization_evidence": bool(
                    future_receipt.get("executes_authorization_evidence")
                    or dry_run_package.get("executes_authorization_evidence")
                    or contract.get("executes_authorization_evidence")
                    or safety.get("executes_authorization_evidence")
                ),
                "executes_database_apply": bool(
                    future_receipt.get("executes_database_apply")
                    or dry_run_package.get("executes_database_apply")
                    or contract.get("executes_database_apply")
                    or safety.get("executes_database_apply")
                ),
                "executes_endpoint": bool(
                    future_receipt.get("executes_endpoint")
                    or contract.get("executes_endpoint")
                    or safety.get("executes_endpoint")
                ),
                "executes_sql": bool(
                    future_receipt.get("executes_sql")
                    or contract.get("executes_sql")
                    or safety.get("executes_sql")
                ),
                "ready_for_database_apply_now": bool(
                    future_receipt.get("ready_for_database_apply_now")
                    or dry_run_package.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "database_apply_authorized": bool(
                    future_receipt.get("database_apply_authorized")
                    or dry_run_package.get("database_apply_authorized")
                    or contract.get("database_apply_authorized")
                ),
                "issues_database_apply_authorization": bool(
                    future_receipt.get("issues_database_apply_authorization")
                    or dry_run_package.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_receipt.get("signs_database_apply_authorization")
                    or dry_run_package.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy controlled dry-run package",
            "warning",
            (
                "PChome auto-policy controlled dry-run package "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_controlled_dry_run_package"
                ),
            },
        )


def _pchome_auto_policy_controlled_dry_run_receipt_closeout_check() -> Dict[str, Any]:
    """Read-only monitor for the controlled dry-run receipt closeout."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        closeout = (
            backlog.build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_closeout(
                payload,
                batch_size=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50),
                ),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = closeout.get("summary") or {}
        future_verification = (
            closeout.get(
                "future_database_apply_controlled_dry_run_result_parser_verification"
            )
            or {}
        )
        receipt_closeout = closeout.get("controlled_dry_run_receipt_closeout") or {}
        contract = closeout.get("controlled_dry_run_receipt_closeout_contract") or {}
        safety = closeout.get("safety") or {}
        validation_report = (
            receipt_closeout.get("receipt_validation_report") or {}
        )
        result_parser = receipt_closeout.get("dry_run_result_parser") or {}
        source_package = closeout.get("source_controlled_dry_run_package") or {}
        source_future_receipt = (
            closeout.get("source_database_apply_controlled_dry_run_execution_receipt")
            or {}
        )
        result = str(closeout.get("result") or "UNKNOWN")

        def _count(key: str) -> int:
            return int(summary.get(key) or 0)

        ready_count = _count("controlled_dry_run_receipt_closeout_ready_count")
        check_count = _count("controlled_dry_run_receipt_closeout_check_count")
        pass_count = _count("controlled_dry_run_receipt_closeout_pass_count")
        waiting_count = _count("controlled_dry_run_receipt_closeout_waiting_count")
        package_ready_count = _count("controlled_dry_run_package_ready_count")
        package_check_count = _count("controlled_dry_run_package_check_count")
        controlled_apply_ready_count = _count(
            "controlled_apply_final_preflight_ready_count"
        )
        controlled_apply_check_count = _count(
            "controlled_apply_final_preflight_check_count"
        )
        evidence_closeout_ready_count = _count(
            "authorization_evidence_execution_closeout_ready_count"
        )
        evidence_closeout_check_count = _count(
            "authorization_evidence_execution_closeout_check_count"
        )
        evidence_preflight_ready_count = _count(
            "authorization_evidence_execution_preflight_ready_count"
        )
        evidence_preflight_check_count = _count(
            "authorization_evidence_execution_preflight_check_count"
        )
        verifier_closeout_ready_count = _count(
            "authorization_verifier_receipt_closeout_ready_count"
        )
        verifier_closeout_check_count = _count("verifier_receipt_closeout_check_count")
        final_verifier_gate_count = _count("database_apply_final_verifier_gate_count")
        final_verifier_gate_ready_count = _count(
            "database_apply_authorization_final_verifier_gate_ready_count"
        )
        closeout_count = _count("controlled_dry_run_receipt_closeout_count")
        closeout_field_count = _count("controlled_dry_run_receipt_closeout_field_count")
        closeout_gate_count = _count(
            "controlled_dry_run_receipt_closeout_acceptance_gate_count"
        )
        parser_count = _count("dry_run_result_parser_count")
        parser_field_count = _count("dry_run_result_parser_field_count")
        validation_report_count = _count("receipt_validation_report_count")
        validation_field_count = _count("receipt_validation_field_count")
        receipt_preview_count = _count("dry_run_execution_receipt_preview_count")
        receipt_preview_field_count = _count("dry_run_execution_receipt_field_count")
        source_package_count = _count("controlled_dry_run_package_count")
        source_package_field_count = _count("controlled_dry_run_package_field_count")
        source_package_gate_count = _count("controlled_dry_run_acceptance_gate_count")
        rollback_binding_count = _count("rollback_binding_count")
        verifier_binding_count = _count("post_apply_verifier_binding_count")
        verifier_required_count = _count("post_apply_verifier_required_count")
        same_run_truth_count = _count("same_run_truth_required_count")
        writes_script_count = _count("writes_script_count")
        writes_artifact_count = _count("writes_artifact_count")
        reads_secret_count = _count("reads_secret_count")
        executes_script_count = _count("executes_script_count")
        executes_migration_count = _count("executes_migration_count")
        executes_endpoint_count = _count("executes_endpoint_count")
        executes_sql_count = _count("executes_sql_count")
        writes_database_count = _count("writes_database_count")
        signs_database_apply_authorization_count = _count(
            "signs_database_apply_authorization_count"
        )
        primary_human_gate_count = _count(PRIMARY_HUMAN_GATE_COUNT_KEY)
        manual_review_required_count = _count(LEGACY_REVIEW_REQUIRED_COUNT_KEY)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("executes_authorization_evidence") is not False,
                safety.get("executes_database_apply") is not False,
                future_verification.get("dry_run_execution_performed") is not False,
                future_verification.get("ready_for_database_apply_now") is not False,
                future_verification.get("database_apply_authorized") is not False,
                future_verification.get("issues_database_apply_authorization")
                is not False,
                future_verification.get("signs_database_apply_authorization")
                is not False,
                future_verification.get("executes_authorization_evidence")
                is not False,
                future_verification.get("executes_database_apply") is not False,
                future_verification.get("executes_endpoint") is not False,
                future_verification.get("executes_sql") is not False,
                future_verification.get("writes_database") is not False,
                future_verification.get("reads_secret_in_preview") is not False,
                receipt_closeout.get("ready_for_database_apply_now") is not False,
                receipt_closeout.get("database_apply_authorized") is not False,
                receipt_closeout.get("issues_database_apply_authorization")
                is not False,
                receipt_closeout.get("signs_database_apply_authorization")
                is not False,
                receipt_closeout.get("accepts_plaintext_secret") is not False,
                receipt_closeout.get("reads_secret_in_preview") is not False,
                receipt_closeout.get("signature_material_included") is not False,
                receipt_closeout.get("secret_material_included") is not False,
                receipt_closeout.get("executes_authorization_evidence") is not False,
                receipt_closeout.get("executes_database_apply") is not False,
                receipt_closeout.get("executes_endpoint_in_preview") is not False,
                receipt_closeout.get("executes_sql_in_preview") is not False,
                receipt_closeout.get("writes_database_in_preview") is not False,
                validation_report.get("execution_performed") is not False,
                validation_report.get("stdout_included") is not False,
                validation_report.get("stderr_included") is not False,
                validation_report.get("database_apply_authorized") is not False,
                validation_report.get("executes_shell") is not False,
                validation_report.get("executes_endpoint") is not False,
                validation_report.get("executes_sql") is not False,
                validation_report.get("writes_database") is not False,
                validation_report.get("reads_secret") is not False,
                result_parser.get("execution_required") is not False,
                result_parser.get("stdout_allowed") is not False,
                result_parser.get("stderr_allowed") is not False,
                result_parser.get("database_apply_authorized") is not False,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("executes_authorization_evidence") is not False,
                contract.get("executes_database_apply") is not False,
                contract.get("executes_endpoint") is not False,
                contract.get("executes_sql") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("database_apply_authorized") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        closeout_contract_present = (
            result == "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_READY"
            and ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and package_ready_count == 1
            and package_check_count == 12
            and controlled_apply_ready_count == 1
            and controlled_apply_check_count == 12
            and evidence_closeout_ready_count == 1
            and evidence_closeout_check_count == 12
            and evidence_preflight_ready_count == 1
            and evidence_preflight_check_count == 12
            and verifier_closeout_ready_count == 1
            and verifier_closeout_check_count == 12
            and final_verifier_gate_count == 1
            and final_verifier_gate_ready_count == 1
            and closeout_count == 1
            and closeout_field_count == 12
            and closeout_gate_count == 10
            and parser_count == 1
            and parser_field_count == 10
            and validation_report_count == 1
            and validation_field_count == 8
            and receipt_preview_count == 1
            and receipt_preview_field_count == 8
            and source_package_count == 1
            and source_package_field_count == 12
            and source_package_gate_count == 10
            and rollback_binding_count == 1
            and verifier_binding_count == 1
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_verification.get(
                "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
            )
            is True
            and future_verification.get(
                "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True
            and future_verification.get("controlled_dry_run_receipt_closeout_ready")
            is True
            and future_verification.get("receipt_validation_status")
            == "preview_validated_not_executed"
            and source_future_receipt.get("dry_run_execution_performed") is False
            and source_future_receipt.get("controlled_dry_run_package_ready") is True
            and source_package.get("target_migration_hash_locked") is True
            and receipt_closeout.get("authorization_material_type")
            == "controlled_dry_run_receipt_closeout"
            and receipt_closeout.get(
                "ready_for_future_database_apply_controlled_dry_run_receipt_closeout"
            )
            is True
            and receipt_closeout.get("target_migration_hash_locked") is True
            and receipt_closeout.get("dry_run_only") is True
            and receipt_closeout.get("check_mode_only") is True
            and receipt_closeout.get("receipt_preview_only") is True
            and receipt_closeout.get("requires_fresh_production_truth_in_same_run")
            is True
            and receipt_closeout.get("requires_post_apply_verifier") is True
            and validation_report.get("receipt_validation_status")
            == "preview_validated_not_executed"
            and validation_report.get("execution_performed") is False
            and validation_report.get("stdout_included") is False
            and validation_report.get("stderr_included") is False
            and validation_report.get("database_apply_authorized") is False
            and validation_report.get("executes_shell") is False
            and validation_report.get("executes_endpoint") is False
            and validation_report.get("executes_sql") is False
            and validation_report.get("writes_database") is False
            and validation_report.get("reads_secret") is False
            and result_parser.get("expected_receipt_status")
            == "preview_only_not_executed"
            and result_parser.get("execution_required") is False
            and result_parser.get("parser_verification_status")
            == "schema_preview_ready"
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True
            and contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy controlled dry-run receipt closeout "
                "偵測到 secret、execution、stdout/stderr、SQL、DB write、"
                "database apply、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_controlled_dry_run_receipt_closeout_and_inspect_risk"
            )
        elif closeout_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy controlled dry-run receipt closeout "
                f"已自動完成 {pass_count}/{check_count} checks，receipt/parser/hash 已閉合，execution/write/apply=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_controlled_dry_run_runner_readiness_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy controlled dry-run receipt closeout "
                "尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_controlled_dry_run_receipt_closeout"
            )

        return _check(
            "PChome auto-policy controlled dry-run receipt closeout",
            status,
            summary_text,
            {
                "policy": closeout.get("policy"),
                "result": result,
                "source_policy": closeout.get("source_policy"),
                "controlled_dry_run_receipt_closeout_ready_count": ready_count,
                "controlled_dry_run_receipt_closeout_check_count": check_count,
                "controlled_dry_run_receipt_closeout_pass_count": pass_count,
                "controlled_dry_run_receipt_closeout_waiting_count": waiting_count,
                "controlled_dry_run_package_ready_count": package_ready_count,
                "controlled_dry_run_package_check_count": package_check_count,
                "controlled_apply_final_preflight_ready_count": (
                    controlled_apply_ready_count
                ),
                "controlled_apply_final_preflight_check_count": (
                    controlled_apply_check_count
                ),
                "authorization_evidence_execution_closeout_ready_count": (
                    evidence_closeout_ready_count
                ),
                "authorization_evidence_execution_closeout_check_count": (
                    evidence_closeout_check_count
                ),
                "authorization_evidence_execution_preflight_ready_count": (
                    evidence_preflight_ready_count
                ),
                "authorization_evidence_execution_preflight_check_count": (
                    evidence_preflight_check_count
                ),
                "authorization_verifier_receipt_closeout_ready_count": (
                    verifier_closeout_ready_count
                ),
                "verifier_receipt_closeout_check_count": (
                    verifier_closeout_check_count
                ),
                "database_apply_final_verifier_gate_count": final_verifier_gate_count,
                "database_apply_authorization_final_verifier_gate_ready_count": (
                    final_verifier_gate_ready_count
                ),
                "controlled_dry_run_receipt_closeout_count": closeout_count,
                "controlled_dry_run_receipt_closeout_field_count": closeout_field_count,
                "controlled_dry_run_receipt_closeout_acceptance_gate_count": (
                    closeout_gate_count
                ),
                "dry_run_result_parser_count": parser_count,
                "dry_run_result_parser_field_count": parser_field_count,
                "receipt_validation_report_count": validation_report_count,
                "receipt_validation_field_count": validation_field_count,
                "dry_run_execution_receipt_preview_count": receipt_preview_count,
                "dry_run_execution_receipt_field_count": receipt_preview_field_count,
                "controlled_dry_run_package_count": source_package_count,
                "controlled_dry_run_package_field_count": source_package_field_count,
                "controlled_dry_run_acceptance_gate_count": source_package_gate_count,
                "rollback_binding_count": rollback_binding_count,
                "post_apply_verifier_binding_count": verifier_binding_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_future_database_apply_controlled_dry_run_result_parser_verification": bool(
                    future_verification.get(
                        "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_runner_readiness": bool(
                    future_verification.get(
                        "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
                    )
                ),
                "controlled_dry_run_receipt_closeout_ready": bool(
                    future_verification.get(
                        "controlled_dry_run_receipt_closeout_ready"
                    )
                ),
                "source_controlled_dry_run_package_ready": bool(
                    source_future_receipt.get("controlled_dry_run_package_ready")
                ),
                "dry_run_execution_performed": bool(
                    source_future_receipt.get("dry_run_execution_performed")
                    or future_verification.get("dry_run_execution_performed")
                ),
                "ready_for_future_database_apply_controlled_dry_run_receipt_closeout": bool(
                    receipt_closeout.get(
                        "ready_for_future_database_apply_controlled_dry_run_receipt_closeout"
                    )
                ),
                "target_migration_hash_locked": bool(
                    receipt_closeout.get("target_migration_hash_locked")
                    or source_package.get("target_migration_hash_locked")
                ),
                "dry_run_only": bool(receipt_closeout.get("dry_run_only")),
                "check_mode_only": bool(receipt_closeout.get("check_mode_only")),
                "receipt_preview_only": bool(
                    receipt_closeout.get("receipt_preview_only")
                ),
                "requires_fresh_production_truth": bool(
                    receipt_closeout.get(
                        "requires_fresh_production_truth_in_same_run"
                    )
                ),
                "requires_post_apply_verifier": bool(
                    receipt_closeout.get("requires_post_apply_verifier")
                ),
                "receipt_validation_status": validation_report.get(
                    "receipt_validation_status"
                ),
                "validation_execution_performed": bool(
                    validation_report.get("execution_performed")
                ),
                "validation_stdout_included": bool(
                    validation_report.get("stdout_included")
                ),
                "validation_stderr_included": bool(
                    validation_report.get("stderr_included")
                ),
                "validation_database_apply_authorized": bool(
                    validation_report.get("database_apply_authorized")
                ),
                "validation_executes_shell": bool(
                    validation_report.get("executes_shell")
                ),
                "validation_executes_endpoint": bool(
                    validation_report.get("executes_endpoint")
                ),
                "validation_executes_sql": bool(validation_report.get("executes_sql")),
                "validation_writes_database": bool(
                    validation_report.get("writes_database")
                ),
                "validation_reads_secret": bool(validation_report.get("reads_secret")),
                "parser_expected_receipt_status": result_parser.get(
                    "expected_receipt_status"
                ),
                "parser_execution_required": bool(
                    result_parser.get("execution_required")
                ),
                "parser_stdout_allowed": bool(result_parser.get("stdout_allowed")),
                "parser_stderr_allowed": bool(result_parser.get("stderr_allowed")),
                "parser_database_apply_authorized": bool(
                    result_parser.get("database_apply_authorized")
                ),
                "parser_verification_status": result_parser.get(
                    "parser_verification_status"
                ),
                "permits_future_database_apply_controlled_dry_run_runner_readiness": bool(
                    contract.get(
                        "permits_future_database_apply_controlled_dry_run_runner_readiness"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    receipt_closeout.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                ),
                "reads_secret_in_preview": bool(
                    receipt_closeout.get("reads_secret_in_preview")
                    or safety.get("reads_secret_in_preview")
                ),
                "signature_material_included": bool(
                    receipt_closeout.get("signature_material_included")
                ),
                "secret_material_included": bool(
                    receipt_closeout.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    contract.get("secret_material_required_in_preview")
                ),
                "executes_authorization_evidence": bool(
                    future_verification.get("executes_authorization_evidence")
                    or receipt_closeout.get("executes_authorization_evidence")
                    or contract.get("executes_authorization_evidence")
                    or safety.get("executes_authorization_evidence")
                ),
                "executes_database_apply": bool(
                    future_verification.get("executes_database_apply")
                    or receipt_closeout.get("executes_database_apply")
                    or contract.get("executes_database_apply")
                    or safety.get("executes_database_apply")
                ),
                "executes_endpoint": bool(
                    future_verification.get("executes_endpoint")
                    or contract.get("executes_endpoint")
                    or safety.get("executes_endpoint")
                ),
                "executes_sql": bool(
                    future_verification.get("executes_sql")
                    or contract.get("executes_sql")
                    or safety.get("executes_sql")
                ),
                "ready_for_database_apply_now": bool(
                    future_verification.get("ready_for_database_apply_now")
                    or receipt_closeout.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "database_apply_authorized": bool(
                    future_verification.get("database_apply_authorized")
                    or receipt_closeout.get("database_apply_authorized")
                    or contract.get("database_apply_authorized")
                ),
                "issues_database_apply_authorization": bool(
                    future_verification.get("issues_database_apply_authorization")
                    or receipt_closeout.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_verification.get("signs_database_apply_authorization")
                    or receipt_closeout.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy controlled dry-run receipt closeout",
            "warning",
            (
                "PChome auto-policy controlled dry-run receipt closeout "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_controlled_dry_run_receipt_closeout"
                ),
            },
        )


def _pchome_auto_policy_controlled_dry_run_runner_readiness_check() -> Dict[str, Any]:
    """Read-only monitor for the controlled dry-run runner readiness binding."""
    try:
        from services import pchome_mapping_backlog_service as backlog
        from services.ai_exception_contract import (
            LEGACY_REVIEW_REQUIRED_COUNT_KEY,
            PRIMARY_HUMAN_GATE_COUNT_KEY,
        )

        payload = _pchome_auto_policy_decision_preflight_contract_payload()
        readiness = (
            backlog.build_pchome_auto_policy_db_apply_controlled_dry_run_runner_readiness(
                payload,
                batch_size=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_BATCH_SIZE, 50),
                ),
                execute_fetch=True,
                timeout_seconds=max(
                    1,
                    min(_PCHOME_AUTO_POLICY_DECISION_PREFLIGHT_TIMEOUT_SECONDS, 30),
                ),
                http_get=_pchome_auto_policy_machine_fetch_evidence_get,
            )
        )
        summary = readiness.get("summary") or {}
        future_plan = (
            readiness.get(
                "future_database_apply_controlled_dry_run_execution_plan_binding"
            )
            or {}
        )
        runner = readiness.get("controlled_dry_run_runner_readiness") or {}
        contract = readiness.get("controlled_dry_run_runner_readiness_contract") or {}
        safety = readiness.get("safety") or {}
        execution_plan = runner.get("execution_plan_binding") or {}
        result_parser = runner.get("dry_run_result_parser") or {}
        validation = runner.get("receipt_validation_report") or {}
        source_closeout = (
            readiness.get("source_controlled_dry_run_receipt_closeout") or {}
        )
        source_future_verification = (
            readiness.get(
                "source_database_apply_controlled_dry_run_result_parser_verification"
            )
            or {}
        )
        source_closeout_contract = (
            readiness.get("source_controlled_dry_run_receipt_closeout_contract")
            or {}
        )
        result = str(readiness.get("result") or "UNKNOWN")

        def _count(key: str) -> int:
            return int(summary.get(key) or 0)

        ready_count = _count("controlled_dry_run_runner_readiness_ready_count")
        check_count = _count("controlled_dry_run_runner_readiness_check_count")
        pass_count = _count("controlled_dry_run_runner_readiness_pass_count")
        waiting_count = _count("controlled_dry_run_runner_readiness_waiting_count")
        receipt_closeout_ready_count = _count(
            "controlled_dry_run_receipt_closeout_ready_count"
        )
        receipt_closeout_check_count = _count(
            "controlled_dry_run_receipt_closeout_check_count"
        )
        package_ready_count = _count("controlled_dry_run_package_ready_count")
        package_check_count = _count("controlled_dry_run_package_check_count")
        controlled_apply_ready_count = _count(
            "controlled_apply_final_preflight_ready_count"
        )
        controlled_apply_check_count = _count(
            "controlled_apply_final_preflight_check_count"
        )
        evidence_closeout_ready_count = _count(
            "authorization_evidence_execution_closeout_ready_count"
        )
        evidence_closeout_check_count = _count(
            "authorization_evidence_execution_closeout_check_count"
        )
        evidence_preflight_ready_count = _count(
            "authorization_evidence_execution_preflight_ready_count"
        )
        evidence_preflight_check_count = _count(
            "authorization_evidence_execution_preflight_check_count"
        )
        final_verifier_gate_count = _count("database_apply_final_verifier_gate_count")
        final_verifier_gate_ready_count = _count(
            "database_apply_authorization_final_verifier_gate_ready_count"
        )
        runner_count = _count("controlled_dry_run_runner_readiness_count")
        runner_field_count = _count("controlled_dry_run_runner_readiness_field_count")
        runner_gate_count = _count(
            "controlled_dry_run_runner_readiness_acceptance_gate_count"
        )
        execution_plan_count = _count("execution_plan_binding_count")
        execution_plan_field_count = _count("execution_plan_binding_field_count")
        parser_count = _count("dry_run_result_parser_count")
        parser_field_count = _count("dry_run_result_parser_field_count")
        validation_report_count = _count("receipt_validation_report_count")
        validation_field_count = _count("receipt_validation_field_count")
        receipt_closeout_count = _count("controlled_dry_run_receipt_closeout_count")
        receipt_closeout_field_count = _count(
            "controlled_dry_run_receipt_closeout_field_count"
        )
        receipt_closeout_gate_count = _count(
            "controlled_dry_run_receipt_closeout_acceptance_gate_count"
        )
        rollback_binding_count = _count("rollback_binding_count")
        verifier_binding_count = _count("post_apply_verifier_binding_count")
        verifier_required_count = _count("post_apply_verifier_required_count")
        same_run_truth_count = _count("same_run_truth_required_count")
        writes_script_count = _count("writes_script_count")
        writes_artifact_count = _count("writes_artifact_count")
        reads_secret_count = _count("reads_secret_count")
        executes_script_count = _count("executes_script_count")
        executes_migration_count = _count("executes_migration_count")
        executes_endpoint_count = _count("executes_endpoint_count")
        executes_sql_count = _count("executes_sql_count")
        writes_database_count = _count("writes_database_count")
        signs_database_apply_authorization_count = _count(
            "signs_database_apply_authorization_count"
        )
        primary_human_gate_count = _count(PRIMARY_HUMAN_GATE_COUNT_KEY)
        manual_review_required_count = _count(LEGACY_REVIEW_REQUIRED_COUNT_KEY)
        side_effect_count = (
            writes_script_count
            + writes_artifact_count
            + reads_secret_count
            + executes_script_count
            + executes_migration_count
            + executes_endpoint_count
            + executes_sql_count
            + writes_database_count
            + signs_database_apply_authorization_count
        )
        risk_detected = any(
            [
                side_effect_count,
                primary_human_gate_count,
                manual_review_required_count,
                safety.get("reads_secret_in_preview") is not False,
                safety.get("writes_file") is not False,
                safety.get("writes_script_in_preview") is not False,
                safety.get("writes_artifact_in_preview") is not False,
                safety.get("executes_script") is not False,
                safety.get("executes_endpoint") is not False,
                safety.get("executes_migration") is not False,
                safety.get("executes_sql") is not False,
                safety.get("writes_database") is not False,
                safety.get("signs_database_apply_authorization") is not False,
                safety.get("performs_detached_signature_verification") is not False,
                safety.get("persists_verifier_receipt") is not False,
                safety.get("executes_authorization_evidence") is not False,
                safety.get("executes_database_apply") is not False,
                future_plan.get("dry_run_execution_performed") is not False,
                future_plan.get("runner_execution_authorized") is not False,
                future_plan.get("dry_run_execution_authorized") is not False,
                future_plan.get("ready_for_database_apply_now") is not False,
                future_plan.get("database_apply_authorized") is not False,
                future_plan.get("issues_database_apply_authorization") is not False,
                future_plan.get("signs_database_apply_authorization") is not False,
                future_plan.get("executes_authorization_evidence") is not False,
                future_plan.get("executes_database_apply") is not False,
                future_plan.get("executes_endpoint") is not False,
                future_plan.get("executes_sql") is not False,
                future_plan.get("writes_database") is not False,
                future_plan.get("reads_secret_in_preview") is not False,
                runner.get("runner_execution_authorized") is not False,
                runner.get("dry_run_execution_authorized") is not False,
                runner.get("ready_for_database_apply_now") is not False,
                runner.get("database_apply_authorized") is not False,
                runner.get("issues_database_apply_authorization") is not False,
                runner.get("signs_database_apply_authorization") is not False,
                runner.get("accepts_plaintext_secret") is not False,
                runner.get("reads_secret_in_preview") is not False,
                runner.get("signature_material_included") is not False,
                runner.get("secret_material_included") is not False,
                runner.get("executes_authorization_evidence") is not False,
                runner.get("executes_database_apply") is not False,
                runner.get("executes_endpoint_in_preview") is not False,
                runner.get("executes_sql_in_preview") is not False,
                runner.get("writes_database_in_preview") is not False,
                execution_plan.get("execution_authorized") is not False,
                execution_plan.get("dry_run_execution_authorized") is not False,
                execution_plan.get("runner_execution_authorized") is not False,
                execution_plan.get("shell_execution_included") is not False,
                execution_plan.get("endpoint_execution_included") is not False,
                execution_plan.get("sql_execution_included") is not False,
                execution_plan.get("database_write_included") is not False,
                execution_plan.get("stdout_capture_allowed") is not False,
                execution_plan.get("stderr_capture_allowed") is not False,
                execution_plan.get("database_apply_authorized") is not False,
                execution_plan.get("ready_for_database_apply_now") is not False,
                validation.get("execution_performed") is not False,
                validation.get("stdout_included") is not False,
                validation.get("stderr_included") is not False,
                validation.get("database_apply_authorized") is not False,
                validation.get("executes_shell") is not False,
                validation.get("executes_endpoint") is not False,
                validation.get("executes_sql") is not False,
                validation.get("writes_database") is not False,
                validation.get("reads_secret") is not False,
                result_parser.get("execution_required") is not False,
                result_parser.get("stdout_allowed") is not False,
                result_parser.get("stderr_allowed") is not False,
                result_parser.get("database_apply_authorized") is not False,
                source_closeout_contract.get(
                    "permits_future_database_apply_controlled_dry_run_runner_readiness"
                )
                is not True,
                contract.get("accepts_plaintext_secret") is not False,
                contract.get("performs_detached_signature_verification") is not False,
                contract.get("persists_verifier_receipt") is not False,
                contract.get("executes_authorization_evidence") is not False,
                contract.get("executes_database_apply") is not False,
                contract.get("executes_endpoint") is not False,
                contract.get("executes_sql") is not False,
                contract.get("issues_database_apply_authorization") is not False,
                contract.get("database_apply_authorized") is not False,
                contract.get("ready_for_database_apply_now") is not False,
                contract.get("signs_database_apply_authorization") is not False,
                contract.get("writes_database") is not False,
                contract.get("executes_in_preview") is not False,
                contract.get("secret_material_required_in_preview") is not False,
            ]
        )
        runner_contract_present = (
            result == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_READY"
            and ready_count == 1
            and check_count >= 12
            and pass_count == check_count
            and waiting_count == 0
            and receipt_closeout_ready_count == 1
            and receipt_closeout_check_count == 12
            and package_ready_count == 1
            and package_check_count == 12
            and controlled_apply_ready_count == 1
            and controlled_apply_check_count == 12
            and evidence_closeout_ready_count == 1
            and evidence_closeout_check_count == 12
            and evidence_preflight_ready_count == 1
            and evidence_preflight_check_count == 12
            and final_verifier_gate_count == 1
            and final_verifier_gate_ready_count == 1
            and runner_count == 1
            and runner_field_count == 12
            and runner_gate_count == 10
            and execution_plan_count == 1
            and execution_plan_field_count == 12
            and parser_count == 1
            and parser_field_count == 10
            and validation_report_count == 1
            and validation_field_count == 8
            and receipt_closeout_count == 1
            and receipt_closeout_field_count == 12
            and receipt_closeout_gate_count == 10
            and rollback_binding_count == 1
            and verifier_binding_count == 1
            and verifier_required_count == 1
            and same_run_truth_count == 1
            and future_plan.get(
                "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding"
            )
            is True
            and future_plan.get(
                "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout"
            )
            is True
            and future_plan.get("controlled_dry_run_runner_readiness_ready") is True
            and future_plan.get("execution_plan_bound") is True
            and future_plan.get("dry_run_execution_performed") is False
            and future_plan.get("runner_execution_authorized") is False
            and future_plan.get("dry_run_execution_authorized") is False
            and source_future_verification.get(
                "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True
            and source_future_verification.get("dry_run_execution_performed")
            is False
            and runner.get("authorization_material_type")
            == "controlled_dry_run_runner_readiness"
            and runner.get(
                "ready_for_future_database_apply_controlled_dry_run_runner_readiness"
            )
            is True
            and runner.get("target_migration_hash_locked") is True
            and runner.get("dry_run_only") is True
            and runner.get("check_mode_only") is True
            and runner.get("runner_readiness_only") is True
            and runner.get("execution_plan_preview_only") is True
            and runner.get("requires_fresh_production_truth_in_same_run") is True
            and runner.get("requires_post_apply_verifier") is True
            and execution_plan.get("runner_mode")
            == "future_controlled_dry_run_runner_readiness_only"
            and execution_plan.get("plan_status")
            == "plan_binding_preview_not_executable"
            and execution_plan.get("dry_run_only") is True
            and execution_plan.get("check_mode_only") is True
            and execution_plan.get("execution_authorized") is False
            and execution_plan.get("dry_run_execution_authorized") is False
            and execution_plan.get("runner_execution_authorized") is False
            and execution_plan.get("shell_execution_included") is False
            and execution_plan.get("endpoint_execution_included") is False
            and execution_plan.get("sql_execution_included") is False
            and execution_plan.get("database_write_included") is False
            and execution_plan.get("stdout_capture_allowed") is False
            and execution_plan.get("stderr_capture_allowed") is False
            and execution_plan.get("database_apply_authorized") is False
            and execution_plan.get("ready_for_database_apply_now") is False
            and validation.get("receipt_validation_status")
            == "preview_validated_not_executed"
            and validation.get("execution_performed") is False
            and validation.get("stdout_included") is False
            and validation.get("stderr_included") is False
            and validation.get("database_apply_authorized") is False
            and validation.get("executes_shell") is False
            and validation.get("executes_endpoint") is False
            and validation.get("executes_sql") is False
            and validation.get("writes_database") is False
            and validation.get("reads_secret") is False
            and result_parser.get("expected_receipt_status")
            == "preview_only_not_executed"
            and result_parser.get("execution_required") is False
            and result_parser.get("parser_verification_status")
            == "schema_preview_ready"
            and contract.get("machine_verifiable") is True
            and contract.get(
                "permits_future_database_apply_controlled_dry_run_execution_plan_binding"
            )
            is True
            and contract.get("manual_review_mode") == "exception_only"
            and safety.get("manual_review_mode") == "exception_only"
        )

        if risk_detected:
            status = "critical"
            summary_text = (
                "PChome auto-policy controlled dry-run runner readiness "
                "偵測到 secret、runner execution、stdout/stderr、SQL、DB write、"
                "database apply、簽發授權或人工主 gate 風險"
            )
            next_machine_action = (
                "halt_pchome_auto_policy_controlled_dry_run_runner_readiness_and_inspect_risk"
            )
        elif runner_contract_present:
            status = "ok"
            summary_text = (
                "PChome auto-policy controlled dry-run runner readiness "
                f"已自動完成 {pass_count}/{check_count} checks，execution plan 已綁定且不可執行，runner/write/apply=0"
            )
            next_machine_action = (
                "continue_to_pchome_auto_policy_controlled_dry_run_execution_plan_closeout_lane"
            )
        else:
            status = "warning"
            summary_text = (
                "PChome auto-policy controlled dry-run runner readiness "
                "尚未達自動監控契約"
            )
            next_machine_action = (
                "refresh_pchome_auto_policy_controlled_dry_run_runner_readiness"
            )

        return _check(
            "PChome auto-policy controlled dry-run runner readiness",
            status,
            summary_text,
            {
                "policy": readiness.get("policy"),
                "result": result,
                "source_policy": readiness.get("source_policy"),
                "controlled_dry_run_runner_readiness_ready_count": ready_count,
                "controlled_dry_run_runner_readiness_check_count": check_count,
                "controlled_dry_run_runner_readiness_pass_count": pass_count,
                "controlled_dry_run_runner_readiness_waiting_count": waiting_count,
                "controlled_dry_run_receipt_closeout_ready_count": (
                    receipt_closeout_ready_count
                ),
                "controlled_dry_run_receipt_closeout_check_count": (
                    receipt_closeout_check_count
                ),
                "controlled_dry_run_package_ready_count": package_ready_count,
                "controlled_dry_run_package_check_count": package_check_count,
                "controlled_apply_final_preflight_ready_count": (
                    controlled_apply_ready_count
                ),
                "controlled_apply_final_preflight_check_count": (
                    controlled_apply_check_count
                ),
                "authorization_evidence_execution_closeout_ready_count": (
                    evidence_closeout_ready_count
                ),
                "authorization_evidence_execution_closeout_check_count": (
                    evidence_closeout_check_count
                ),
                "authorization_evidence_execution_preflight_ready_count": (
                    evidence_preflight_ready_count
                ),
                "authorization_evidence_execution_preflight_check_count": (
                    evidence_preflight_check_count
                ),
                "database_apply_final_verifier_gate_count": final_verifier_gate_count,
                "database_apply_authorization_final_verifier_gate_ready_count": (
                    final_verifier_gate_ready_count
                ),
                "controlled_dry_run_runner_readiness_count": runner_count,
                "controlled_dry_run_runner_readiness_field_count": runner_field_count,
                "controlled_dry_run_runner_readiness_acceptance_gate_count": (
                    runner_gate_count
                ),
                "execution_plan_binding_count": execution_plan_count,
                "execution_plan_binding_field_count": execution_plan_field_count,
                "dry_run_result_parser_count": parser_count,
                "dry_run_result_parser_field_count": parser_field_count,
                "receipt_validation_report_count": validation_report_count,
                "receipt_validation_field_count": validation_field_count,
                "controlled_dry_run_receipt_closeout_count": receipt_closeout_count,
                "controlled_dry_run_receipt_closeout_field_count": (
                    receipt_closeout_field_count
                ),
                "controlled_dry_run_receipt_closeout_acceptance_gate_count": (
                    receipt_closeout_gate_count
                ),
                "rollback_binding_count": rollback_binding_count,
                "post_apply_verifier_binding_count": verifier_binding_count,
                "post_apply_verifier_required_count": verifier_required_count,
                "same_run_truth_required_count": same_run_truth_count,
                "writes_script_count": writes_script_count,
                "writes_artifact_count": writes_artifact_count,
                "reads_secret_count": reads_secret_count,
                "executes_script_count": executes_script_count,
                "executes_migration_count": executes_migration_count,
                "executes_endpoint_count": executes_endpoint_count,
                "executes_sql_count": executes_sql_count,
                "writes_database_count": writes_database_count,
                "signs_database_apply_authorization_count": (
                    signs_database_apply_authorization_count
                ),
                "primary_human_gate_count": primary_human_gate_count,
                "manual_review_required_count": manual_review_required_count,
                "manual_review_mode": safety.get("manual_review_mode"),
                "payload_source": "local_contract_fixture",
                "machine_fetch_evidence_source": "local_schema_fixture",
                "http_get_adapter": "_pchome_auto_policy_machine_fetch_evidence_get",
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding": bool(
                    future_plan.get(
                        "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding"
                    )
                ),
                "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout": bool(
                    future_plan.get(
                        "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout"
                    )
                ),
                "controlled_dry_run_runner_readiness_ready": bool(
                    future_plan.get("controlled_dry_run_runner_readiness_ready")
                ),
                "execution_plan_bound": bool(future_plan.get("execution_plan_bound")),
                "source_controlled_dry_run_receipt_closeout_ready": bool(
                    source_future_verification.get(
                        "controlled_dry_run_receipt_closeout_ready"
                    )
                ),
                "dry_run_execution_performed": bool(
                    future_plan.get("dry_run_execution_performed")
                    or source_future_verification.get("dry_run_execution_performed")
                ),
                "ready_for_future_database_apply_controlled_dry_run_runner_readiness": bool(
                    runner.get(
                        "ready_for_future_database_apply_controlled_dry_run_runner_readiness"
                    )
                ),
                "target_migration_hash_locked": bool(
                    runner.get("target_migration_hash_locked")
                    or source_closeout.get("target_migration_hash_locked")
                ),
                "dry_run_only": bool(runner.get("dry_run_only")),
                "check_mode_only": bool(runner.get("check_mode_only")),
                "runner_readiness_only": bool(runner.get("runner_readiness_only")),
                "execution_plan_preview_only": bool(
                    runner.get("execution_plan_preview_only")
                ),
                "requires_fresh_production_truth": bool(
                    runner.get("requires_fresh_production_truth_in_same_run")
                ),
                "requires_post_apply_verifier": bool(
                    runner.get("requires_post_apply_verifier")
                ),
                "execution_plan_runner_mode": execution_plan.get("runner_mode"),
                "execution_plan_status": execution_plan.get("plan_status"),
                "execution_authorized": bool(
                    execution_plan.get("execution_authorized")
                ),
                "dry_run_execution_authorized": bool(
                    execution_plan.get("dry_run_execution_authorized")
                    or future_plan.get("dry_run_execution_authorized")
                    or runner.get("dry_run_execution_authorized")
                ),
                "runner_execution_authorized": bool(
                    execution_plan.get("runner_execution_authorized")
                    or future_plan.get("runner_execution_authorized")
                    or runner.get("runner_execution_authorized")
                ),
                "shell_execution_included": bool(
                    execution_plan.get("shell_execution_included")
                ),
                "endpoint_execution_included": bool(
                    execution_plan.get("endpoint_execution_included")
                ),
                "sql_execution_included": bool(
                    execution_plan.get("sql_execution_included")
                ),
                "database_write_included": bool(
                    execution_plan.get("database_write_included")
                ),
                "stdout_capture_allowed": bool(
                    execution_plan.get("stdout_capture_allowed")
                ),
                "stderr_capture_allowed": bool(
                    execution_plan.get("stderr_capture_allowed")
                ),
                "receipt_validation_status": validation.get(
                    "receipt_validation_status"
                ),
                "validation_execution_performed": bool(
                    validation.get("execution_performed")
                ),
                "validation_stdout_included": bool(validation.get("stdout_included")),
                "validation_stderr_included": bool(validation.get("stderr_included")),
                "validation_database_apply_authorized": bool(
                    validation.get("database_apply_authorized")
                ),
                "validation_executes_shell": bool(validation.get("executes_shell")),
                "validation_executes_endpoint": bool(
                    validation.get("executes_endpoint")
                ),
                "validation_executes_sql": bool(validation.get("executes_sql")),
                "validation_writes_database": bool(validation.get("writes_database")),
                "validation_reads_secret": bool(validation.get("reads_secret")),
                "parser_expected_receipt_status": result_parser.get(
                    "expected_receipt_status"
                ),
                "parser_execution_required": bool(
                    result_parser.get("execution_required")
                ),
                "parser_stdout_allowed": bool(result_parser.get("stdout_allowed")),
                "parser_stderr_allowed": bool(result_parser.get("stderr_allowed")),
                "parser_database_apply_authorized": bool(
                    result_parser.get("database_apply_authorized")
                ),
                "parser_verification_status": result_parser.get(
                    "parser_verification_status"
                ),
                "permits_future_database_apply_controlled_dry_run_execution_plan_binding": bool(
                    contract.get(
                        "permits_future_database_apply_controlled_dry_run_execution_plan_binding"
                    )
                ),
                "accepts_plaintext_secret": bool(
                    runner.get("accepts_plaintext_secret")
                    or contract.get("accepts_plaintext_secret")
                ),
                "reads_secret_in_preview": bool(
                    runner.get("reads_secret_in_preview")
                    or safety.get("reads_secret_in_preview")
                ),
                "signature_material_included": bool(
                    runner.get("signature_material_included")
                ),
                "secret_material_included": bool(
                    runner.get("secret_material_included")
                ),
                "secret_material_required_in_preview": bool(
                    contract.get("secret_material_required_in_preview")
                ),
                "executes_authorization_evidence": bool(
                    future_plan.get("executes_authorization_evidence")
                    or runner.get("executes_authorization_evidence")
                    or contract.get("executes_authorization_evidence")
                    or safety.get("executes_authorization_evidence")
                ),
                "executes_database_apply": bool(
                    future_plan.get("executes_database_apply")
                    or runner.get("executes_database_apply")
                    or contract.get("executes_database_apply")
                    or safety.get("executes_database_apply")
                ),
                "executes_endpoint": bool(
                    future_plan.get("executes_endpoint")
                    or contract.get("executes_endpoint")
                    or safety.get("executes_endpoint")
                ),
                "executes_sql": bool(
                    future_plan.get("executes_sql")
                    or contract.get("executes_sql")
                    or safety.get("executes_sql")
                ),
                "ready_for_database_apply_now": bool(
                    future_plan.get("ready_for_database_apply_now")
                    or runner.get("ready_for_database_apply_now")
                    or execution_plan.get("ready_for_database_apply_now")
                    or contract.get("ready_for_database_apply_now")
                ),
                "database_apply_authorized": bool(
                    future_plan.get("database_apply_authorized")
                    or runner.get("database_apply_authorized")
                    or execution_plan.get("database_apply_authorized")
                    or contract.get("database_apply_authorized")
                ),
                "issues_database_apply_authorization": bool(
                    future_plan.get("issues_database_apply_authorization")
                    or runner.get("issues_database_apply_authorization")
                    or contract.get("issues_database_apply_authorization")
                ),
                "signs_database_apply_authorization": bool(
                    future_plan.get("signs_database_apply_authorization")
                    or runner.get("signs_database_apply_authorization")
                    or contract.get("signs_database_apply_authorization")
                ),
                "writes_database": False,
                "next_machine_action": next_machine_action,
            },
        )
    except Exception as exc:
        return _check(
            "PChome auto-policy controlled dry-run runner readiness",
            "warning",
            (
                "PChome auto-policy controlled dry-run runner readiness "
                f"例行監控暫時無法讀取：{exc}"
            ),
            {
                "writes_database": False,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "execute_fetch": True,
                "outbound_network": False,
                "business_data_source": False,
                "payload_source": "local_contract_fixture",
                "next_machine_action": (
                    "refresh_pchome_auto_policy_controlled_dry_run_runner_readiness"
                ),
            },
        )


def _ai_surface_html_readback_check() -> Dict[str, Any]:
    """Read-only AI product surface guardrail readback."""
    try:
        from services.ai_surface_html_readback_service import build_ai_surface_html_readback

        readback = build_ai_surface_html_readback()
        summary = readback.get("summary") or {}
        checked_count = int(summary.get("checked_surface_count") or 0)
        pass_count = int(summary.get("pass_count") or 0)
        failed_count = int(summary.get("failed_count") or 0)
        leak_count = int(summary.get("forbidden_leak_count") or 0)
        status = "ok" if readback.get("status") == "ok" else "critical"
        summary_text = (
            f"AI surface HTML readback 通過 {pass_count}/{checked_count}，無產品面 raw wording"
            if status == "ok"
            else f"AI surface HTML readback 偵測 {failed_count} 個頁面退化 / {leak_count} 個 raw wording"
        )
        return _check(
            "AI surface HTML readback",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "checked_surface_count": checked_count,
                "pass_count": pass_count,
                "failed_count": failed_count,
                "forbidden_leak_count": leak_count,
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "AI surface HTML readback",
            "critical",
            f"AI surface HTML readback 無法執行：{exc}",
            {
                "writes_database": False,
                "primary_human_gate_count": 0,
            },
        )


def _sitewide_ui_ux_agent_check() -> Dict[str, Any]:
    """Read-only sitewide professional UI/UX regression sentinel."""
    try:
        from services.ai_surface_html_readback_service import (
            build_sitewide_ui_ux_agent_inventory,
            build_sitewide_ui_ux_repair_package,
        )

        inventory = build_sitewide_ui_ux_agent_inventory()
        repair_package = build_sitewide_ui_ux_repair_package(source_inventory=inventory, limit=5)
        summary = inventory.get("summary") or {}
        package_summary = repair_package.get("summary") or {}
        issue_count = int(summary.get("issue_surface_count") or 0)
        raw_issue_count = int(summary.get("raw_engineering_issue_count") or 0)
        write_count = int(summary.get("writes_database_count") or 0) + int(
            package_summary.get("writes_database_count") or 0
        )
        repair_action_count = int(package_summary.get("controlled_action_count") or 0)
        status = "ok"
        if write_count:
            status = "critical"
        elif issue_count or raw_issue_count or repair_action_count:
            status = "critical"
        summary_text = (
            "Sitewide UI/UX Agent ok/no-op，整站專業化 surface 無退化"
            if status == "ok"
            else (
                f"Sitewide UI/UX Agent 偵測 {issue_count} 個待修 surface、"
                f"{raw_issue_count} 個 raw wording、{repair_action_count} 個待套用 action"
            )
        )
        return _check(
            "Sitewide UI/UX Agent readback",
            status,
            summary_text,
            {
                "policy": inventory.get("policy"),
                "inventory_status": inventory.get("status"),
                "template_count": int(summary.get("template_count") or 0),
                "high_priority_template_count": int(summary.get("high_priority_template_count") or 0),
                "compact_guardrail_count": int(summary.get("compact_guardrail_count") or 0),
                "issue_surface_count": issue_count,
                "raw_engineering_issue_count": raw_issue_count,
                "next_machine_action": inventory.get("next_machine_action"),
                "repair_package_policy": repair_package.get("policy"),
                "repair_package_status": repair_package.get("status"),
                "repair_action_count": repair_action_count,
                "repair_next_machine_action": repair_package.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": write_count,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "Sitewide UI/UX Agent readback",
            "critical",
            f"Sitewide UI/UX Agent 無法執行：{exc}",
            {
                "writes_database": False,
                "primary_human_gate_count": 0,
            },
        )


def _sitewide_visual_qa_check() -> Dict[str, Any]:
    """Read-only sentinel for latest desktop/tablet/mobile visual QA artifact."""
    try:
        from services.ai_surface_html_readback_service import build_sitewide_visual_qa_readback

        readback = build_sitewide_visual_qa_readback()
        summary = readback.get("summary") or {}
        status = readback.get("status") or "warning"
        failed_count = int(summary.get("failed_count") or 0)
        route_count = int(summary.get("route_count") or 0)
        viewport_count = int(summary.get("viewport_count") or 0)
        summary_text = (
            f"Sitewide visual QA ok，{route_count} routes x {viewport_count} viewports 無 overflow 退化"
            if status == "ok"
            else (
                f"Sitewide visual QA 需更新或修復：failed={failed_count}、"
                f"routes={route_count}、stale={bool(summary.get('stale'))}"
            )
        )
        return _check(
            "Sitewide visual QA readback",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "result_count": int(summary.get("result_count") or 0),
                "route_count": route_count,
                "viewport_count": viewport_count,
                "pass_count": int(summary.get("pass_count") or 0),
                "failed_count": failed_count,
                "overflow_issue_count": int(summary.get("overflow_issue_count") or 0),
                "visual_offender_count": int(summary.get("visual_offender_count") or 0),
                "artifact_path": readback.get("artifact_path"),
                "artifact_exists": bool(readback.get("artifact_exists")),
                "artifact_generated_at": readback.get("artifact_generated_at"),
                "age_hours": summary.get("age_hours"),
                "stale": bool(summary.get("stale")),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "Sitewide visual QA readback",
            "critical",
            f"Sitewide visual QA readback 無法執行：{exc}",
            {
                "writes_database": False,
                "primary_human_gate_count": 0,
            },
        )


def _latest_sitewide_visual_qa_readback_check() -> Dict[str, Any]:
    """Read the latest visual QA artifact for scheduled summaries without running smoke."""
    try:
        from services.ai_surface_html_readback_service import build_sitewide_visual_qa_readback

        readback = build_sitewide_visual_qa_readback()
        summary = readback.get("summary") or {}
        status = readback.get("status") or "warning"
        route_count = int(summary.get("route_count") or 0)
        viewport_count = int(summary.get("viewport_count") or 0)
        failed_count = int(summary.get("failed_count") or 0)
        return _check(
            "Sitewide visual QA readback",
            status,
            (
                f"Sitewide visual QA ok，{route_count} routes x {viewport_count} viewports 無 overflow 退化"
                if status == "ok"
                else (
                    f"Sitewide visual QA 需更新或修復：failed={failed_count}、"
                    f"routes={route_count}、stale={bool(summary.get('stale'))}"
                )
            ),
            {
                "policy": readback.get("policy"),
                "result_count": int(summary.get("result_count") or 0),
                "route_count": route_count,
                "viewport_count": viewport_count,
                "pass_count": int(summary.get("pass_count") or 0),
                "failed_count": failed_count,
                "overflow_issue_count": int(summary.get("overflow_issue_count") or 0),
                "visual_offender_count": int(summary.get("visual_offender_count") or 0),
                "artifact_path": readback.get("artifact_path"),
                "artifact_exists": bool(readback.get("artifact_exists")),
                "artifact_generated_at": readback.get("artifact_generated_at"),
                "age_hours": summary.get("age_hours"),
                "stale": bool(summary.get("stale")),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "Sitewide visual QA readback",
            "warning",
            f"Sitewide visual QA artifact fallback 無法讀取：{exc}",
            {
                "writes_database": False,
                "primary_human_gate_count": 0,
            },
        )


def _external_mcp_rag_integration_check() -> Dict[str, Any]:
    """Read-only sentinel for external MCP/RAG registry and runtime flags."""
    try:
        from services.external_mcp_rag_integration_service import (
            build_external_mcp_rag_integration_readback,
        )

        readback = build_external_mcp_rag_integration_readback()
        completion = readback.get("completion") or {}
        runtime = readback.get("runtime") or {}
        env_flags = runtime.get("env_flags") or {}
        mcp_runtime = runtime.get("mcp") or {}
        rag_runtime = runtime.get("rag") or {}
        unresolved_count = int(completion.get("unresolved_count") or 0)
        absorbed_count = int(completion.get("absorbed_count") or 0)
        total_capabilities = int(completion.get("total_capabilities") or 0)
        mcp_enabled = bool(env_flags.get("MCP_ROUTER_ENABLED") or mcp_runtime.get("enabled"))
        rag_enabled = bool(env_flags.get("RAG_ENABLED") or rag_runtime.get("enabled"))
        fully_integrated = readback.get("status") == "fully_integrated"
        status = "ok" if fully_integrated and mcp_enabled and rag_enabled else "warning"
        summary = (
            f"External MCP/RAG registry {absorbed_count}/{total_capabilities} absorbed; "
            f"unresolved={unresolved_count}; runtime mcp={mcp_enabled} rag={rag_enabled}"
        )
        return _check(
            "External MCP/RAG integration readback",
            status,
            summary,
            {
                "policy": readback.get("policy"),
                "integration_status": readback.get("status"),
                "total_capabilities": total_capabilities,
                "absorbed_count": absorbed_count,
                "unresolved_count": unresolved_count,
                "mcp_router_enabled": mcp_enabled,
                "rag_enabled": rag_enabled,
                "gemini_hard_disabled": bool(env_flags.get("GEMINI_API_HARD_DISABLED")),
                "mcp_caller_count": int(mcp_runtime.get("caller_count") or 0),
                "rag_vector_store": rag_runtime.get("vector_store"),
                "next_machine_action": (
                    "keep_external_mcp_rag_runtime_monitoring"
                    if status == "ok"
                    else "complete_mcp_router_health_and_rag_runtime_enablement"
                ),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "External MCP/RAG integration readback",
            "critical",
            f"External MCP/RAG integration readback 無法執行：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_rag_candidate_replay_check() -> Dict[str, Any]:
    """Read-only sentinel for PixelRAG receipts becoming internal RAG candidates."""
    try:
        from services.pixelrag_rag_candidate_replay_service import (
            build_pixelrag_rag_candidate_replay_readback,
        )

        readback = build_pixelrag_rag_candidate_replay_readback()
        summary = readback.get("summary") or {}
        receipt_count = int(summary.get("receipt_count") or 0)
        eligible_count = int(summary.get("eligible_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        invalid_count = int(summary.get("invalid_count") or 0)
        visual_barrier_count = int(summary.get("visual_barrier_count") or 0)
        worker_receipt_count = int(summary.get("platform_probe_worker_receipt_count") or 0)
        source_contract_fallback_count = int(summary.get("source_contract_fallback_count") or 0)
        capture_runtime_gap_count = int(summary.get("capture_runtime_gap_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG RAG candidate replay receipts={receipt_count}, "
            f"eligible={eligible_count}, blocked={blocked_count}, invalid={invalid_count}, "
            f"barriers={visual_barrier_count}, worker_receipts={worker_receipt_count}, "
            f"source_contract_fallback={source_contract_fallback_count}"
        )
        return _check(
            "PixelRAG RAG candidate replay",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "receipt_count": receipt_count,
                "eligible_count": eligible_count,
                "blocked_count": blocked_count,
                "invalid_count": invalid_count,
                "visual_barrier_count": visual_barrier_count,
                "visual_receipt_count": int(summary.get("visual_receipt_count") or 0),
                "platform_probe_worker_receipt_count": worker_receipt_count,
                "source_contract_fallback_count": source_contract_fallback_count,
                "capture_runtime_gap_count": capture_runtime_gap_count,
                "tile_file_count": int(summary.get("tile_file_count") or 0),
                "missing_file_count": int(summary.get("missing_file_count") or 0),
                "stale_count": int(summary.get("stale_count") or 0),
                "blocked_pages_are_not_product_data": bool(
                    (readback.get("replay_contract") or {}).get("blocked_pages_are_not_product_data")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG RAG candidate replay",
            "critical",
            f"PixelRAG RAG candidate replay 無法執行：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_source_contract_replay_worker_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG source-contract replay automation."""
    try:
        from services.pixelrag_source_contract_replay_worker_service import (
            run_pixelrag_source_contract_replay_worker,
        )

        readback = run_pixelrag_source_contract_replay_worker(execute=False)
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG source-contract replay worker candidates={candidate_count}, "
            f"ready={ready_count}, blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}"
        )
        return _check(
            "PixelRAG source-contract replay worker",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG source-contract replay worker",
            "critical",
            f"PixelRAG source-contract replay worker 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_marketplace_adapter_preflight_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG marketplace source-contract adapter preflight."""
    try:
        from services.pixelrag_marketplace_source_contract_adapter_preflight_service import (
            run_pixelrag_marketplace_source_contract_adapter_preflight,
        )

        readback = run_pixelrag_marketplace_source_contract_adapter_preflight(
            execute=False,
        )
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG marketplace adapter preflight candidates={candidate_count}, "
            f"ready={ready_count}, blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}"
        )
        return _check(
            "PixelRAG marketplace adapter preflight",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG marketplace adapter preflight",
            "critical",
            f"PixelRAG marketplace adapter preflight 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_marketplace_adapter_dry_run_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG marketplace adapter deterministic mapping."""
    try:
        from services.pixelrag_marketplace_source_contract_adapter_dry_run_service import (
            run_pixelrag_marketplace_source_contract_adapter_dry_run,
        )

        readback = run_pixelrag_marketplace_source_contract_adapter_dry_run(
            execute=False,
        )
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        field_contract_count = int(summary.get("field_contract_count") or 0)
        output_contract_count = int(summary.get("dry_run_output_contract_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG marketplace adapter dry-run candidates={candidate_count}, "
            f"ready={ready_count}, blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}, "
            f"fields={field_contract_count}, outputs={output_contract_count}"
        )
        return _check(
            "PixelRAG marketplace adapter dry-run",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "field_contract_count": field_contract_count,
                "dry_run_output_contract_count": output_contract_count,
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG marketplace adapter dry-run",
            "critical",
            f"PixelRAG marketplace adapter dry-run 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_marketplace_identity_matcher_replay_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG marketplace identity matcher replay."""
    try:
        from services.pixelrag_marketplace_identity_matcher_replay_service import (
            run_pixelrag_marketplace_identity_matcher_replay,
        )

        readback = run_pixelrag_marketplace_identity_matcher_replay(
            execute=False,
        )
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        identity_candidate_count = int(summary.get("identity_candidate_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG marketplace identity matcher replay candidates={candidate_count}, "
            f"ready={ready_count}, blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}, "
            f"identity_candidates={identity_candidate_count}"
        )
        return _check(
            "PixelRAG marketplace identity matcher replay",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "identity_candidate_count": identity_candidate_count,
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG marketplace identity matcher replay",
            "critical",
            f"PixelRAG marketplace identity matcher replay 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_marketplace_promotion_gate_replay_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG marketplace PromotionGate replay."""
    try:
        from services.pixelrag_marketplace_promotion_gate_replay_service import (
            run_pixelrag_marketplace_promotion_gate_replay,
        )

        readback = run_pixelrag_marketplace_promotion_gate_replay(
            execute=False,
        )
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        promotion_candidate_count = int(summary.get("promotion_candidate_count") or 0)
        embedding_ready_count = int(
            summary.get("embedding_signature_guard_ready_count") or 0
        )
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG marketplace PromotionGate replay candidates={candidate_count}, "
            f"ready={ready_count}, blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}, "
            f"promotion_candidates={promotion_candidate_count}, "
            f"embedding_ready={embedding_ready_count}"
        )
        return _check(
            "PixelRAG marketplace PromotionGate replay",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "promotion_candidate_count": promotion_candidate_count,
                "embedding_signature_guard_ready_count": embedding_ready_count,
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG marketplace PromotionGate replay",
            "critical",
            f"PixelRAG marketplace PromotionGate replay 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_marketplace_embedding_signature_guard_replay_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG marketplace embedding signature guard."""
    try:
        from services.pixelrag_marketplace_embedding_signature_guard_replay_service import (
            run_pixelrag_marketplace_embedding_signature_guard_replay,
        )

        readback = run_pixelrag_marketplace_embedding_signature_guard_replay(
            execute=False,
        )
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        signature_candidate_count = int(
            summary.get("signature_guard_candidate_count") or 0
        )
        knowledge_ready_count = int(
            summary.get("candidate_knowledge_ready_count") or 0
        )
        signatures = list(summary.get("expected_embedding_signatures") or [])
        status = readback.get("status") or "warning"
        signature_text = ",".join(str(item) for item in signatures) or "none"
        summary_text = (
            f"PixelRAG marketplace embedding signature guard replay "
            f"candidates={candidate_count}, ready={ready_count}, "
            f"blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}, "
            f"signature_candidates={signature_candidate_count}, "
            f"knowledge_ready={knowledge_ready_count}, signatures={signature_text}"
        )
        return _check(
            "PixelRAG marketplace embedding signature guard replay",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "signature_guard_candidate_count": signature_candidate_count,
                "candidate_knowledge_ready_count": knowledge_ready_count,
                "expected_embedding_signatures": signatures,
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "embedding_generation_performed": bool(
                    summary.get("embedding_generation_performed")
                ),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG marketplace embedding signature guard replay",
            "critical",
            f"PixelRAG marketplace embedding signature guard replay 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_marketplace_candidate_knowledge_replay_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG marketplace candidate knowledge replay."""
    try:
        from services.pixelrag_marketplace_candidate_knowledge_replay_service import (
            run_pixelrag_marketplace_candidate_knowledge_replay,
        )

        readback = run_pixelrag_marketplace_candidate_knowledge_replay(
            execute=False,
        )
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        receipt_written_count = int(summary.get("receipt_written_count") or 0)
        knowledge_candidate_count = int(
            summary.get("knowledge_candidate_count") or 0
        )
        internal_rag_ready_count = int(
            summary.get("internal_rag_ready_count") or 0
        )
        signatures = list(summary.get("expected_embedding_signatures") or [])
        status = readback.get("status") or "warning"
        signature_text = ",".join(str(item) for item in signatures) or "none"
        summary_text = (
            f"PixelRAG marketplace candidate knowledge replay "
            f"candidates={candidate_count}, ready={ready_count}, "
            f"blocked={blocked_count}, dry_run={dry_run_count}, "
            f"executed={executed_count}, receipts={receipt_written_count}, "
            f"knowledge_candidates={knowledge_candidate_count}, "
            f"internal_rag_ready={internal_rag_ready_count}, signatures={signature_text}"
        )
        return _check(
            "PixelRAG marketplace candidate knowledge replay",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "candidate_count": candidate_count,
                "ready_count": ready_count,
                "blocked_count": blocked_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "receipt_written_count": receipt_written_count,
                "capture_runtime_gap_count": int(
                    summary.get("capture_runtime_gap_count") or 0
                ),
                "guard_failed_count": int(summary.get("guard_failed_count") or 0),
                "knowledge_candidate_count": knowledge_candidate_count,
                "internal_rag_ready_count": internal_rag_ready_count,
                "expected_embedding_signatures": signatures,
                "network_call_performed": bool(summary.get("network_call_performed")),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "embedding_generation_performed": bool(
                    summary.get("embedding_generation_performed")
                ),
                "artifact_write_performed": bool(
                    summary.get("artifact_write_performed")
                ),
                "writes_ai_insights": bool(summary.get("writes_ai_insights")),
                "writes_price_tables": bool(summary.get("writes_price_tables")),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG marketplace candidate knowledge replay",
            "critical",
            f"PixelRAG marketplace candidate knowledge replay 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_ocr_vlm_replay_check() -> Dict[str, Any]:
    """Read-only sentinel for PixelRAG receipts becoming OCR/VLM replay contracts."""
    try:
        from services.pixelrag_ocr_vlm_replay_service import (
            build_pixelrag_ocr_vlm_replay_contract,
        )

        readback = build_pixelrag_ocr_vlm_replay_contract()
        summary = readback.get("summary") or {}
        receipt_count = int(summary.get("receipt_count") or 0)
        replay_ready_count = int(summary.get("replay_ready_count") or 0)
        blocked_count = int(summary.get("blocked_count") or 0)
        invalid_count = int(summary.get("invalid_count") or 0)
        field_contract_count = int(summary.get("field_contract_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG OCR/VLM replay contract receipts={receipt_count}, "
            f"ready={replay_ready_count}, blocked={blocked_count}, invalid={invalid_count}, "
            f"field_contracts={field_contract_count}"
        )
        return _check(
            "PixelRAG OCR/VLM replay contract",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "receipt_count": receipt_count,
                "replay_ready_count": replay_ready_count,
                "blocked_count": blocked_count,
                "invalid_count": invalid_count,
                "tile_input_count": int(summary.get("tile_input_count") or 0),
                "missing_tile_count": int(summary.get("missing_tile_count") or 0),
                "field_contract_count": field_contract_count,
                "extraction_execution_performed": bool(
                    summary.get("extraction_execution_performed")
                ),
                "blocked_pages_are_not_product_data": bool(
                    (readback.get("replay_contract") or {}).get("blocked_pages_are_not_product_data")
                ),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG OCR/VLM replay contract",
            "critical",
            f"PixelRAG OCR/VLM replay contract 無法執行：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_vlm_replay_worker_check() -> Dict[str, Any]:
    """Dry-run sentinel for the Ollama-first PixelRAG VLM replay worker."""
    try:
        from services.pixelrag_vlm_replay_worker_service import (
            run_pixelrag_ollama_vlm_replay_worker,
        )

        readback = run_pixelrag_ollama_vlm_replay_worker(execute=False)
        summary = readback.get("summary") or {}
        receipt_count = int(summary.get("receipt_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        dry_run_count = int(summary.get("dry_run_count") or 0)
        skipped_count = int(summary.get("skipped_count") or 0)
        executed_count = int(summary.get("executed_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG VLM replay worker receipts={receipt_count}, "
            f"ready={ready_count}, dry_run={dry_run_count}, skipped={skipped_count}, "
            f"executed={executed_count}"
        )
        return _check(
            "PixelRAG VLM replay worker",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "receipt_count": receipt_count,
                "ready_count": ready_count,
                "skipped_count": skipped_count,
                "dry_run_count": dry_run_count,
                "executed_count": executed_count,
                "executed_ok_count": int(summary.get("executed_ok_count") or 0),
                "executed_warning_count": int(summary.get("executed_warning_count") or 0),
                "model_error_count": int(summary.get("model_error_count") or 0),
                "model_route_not_ready_count": int(summary.get("model_route_not_ready_count") or 0),
                "parse_error_count": int(summary.get("parse_error_count") or 0),
                "receipt_written_count": int(summary.get("receipt_written_count") or 0),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "artifact_write_performed": bool(summary.get("artifact_write_performed")),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG VLM replay worker",
            "critical",
            f"PixelRAG VLM replay worker 無法執行 dry-run：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_vlm_route_readiness_check() -> Dict[str, Any]:
    """Read-only sentinel for approved Ollama VLM route/model readiness."""
    try:
        from services.pixelrag_vlm_route_readiness_service import (
            build_pixelrag_vlm_route_readiness,
        )

        readback = build_pixelrag_vlm_route_readiness(timeout_seconds=3)
        summary = readback.get("summary") or {}
        host_count = int(summary.get("host_count") or 0)
        reachable_host_count = int(summary.get("reachable_host_count") or 0)
        configured_model = summary.get("configured_model")
        configured_available = int(summary.get("configured_model_available_count") or 0)
        candidate_model = summary.get("candidate_model")
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG VLM route readiness hosts={reachable_host_count}/{host_count}, "
            f"configured={configured_model}, configured_available={configured_available}, "
            f"candidate={candidate_model or 'none'}"
        )
        return _check(
            "PixelRAG VLM route readiness",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "host_count": host_count,
                "reachable_host_count": reachable_host_count,
                "configured_model": configured_model,
                "configured_model_available_count": configured_available,
                "candidate_model": candidate_model,
                "candidate_host": summary.get("candidate_host"),
                "candidate_provider": summary.get("candidate_provider"),
                "tag_model_route_ready": bool(summary.get("tag_model_route_ready")),
                "model_route_ready": bool(summary.get("model_route_ready")),
                "generate_probe_performed": bool(summary.get("generate_probe_performed")),
                "generate_probe_ok_count": int(summary.get("generate_probe_ok_count") or 0),
                "generate_route_ready": (
                    summary.get("generate_route_ready")
                    if summary.get("generate_probe_performed")
                    else None
                ),
                "generate_ready_model": summary.get("generate_ready_model"),
                "generate_ready_host": summary.get("generate_ready_host"),
                "generate_ready_provider": summary.get("generate_ready_provider"),
                "model_call_performed": bool(summary.get("model_call_performed")),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG VLM route readiness",
            "critical",
            f"PixelRAG VLM route readiness 無法執行：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_platform_probe_check() -> Dict[str, Any]:
    """Read-only sentinel for PixelRAG platform probe automation readiness."""
    try:
        from services.pixelrag_platform_probe_service import (
            build_pixelrag_platform_probe_readiness,
        )

        readback = build_pixelrag_platform_probe_readiness()
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("probe_candidate_count") or 0)
        ready_count = int(summary.get("ready_for_probe_count") or 0)
        shopee_context_count = int(summary.get("shopee_public_context_probe_count") or 0)
        structured_count = int(summary.get("structured_source_fallback_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG platform probe candidates={candidate_count}, "
            f"ready={ready_count}, shopee_context={shopee_context_count}, "
            f"structured_fallback={structured_count}"
        )
        return _check(
            "PixelRAG platform probe readiness",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "probe_candidate_count": candidate_count,
                "ready_for_probe_count": ready_count,
                "invalid_count": int(summary.get("invalid_count") or 0),
                "capture_source_count": int(summary.get("capture_source_count") or 0),
                "vlm_source_count": int(summary.get("vlm_source_count") or 0),
                "shopee_public_context_probe_count": shopee_context_count,
                "language_or_region_interstitial_count": int(
                    summary.get("language_or_region_interstitial_count") or 0
                ),
                "traffic_verification_count": int(
                    summary.get("traffic_verification_count") or 0
                ),
                "access_denied_count": int(summary.get("access_denied_count") or 0),
                "structured_source_fallback_count": structured_count,
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG platform probe readiness",
            "critical",
            f"PixelRAG platform probe readiness 無法執行：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _pixelrag_platform_probe_worker_check() -> Dict[str, Any]:
    """Dry-run sentinel for PixelRAG platform probe worker automation."""
    try:
        from services.pixelrag_platform_probe_worker_service import (
            run_pixelrag_platform_probe_worker,
        )

        readback = run_pixelrag_platform_probe_worker()
        summary = readback.get("summary") or {}
        candidate_count = int(summary.get("probe_candidate_count") or 0)
        ready_count = int(summary.get("ready_count") or 0)
        capture_ready_count = int(summary.get("capture_ready_count") or 0)
        structured_count = int(summary.get("structured_fallback_count") or 0)
        status = readback.get("status") or "warning"
        summary_text = (
            f"PixelRAG platform probe worker candidates={candidate_count}, "
            f"ready={ready_count}, capture_ready={capture_ready_count}, "
            f"structured_fallback={structured_count}, execute=false"
        )
        return _check(
            "PixelRAG platform probe worker",
            status,
            summary_text,
            {
                "policy": readback.get("policy"),
                "probe_candidate_count": candidate_count,
                "ready_count": ready_count,
                "skipped_count": int(summary.get("skipped_count") or 0),
                "dry_run_count": int(summary.get("dry_run_count") or 0),
                "capture_ready_count": capture_ready_count,
                "capture_execute_count": int(summary.get("capture_execute_count") or 0),
                "capture_ok_count": int(summary.get("capture_ok_count") or 0),
                "capture_error_count": int(summary.get("capture_error_count") or 0),
                "structured_fallback_count": structured_count,
                "executed_structured_count": int(summary.get("executed_structured_count") or 0),
                "executed_count": int(summary.get("executed_count") or 0),
                "receipt_written_count": int(summary.get("receipt_written_count") or 0),
                "network_call_performed": bool(summary.get("network_call_performed")),
                "artifact_write_performed": bool(summary.get("artifact_write_performed")),
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "PixelRAG platform probe worker",
            "critical",
            f"PixelRAG platform probe worker 無法執行：{exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def _security_governance_review_check() -> Dict[str, Any]:
    try:
        from services.security_governance_review_service import (
            build_security_governance_review,
        )

        readback = build_security_governance_review(detail_limit=10)
        completion = readback.get("completion") or {}
        release_gate = readback.get("release_gate") or {}
        blocking_count = int(release_gate.get("blocking_failure_count") or 0)
        status = "critical" if blocking_count else (
            "ok" if readback.get("status") == "complete" else "warning"
        )
        return _check(
            "Security governance automation review",
            status,
            (
                f"Security governance program={completion.get('program_percent', 0)}%, "
                f"asset_fields={completion.get('asset_field_coverage_percent', 0)}%, "
                f"runtime_closure={completion.get('runtime_closure_passed', 0)}/"
                f"{completion.get('runtime_closure_total', 0)}, blocking={blocking_count}"
            ),
            {
                "policy": readback.get("policy"),
                "review_status": readback.get("status"),
                "program_percent": completion.get("program_percent"),
                "asset_field_coverage_percent": completion.get(
                    "asset_field_coverage_percent"
                ),
                "asset_runtime_reconciliation_complete": completion.get(
                    "asset_runtime_reconciliation_complete"
                ),
                "runtime_closure_passed": completion.get("runtime_closure_passed"),
                "runtime_closure_total": completion.get("runtime_closure_total"),
                "blocking_failure_count": blocking_count,
                "next_machine_action": readback.get("next_machine_action"),
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )
    except Exception as exc:
        return _check(
            "Security governance automation review",
            "critical",
            f"Security governance review failed: {exc}",
            {
                "writes_database": False,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
            },
        )


def collect_ai_automation_smoke(*, record_history: bool = True, history_limit: int = 20) -> Dict[str, Any]:
    checks: List[Dict[str, Any]] = [
        _event_router_check(),
        _gemini_egress_check(),
        _autoheal_check(),
        _nemotron_check(),
        _embedding_queue_check(),
        _elephant_hitl_check(),
        _pchome_controlled_apply_drift_monitor_check(),
        _pchome_auto_policy_authorization_guard_check(),
        _pchome_auto_policy_decision_preflight_check(),
        _pchome_auto_policy_decision_closeout_check(),
        _pchome_auto_policy_authorization_issuer_gate_check(),
        _pchome_auto_policy_signing_decision_preflight_check(),
        _pchome_auto_policy_signing_decision_closeout_check(),
        _pchome_auto_policy_signing_issuer_guard_check(),
        _pchome_auto_policy_signing_issuer_closeout_check(),
        _pchome_auto_policy_signing_execution_preflight_check(),
        _pchome_auto_policy_signing_execution_closeout_check(),
        _pchome_auto_policy_signed_receipt_preflight_check(),
        _pchome_auto_policy_signed_receipt_closeout_check(),
        _pchome_auto_policy_signed_receipt_evidence_intake_check(),
        _pchome_auto_policy_detached_verification_evidence_validation_check(),
        _pchome_auto_policy_verifier_receipt_closeout_check(),
        _pchome_auto_policy_authorization_evidence_execution_preflight_check(),
        _pchome_auto_policy_authorization_evidence_execution_closeout_check(),
        _pchome_auto_policy_controlled_apply_final_preflight_check(),
        _pchome_auto_policy_controlled_dry_run_package_check(),
        _pchome_auto_policy_controlled_dry_run_receipt_closeout_check(),
        _pchome_auto_policy_controlled_dry_run_runner_readiness_check(),
        _ai_surface_html_readback_check(),
        _sitewide_ui_ux_agent_check(),
        _sitewide_visual_qa_check(),
        _security_governance_review_check(),
        _external_mcp_rag_integration_check(),
        _pixelrag_rag_candidate_replay_check(),
        _pixelrag_source_contract_replay_worker_check(),
        _pixelrag_marketplace_adapter_preflight_check(),
        _pixelrag_marketplace_adapter_dry_run_check(),
        _pixelrag_marketplace_identity_matcher_replay_check(),
        _pixelrag_marketplace_promotion_gate_replay_check(),
        _pixelrag_marketplace_embedding_signature_guard_replay_check(),
        _pixelrag_marketplace_candidate_knowledge_replay_check(),
        _pixelrag_ocr_vlm_replay_check(),
        _pixelrag_vlm_route_readiness_check(),
        _pixelrag_vlm_replay_worker_check(),
        _pixelrag_platform_probe_check(),
        _pixelrag_platform_probe_worker_check(),
    ]
    worst = max(checks, key=lambda item: STATUS_RANK.get(item["status"], 2))["status"]
    result = {
        "status": worst,
        "version": SYSTEM_VERSION,
        "generated_at": datetime.now().isoformat(timespec="seconds"),
        "checks": checks,
        "summary": {
            "ok": sum(1 for item in checks if item["status"] == "ok"),
            "warning": sum(1 for item in checks if item["status"] == "warning"),
            "critical": sum(1 for item in checks if item["status"] == "critical"),
            "total": len(checks),
        },
    }
    if record_history:
        try:
            _append_history(result)
        except Exception as exc:
            result["history_error"] = str(exc)[:300]
    result["history"] = _history_summary(_load_history(limit=history_limit))
    return result
