import json


def _auto_policy_guard_history_check(status="ok"):
    return {
        "name": "PChome auto-policy authorization guard",
        "status": status,
        "summary": "PChome auto-policy guard 已自動讀回 no-write/no-secret package",
        "details": {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_lane_guard",
            "result": "WAITING_FOR_DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT",
            "guard_ready_count": 0,
            "lane_guard_check_count": 12,
            "lane_guard_pass_count": 11,
            "lane_guard_waiting_count": 1,
            "authorization_request_closeout_ready_count": 0,
            "exact_request_payload_field_count": 10,
            "machine_request_manifest_step_count": 6,
            "lane_entry_requirement_count": 6,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "machine_verifiable": True,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "next_machine_action": "collect_machine_fetch_evidence_for_authorization_guard",
        },
    }


def _auto_policy_decision_preflight_history_check(status="ok"):
    return {
        "name": "PChome auto-policy decision preflight",
        "status": status,
        "summary": "PChome auto-policy decision preflight 已用本機 machine evidence 自動通過",
        "details": {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_preflight",
            "result": "DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_READY",
            "decision_preflight_ready_count": 1,
            "authorization_lane_guard_ready_count": 1,
            "decision_preflight_check_count": 12,
            "decision_preflight_pass_count": 12,
            "decision_preflight_waiting_count": 0,
            "decision_input_requirement_count": 8,
            "decision_rejection_reason_count": 10,
            "machine_fetch_evidence_ready_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "next_machine_action": "continue_to_pchome_auto_policy_decision_closeout_lane",
        },
    }


def _auto_policy_decision_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy decision closeout",
        "status": status,
        "summary": "PChome auto-policy decision closeout 已自動完成",
        "details": {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_closeout",
            "result": "DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_READY",
            "decision_closeout_ready_count": 1,
            "decision_preflight_ready_count": 1,
            "decision_closeout_check_count": 12,
            "decision_closeout_pass_count": 12,
            "decision_closeout_waiting_count": 0,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "permits_future_authorization_decision_lane": True,
            "next_machine_action": "continue_to_pchome_auto_policy_authorization_issuer_gate",
        },
    }


def _auto_policy_authorization_issuer_gate_history_check(status="ok"):
    return {
        "name": "PChome auto-policy authorization issuer gate",
        "status": status,
        "summary": "PChome auto-policy authorization issuer gate 已自動完成",
        "details": {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_issuer_gate",
            "result": "DB_APPLY_AUTHORIZATION_ISSUER_GATE_READY",
            "issuer_gate_ready_count": 1,
            "decision_closeout_ready_count": 1,
            "issuer_gate_check_count": 12,
            "issuer_gate_pass_count": 12,
            "issuer_gate_waiting_count": 0,
            "required_issuer_evidence_count": 9,
            "nonsecret_authorization_claim_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "permits_future_authorization_issuer_lane": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signing_decision_preflight_lane"
            ),
        },
    }


def _auto_policy_signing_decision_preflight_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signing decision preflight",
        "status": status,
        "summary": "PChome auto-policy signing decision preflight 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_decision_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_READY",
            "signing_decision_preflight_ready_count": 1,
            "authorization_issuer_gate_ready_count": 1,
            "signing_decision_preflight_check_count": 12,
            "signing_decision_preflight_pass_count": 12,
            "signing_decision_preflight_waiting_count": 0,
            "required_issuer_evidence_count": 9,
            "nonsecret_authorization_claim_count": 8,
            "signing_decision_input_requirement_count": 10,
            "signing_decision_rejection_reason_count": 11,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_required_in_preview": False,
            "allows_future_authorization_signing_decision_lane": True,
            "rejects_direct_database_apply": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signing_decision_closeout_lane"
            ),
        },
    }


def _auto_policy_signing_decision_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signing decision closeout",
        "status": status,
        "summary": "PChome auto-policy signing decision closeout 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_decision_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_READY",
            "signing_decision_closeout_ready_count": 1,
            "signing_decision_preflight_ready_count": 1,
            "signing_decision_closeout_check_count": 12,
            "signing_decision_closeout_pass_count": 12,
            "signing_decision_closeout_waiting_count": 0,
            "signing_decision_preflight_check_count": 12,
            "signing_decision_input_requirement_count": 10,
            "signing_decision_rejection_reason_count": 11,
            "required_issuer_evidence_count": 9,
            "nonsecret_authorization_claim_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "permits_future_unsigned_signing_decision_package_lane": True,
            "next_machine_action": "continue_to_pchome_auto_policy_signing_issuer_guard_lane",
        },
    }


def _auto_policy_signing_issuer_guard_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signing issuer guard",
        "status": status,
        "summary": "PChome auto-policy signing issuer guard 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_issuer_guard"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_READY",
            "signing_issuer_guard_ready_count": 1,
            "signing_issuer_guard_check_count": 12,
            "signing_issuer_guard_pass_count": 12,
            "signing_issuer_guard_waiting_count": 0,
            "signing_decision_closeout_ready_count": 1,
            "signing_decision_closeout_check_count": 12,
            "signing_decision_input_requirement_count": 10,
            "signing_decision_rejection_reason_count": 11,
            "required_issuer_evidence_count": 9,
            "nonsecret_authorization_claim_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "ready_for_future_signable_request_boundary": True,
            "permits_future_authorization_signing_issuer_lane": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signing_issuer_closeout_lane"
            ),
        },
    }


def _auto_policy_signing_issuer_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signing issuer closeout",
        "status": status,
        "summary": "PChome auto-policy signing issuer closeout 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_issuer_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_READY",
            "signing_issuer_closeout_ready_count": 1,
            "signing_issuer_closeout_check_count": 12,
            "signing_issuer_closeout_pass_count": 12,
            "signing_issuer_closeout_waiting_count": 0,
            "signing_issuer_guard_ready_count": 1,
            "signing_issuer_guard_check_count": 12,
            "signing_decision_input_requirement_count": 10,
            "signing_decision_rejection_reason_count": 11,
            "required_issuer_evidence_count": 9,
            "nonsecret_authorization_claim_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "ready_for_future_final_signable_request_package": True,
            "permits_future_final_signable_request_package_lane": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signing_execution_preflight_lane"
            ),
        },
    }


def _auto_policy_signing_execution_preflight_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signing execution preflight",
        "status": status,
        "summary": "PChome auto-policy signing execution preflight 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_execution_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_READY",
            "signing_execution_preflight_ready_count": 1,
            "signing_execution_preflight_check_count": 12,
            "signing_execution_preflight_pass_count": 12,
            "signing_execution_preflight_waiting_count": 0,
            "signing_issuer_closeout_ready_count": 1,
            "signing_issuer_closeout_check_count": 12,
            "signing_issuer_closeout_pass_count": 12,
            "final_signable_request_package_ready_count": 1,
            "operator_held_secret_boundary_count": 1,
            "signing_execution_input_requirement_count": 10,
            "signing_execution_abort_condition_count": 8,
            "rollback_boundary_count": 4,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "command_preview_redacts_secret_values": True,
            "command_preview_executes_in_preview": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "ready_for_future_signing_execution_preflight": True,
            "permits_future_explicit_authorization_signing_execution_lane": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signing_execution_closeout_lane"
            ),
        },
    }


def _auto_policy_signing_execution_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signing execution closeout",
        "status": status,
        "summary": "PChome auto-policy signing execution closeout 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_execution_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_READY",
            "signing_execution_closeout_ready_count": 1,
            "signing_execution_closeout_check_count": 12,
            "signing_execution_closeout_pass_count": 12,
            "signing_execution_closeout_waiting_count": 0,
            "signing_execution_preflight_ready_count": 1,
            "signing_execution_preflight_check_count": 12,
            "signing_execution_preflight_pass_count": 12,
            "unsigned_signed_authorization_receipt_boundary_count": 1,
            "operator_held_secret_boundary_count": 1,
            "signing_execution_input_requirement_count": 10,
            "signing_execution_abort_condition_count": 8,
            "rollback_boundary_count": 4,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "command_preview_redacts_secret_values": True,
            "command_preview_executes_in_preview": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "ready_for_future_signing_execution_closeout": True,
            "ready_for_future_unsigned_signed_authorization_receipt_boundary": True,
            "ready_for_future_signed_authorization_receipt_lane": True,
            "permits_future_unsigned_signed_authorization_receipt_boundary": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signed_receipt_preflight_lane"
            ),
        },
    }


def _auto_policy_signed_receipt_preflight_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signed receipt preflight",
        "status": status,
        "summary": "PChome auto-policy signed receipt preflight 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_READY",
            "signed_receipt_preflight_ready_count": 1,
            "signed_receipt_preflight_check_count": 12,
            "signed_receipt_preflight_pass_count": 12,
            "signed_receipt_preflight_waiting_count": 0,
            "signing_execution_closeout_ready_count": 1,
            "signing_execution_closeout_check_count": 12,
            "unsigned_signed_authorization_receipt_boundary_count": 1,
            "external_signing_receipt_evidence_boundary_count": 1,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "operator_held_secret_boundary_count": 1,
            "signing_execution_input_requirement_count": 10,
            "signing_execution_abort_condition_count": 8,
            "rollback_boundary_count": 4,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "signer_key_id_reference_only": True,
            "signature_algorithm_reference_only": True,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "ready_for_future_signed_authorization_receipt_preflight": True,
            "can_enter_future_external_signing_receipt_evidence_boundary": True,
            "ready_for_future_external_signing_receipt_evidence_boundary": True,
            "ready_for_future_signed_authorization_receipt_lane": True,
            "permits_future_external_signing_receipt_evidence_boundary": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signed_receipt_closeout_lane"
            ),
        },
    }


def _auto_policy_signed_receipt_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signed receipt closeout",
        "status": status,
        "summary": "PChome auto-policy signed receipt closeout 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_READY",
            "signed_receipt_closeout_ready_count": 1,
            "signed_receipt_closeout_check_count": 12,
            "signed_receipt_closeout_pass_count": 12,
            "signed_receipt_closeout_waiting_count": 0,
            "signed_receipt_preflight_ready_count": 1,
            "signed_receipt_preflight_check_count": 12,
            "external_signing_receipt_evidence_boundary_count": 1,
            "detached_receipt_verification_boundary_count": 1,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "detached_receipt_verification_check_count": 10,
            "operator_held_secret_boundary_count": 1,
            "signing_execution_input_requirement_count": 10,
            "signing_execution_abort_condition_count": 8,
            "rollback_boundary_count": 4,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "requires_detached_signature_verification": True,
            "detached_signature_verification_performed": False,
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "signer_key_id_reference_only": True,
            "signature_algorithm_reference_only": True,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "ready_for_future_signed_authorization_receipt_closeout": True,
            "can_enter_future_detached_receipt_verification_boundary": True,
            "ready_for_future_detached_receipt_verification_boundary": True,
            "ready_for_future_signed_authorization_receipt_verification_lane": True,
            "permits_future_detached_receipt_verification_boundary": True,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_signed_receipt_evidence_intake_lane"
            ),
        },
    }


def _auto_policy_signed_receipt_evidence_intake_history_check(status="ok"):
    return {
        "name": "PChome auto-policy signed receipt evidence intake",
        "status": status,
        "summary": "PChome auto-policy signed receipt evidence intake 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_evidence_intake"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_READY",
            "signed_receipt_evidence_intake_ready_count": 1,
            "signed_receipt_evidence_intake_check_count": 12,
            "signed_receipt_evidence_intake_pass_count": 12,
            "signed_receipt_evidence_intake_waiting_count": 0,
            "signed_receipt_closeout_ready_count": 1,
            "signed_receipt_closeout_check_count": 12,
            "signed_receipt_preflight_ready_count": 1,
            "signed_receipt_preflight_check_count": 12,
            "external_signing_receipt_evidence_boundary_count": 1,
            "detached_receipt_verification_boundary_count": 1,
            "detached_verification_evidence_schema_count": 1,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "detached_receipt_verification_check_count": 10,
            "detached_verification_evidence_field_count": 12,
            "detached_verification_acceptance_gate_count": 10,
            "operator_held_secret_boundary_count": 1,
            "rollback_boundary_count": 4,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "requires_detached_signature_verification": True,
            "detached_signature_verification_performed": False,
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "signer_key_id_reference_only": True,
            "signature_algorithm_reference_only": True,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "accepts_plaintext_secret": False,
            "ready_for_future_signed_authorization_receipt_evidence_intake": True,
            "can_enter_future_detached_verification_evidence_validation": True,
            "external_signed_authorization_receipt_evidence_schema_ready": True,
            "ready_for_future_detached_verification_evidence_schema": True,
            "permits_future_detached_verification_evidence_validation": True,
            "performs_detached_signature_verification": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_detached_verification_evidence_validation_lane"
            ),
        },
    }


def _auto_policy_detached_verification_evidence_validation_history_check(status="ok"):
    return {
        "name": "PChome auto-policy detached verification evidence validation",
        "status": status,
        "summary": (
            "PChome auto-policy detached verification evidence validation 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "detached_verification_evidence_validation"
            ),
            "result": (
                "DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_READY"
            ),
            "detached_verification_evidence_validation_ready_count": 1,
            "detached_verification_evidence_validation_check_count": 12,
            "detached_verification_evidence_validation_pass_count": 12,
            "detached_verification_evidence_validation_waiting_count": 0,
            "signed_receipt_evidence_intake_ready_count": 1,
            "signed_receipt_evidence_intake_check_count": 12,
            "signed_receipt_closeout_check_count": 12,
            "detached_verification_evidence_schema_count": 1,
            "verifier_receipt_closeout_boundary_count": 1,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "detached_receipt_verification_check_count": 10,
            "detached_verification_evidence_field_count": 12,
            "detached_verification_acceptance_gate_count": 10,
            "verifier_receipt_field_count": 12,
            "verifier_receipt_acceptance_gate_count": 10,
            "operator_held_secret_boundary_count": 1,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "requires_detached_signature_verification": True,
            "detached_signature_verification_performed": False,
            "verifier_receipt_persisted": False,
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "accepts_plaintext_secret": False,
            "ready_for_future_detached_verification_evidence_validation": True,
            "can_enter_future_verifier_receipt_closeout": True,
            "verifier_receipt_closeout_boundary_ready": True,
            "ready_for_future_verifier_receipt_closeout_boundary": True,
            "permits_future_verifier_receipt_closeout": True,
            "persists_verifier_receipt": False,
            "performs_detached_signature_verification": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_verifier_receipt_closeout_lane"
            ),
        },
    }


def _auto_policy_verifier_receipt_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy verifier receipt closeout",
        "status": status,
        "summary": "PChome auto-policy verifier receipt closeout 已自動完成",
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "verifier_receipt_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_READY",
            "verifier_receipt_closeout_ready_count": 1,
            "verifier_receipt_closeout_check_count": 12,
            "verifier_receipt_closeout_pass_count": 12,
            "verifier_receipt_closeout_waiting_count": 0,
            "detached_verification_evidence_validation_ready_count": 1,
            "detached_verification_evidence_validation_check_count": 12,
            "signed_receipt_evidence_intake_ready_count": 1,
            "signed_receipt_evidence_intake_check_count": 12,
            "verifier_receipt_closeout_boundary_count": 1,
            "verifier_receipt_evidence_handoff_count": 1,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "verifier_receipt_field_count": 12,
            "verifier_receipt_acceptance_gate_count": 10,
            "verifier_receipt_evidence_handoff_field_count": 12,
            "verifier_receipt_handoff_acceptance_gate_count": 10,
            "detached_verification_evidence_field_count": 12,
            "detached_verification_acceptance_gate_count": 10,
            "operator_held_secret_boundary_count": 1,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "secret_reference_mode": "external_runtime_reference_only",
            "requires_detached_signature_verification": True,
            "detached_signature_verification_performed": False,
            "verifier_receipt_persisted": False,
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "accepts_plaintext_secret": False,
            "ready_for_future_verifier_receipt_closeout": True,
            "can_enter_future_database_apply_authorization_verifier_handoff": True,
            "verifier_receipt_evidence_handoff_ready": True,
            "ready_for_future_verifier_receipt_evidence_handoff": True,
            "permits_future_database_apply_authorization_verifier_handoff": True,
            "persists_verifier_receipt": False,
            "performs_detached_signature_verification": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_database_apply_authorization_verifier_handoff_lane"
            ),
        },
    }


def _auto_policy_authorization_evidence_execution_preflight_history_check(status="ok"):
    return {
        "name": "PChome auto-policy authorization evidence execution preflight",
        "status": status,
        "summary": (
            "PChome auto-policy authorization evidence execution preflight 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "evidence_execution_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_READY",
            "authorization_evidence_execution_preflight_ready_count": 1,
            "authorization_evidence_execution_preflight_check_count": 12,
            "authorization_evidence_execution_preflight_pass_count": 12,
            "authorization_evidence_execution_preflight_waiting_count": 0,
            "authorization_verifier_receipt_closeout_ready_count": 1,
            "verifier_receipt_closeout_check_count": 12,
            "detached_verification_evidence_validation_ready_count": 1,
            "detached_verification_evidence_validation_check_count": 12,
            "verifier_receipt_evidence_handoff_count": 1,
            "authorization_evidence_execution_preflight_count": 1,
            "authorization_evidence_execution_field_count": 12,
            "authorization_evidence_execution_acceptance_gate_count": 10,
            "verifier_receipt_field_count": 12,
            "verifier_receipt_acceptance_gate_count": 10,
            "verifier_receipt_evidence_handoff_field_count": 12,
            "verifier_receipt_handoff_acceptance_gate_count": 10,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_future_database_apply_authorization_verifier_handoff": True,
            "can_enter_future_authorization_evidence_execution_closeout": True,
            "authorization_evidence_execution_preflight_ready": True,
            "ready_for_future_authorization_evidence_execution_preflight": True,
            "permits_future_authorization_evidence_execution_closeout": True,
            "requires_detached_signature_verification": True,
            "detached_signature_verification_performed": False,
            "verifier_receipt_persisted": False,
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "signer_key_id_reference_only": True,
            "signature_algorithm_reference_only": True,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "accepts_plaintext_secret": False,
            "reads_secret_in_preview": False,
            "executes_authorization_evidence": False,
            "ready_for_database_apply_now": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_authorization_evidence_execution_closeout_lane"
            ),
        },
    }


def _auto_policy_authorization_evidence_execution_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy authorization evidence execution closeout",
        "status": status,
        "summary": (
            "PChome auto-policy authorization evidence execution closeout 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "evidence_execution_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_READY",
            "authorization_evidence_execution_closeout_ready_count": 1,
            "authorization_evidence_execution_closeout_check_count": 12,
            "authorization_evidence_execution_closeout_pass_count": 12,
            "authorization_evidence_execution_closeout_waiting_count": 0,
            "authorization_evidence_execution_preflight_ready_count": 1,
            "authorization_evidence_execution_preflight_check_count": 12,
            "authorization_verifier_receipt_closeout_ready_count": 1,
            "verifier_receipt_closeout_check_count": 12,
            "detached_verification_evidence_validation_ready_count": 1,
            "detached_verification_evidence_validation_check_count": 12,
            "verifier_receipt_evidence_handoff_count": 1,
            "authorization_evidence_execution_preflight_count": 1,
            "authorization_evidence_execution_closeout_count": 1,
            "database_apply_final_verifier_gate_count": 1,
            "database_apply_authorization_final_verifier_gate_ready_count": 1,
            "authorization_evidence_execution_closeout_field_count": 12,
            "authorization_evidence_execution_closeout_acceptance_gate_count": 10,
            "authorization_evidence_execution_field_count": 12,
            "authorization_evidence_execution_acceptance_gate_count": 10,
            "verifier_receipt_field_count": 12,
            "verifier_receipt_acceptance_gate_count": 10,
            "verifier_receipt_evidence_handoff_field_count": 12,
            "verifier_receipt_handoff_acceptance_gate_count": 10,
            "required_external_receipt_evidence_count": 10,
            "external_receipt_acceptance_gate_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_future_database_apply_authorization_final_verifier_gate": True,
            "can_enter_future_database_apply_controlled_apply_final_preflight": True,
            "authorization_evidence_execution_closeout_ready": True,
            "ready_for_future_authorization_evidence_execution_closeout": True,
            "permits_future_database_apply_authorization_final_verifier_gate": True,
            "permits_future_database_apply_controlled_apply_final_preflight": True,
            "requires_detached_signature_verification": True,
            "detached_signature_verification_performed": False,
            "verifier_receipt_persisted": False,
            "external_signed_authorization_receipt_required_in_future": True,
            "external_signed_authorization_receipt_included": False,
            "signed_authorization_receipt_included": False,
            "signature_material_included": False,
            "signer_key_id_reference_only": True,
            "signature_algorithm_reference_only": True,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "accepts_plaintext_secret": False,
            "reads_secret_in_preview": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "ready_for_database_apply_now": False,
            "database_apply_authorized": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_database_apply_controlled_apply_final_preflight_lane"
            ),
        },
    }


def _auto_policy_controlled_apply_final_preflight_history_check(status="ok"):
    return {
        "name": "PChome auto-policy controlled apply final preflight",
        "status": status,
        "summary": (
            "PChome auto-policy controlled apply final preflight 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_controlled_apply_"
                "final_preflight"
            ),
            "result": "DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_READY",
            "controlled_apply_final_preflight_ready_count": 1,
            "controlled_apply_final_preflight_check_count": 12,
            "controlled_apply_final_preflight_pass_count": 12,
            "controlled_apply_final_preflight_waiting_count": 0,
            "authorization_evidence_execution_closeout_ready_count": 1,
            "authorization_evidence_execution_closeout_check_count": 12,
            "authorization_evidence_execution_preflight_ready_count": 1,
            "authorization_evidence_execution_preflight_check_count": 12,
            "authorization_verifier_receipt_closeout_ready_count": 1,
            "verifier_receipt_closeout_check_count": 12,
            "database_apply_final_verifier_gate_count": 1,
            "database_apply_authorization_final_verifier_gate_ready_count": 1,
            "controlled_apply_final_preflight_count": 1,
            "controlled_apply_final_preflight_field_count": 12,
            "controlled_apply_final_preflight_acceptance_gate_count": 10,
            "rollback_binding_count": 1,
            "rollback_binding_field_count": 8,
            "post_apply_verifier_binding_count": 1,
            "post_apply_verifier_binding_field_count": 8,
            "authorization_evidence_execution_closeout_field_count": 12,
            "authorization_evidence_execution_closeout_acceptance_gate_count": 10,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_future_database_apply_controlled_apply_final_preflight": True,
            "can_enter_future_database_apply_controlled_dry_run_package": True,
            "controlled_apply_final_preflight_ready": True,
            "rollback_binding_ready": True,
            "post_apply_verifier_binding_ready": True,
            "rollback_bound": True,
            "post_apply_verifier_bound": True,
            "dry_run_only": True,
            "check_mode_only": True,
            "rollback_execution_authorized": False,
            "rollback_executes_sql": False,
            "rollback_writes_database": False,
            "rollback_reads_secret": False,
            "rollback_requires_same_run_truth": True,
            "post_apply_verifier_must_run_after_apply": True,
            "post_apply_verifier_execution_authorized_in_preview": False,
            "permits_future_database_apply_controlled_dry_run_package": True,
            "accepts_plaintext_secret": False,
            "reads_secret_in_preview": False,
            "signature_material_included": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "executes_endpoint": False,
            "executes_sql": False,
            "ready_for_database_apply_now": False,
            "database_apply_authorized": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_controlled_dry_run_package_lane"
            ),
        },
    }


def _auto_policy_controlled_dry_run_package_history_check(status="ok"):
    return {
        "name": "PChome auto-policy controlled dry-run package",
        "status": status,
        "summary": (
            "PChome auto-policy controlled dry-run package 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_controlled_"
                "dry_run_package"
            ),
            "result": "DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_READY",
            "controlled_dry_run_package_ready_count": 1,
            "controlled_dry_run_package_check_count": 12,
            "controlled_dry_run_package_pass_count": 12,
            "controlled_dry_run_package_waiting_count": 0,
            "controlled_apply_final_preflight_ready_count": 1,
            "controlled_apply_final_preflight_check_count": 12,
            "authorization_evidence_execution_closeout_ready_count": 1,
            "authorization_evidence_execution_closeout_check_count": 12,
            "authorization_evidence_execution_preflight_ready_count": 1,
            "authorization_evidence_execution_preflight_check_count": 12,
            "authorization_verifier_receipt_closeout_ready_count": 1,
            "verifier_receipt_closeout_check_count": 12,
            "database_apply_final_verifier_gate_count": 1,
            "database_apply_authorization_final_verifier_gate_ready_count": 1,
            "controlled_dry_run_package_count": 1,
            "controlled_dry_run_package_field_count": 12,
            "controlled_dry_run_acceptance_gate_count": 10,
            "dry_run_execution_receipt_preview_count": 1,
            "dry_run_execution_receipt_field_count": 8,
            "dry_run_result_parser_count": 1,
            "dry_run_result_parser_field_count": 10,
            "controlled_apply_final_preflight_count": 1,
            "controlled_apply_final_preflight_field_count": 12,
            "controlled_apply_final_preflight_acceptance_gate_count": 10,
            "rollback_binding_count": 1,
            "rollback_binding_field_count": 8,
            "post_apply_verifier_binding_count": 1,
            "post_apply_verifier_binding_field_count": 8,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_future_database_apply_controlled_dry_run_execution_receipt": True,
            "can_enter_future_database_apply_controlled_dry_run_receipt_closeout": True,
            "controlled_dry_run_package_ready": True,
            "dry_run_execution_performed": False,
            "ready_for_future_database_apply_controlled_dry_run_package": True,
            "target_migration_hash_locked": True,
            "dry_run_only": True,
            "check_mode_only": True,
            "requires_fresh_production_truth": True,
            "requires_post_apply_verifier": True,
            "command_shape_dry_run_only": True,
            "command_shape_check_mode_only": True,
            "command_shape_execution_allowed": False,
            "command_shape_shell_command_included": False,
            "command_shape_sql_included": False,
            "command_shape_endpoint_execution_included": False,
            "command_shape_database_write_included": False,
            "receipt_dry_run_status": "preview_only_not_executed",
            "receipt_execution_performed": False,
            "receipt_stdout_included": False,
            "receipt_stderr_included": False,
            "receipt_database_apply_authorized": False,
            "receipt_executes_shell": False,
            "receipt_executes_endpoint": False,
            "receipt_executes_sql": False,
            "receipt_writes_database": False,
            "receipt_reads_secret": False,
            "parser_expected_receipt_status": "preview_only_not_executed",
            "parser_execution_required": False,
            "parser_stdout_allowed": False,
            "parser_stderr_allowed": False,
            "parser_database_apply_authorized": False,
            "parser_verification_status": "schema_preview_ready",
            "permits_future_database_apply_controlled_dry_run_execution_receipt": True,
            "accepts_plaintext_secret": False,
            "reads_secret_in_preview": False,
            "signature_material_included": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "executes_endpoint": False,
            "executes_sql": False,
            "ready_for_database_apply_now": False,
            "database_apply_authorized": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_controlled_dry_run_receipt_closeout_lane"
            ),
        },
    }


def _auto_policy_controlled_dry_run_receipt_closeout_history_check(status="ok"):
    return {
        "name": "PChome auto-policy controlled dry-run receipt closeout",
        "status": status,
        "summary": (
            "PChome auto-policy controlled dry-run receipt closeout 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_controlled_"
                "dry_run_receipt_closeout"
            ),
            "result": "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_READY",
            "controlled_dry_run_receipt_closeout_ready_count": 1,
            "controlled_dry_run_receipt_closeout_check_count": 12,
            "controlled_dry_run_receipt_closeout_pass_count": 12,
            "controlled_dry_run_receipt_closeout_waiting_count": 0,
            "controlled_dry_run_package_ready_count": 1,
            "controlled_dry_run_package_check_count": 12,
            "controlled_apply_final_preflight_ready_count": 1,
            "controlled_apply_final_preflight_check_count": 12,
            "authorization_evidence_execution_closeout_ready_count": 1,
            "authorization_evidence_execution_closeout_check_count": 12,
            "authorization_evidence_execution_preflight_ready_count": 1,
            "authorization_evidence_execution_preflight_check_count": 12,
            "authorization_verifier_receipt_closeout_ready_count": 1,
            "verifier_receipt_closeout_check_count": 12,
            "database_apply_final_verifier_gate_count": 1,
            "database_apply_authorization_final_verifier_gate_ready_count": 1,
            "controlled_dry_run_receipt_closeout_count": 1,
            "controlled_dry_run_receipt_closeout_field_count": 12,
            "controlled_dry_run_receipt_closeout_acceptance_gate_count": 10,
            "dry_run_result_parser_count": 1,
            "dry_run_result_parser_field_count": 10,
            "receipt_validation_report_count": 1,
            "receipt_validation_field_count": 8,
            "dry_run_execution_receipt_preview_count": 1,
            "dry_run_execution_receipt_field_count": 8,
            "controlled_dry_run_package_count": 1,
            "controlled_dry_run_package_field_count": 12,
            "controlled_dry_run_acceptance_gate_count": 10,
            "rollback_binding_count": 1,
            "post_apply_verifier_binding_count": 1,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_future_database_apply_controlled_dry_run_result_parser_verification": True,
            "can_enter_future_database_apply_controlled_dry_run_runner_readiness": True,
            "controlled_dry_run_receipt_closeout_ready": True,
            "source_controlled_dry_run_package_ready": True,
            "dry_run_execution_performed": False,
            "ready_for_future_database_apply_controlled_dry_run_receipt_closeout": True,
            "target_migration_hash_locked": True,
            "dry_run_only": True,
            "check_mode_only": True,
            "receipt_preview_only": True,
            "requires_fresh_production_truth": True,
            "requires_post_apply_verifier": True,
            "receipt_validation_status": "preview_validated_not_executed",
            "validation_execution_performed": False,
            "validation_stdout_included": False,
            "validation_stderr_included": False,
            "validation_database_apply_authorized": False,
            "validation_executes_shell": False,
            "validation_executes_endpoint": False,
            "validation_executes_sql": False,
            "validation_writes_database": False,
            "validation_reads_secret": False,
            "parser_expected_receipt_status": "preview_only_not_executed",
            "parser_execution_required": False,
            "parser_stdout_allowed": False,
            "parser_stderr_allowed": False,
            "parser_database_apply_authorized": False,
            "parser_verification_status": "schema_preview_ready",
            "permits_future_database_apply_controlled_dry_run_runner_readiness": True,
            "accepts_plaintext_secret": False,
            "reads_secret_in_preview": False,
            "signature_material_included": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "executes_endpoint": False,
            "executes_sql": False,
            "ready_for_database_apply_now": False,
            "database_apply_authorized": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_controlled_dry_run_runner_readiness_lane"
            ),
        },
    }


def _auto_policy_controlled_dry_run_runner_readiness_history_check(status="ok"):
    return {
        "name": "PChome auto-policy controlled dry-run runner readiness",
        "status": status,
        "summary": (
            "PChome auto-policy controlled dry-run runner readiness 已自動完成"
        ),
        "details": {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_controlled_"
                "dry_run_runner_readiness"
            ),
            "result": "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_READY",
            "controlled_dry_run_runner_readiness_ready_count": 1,
            "controlled_dry_run_runner_readiness_check_count": 12,
            "controlled_dry_run_runner_readiness_pass_count": 12,
            "controlled_dry_run_runner_readiness_waiting_count": 0,
            "controlled_dry_run_receipt_closeout_ready_count": 1,
            "controlled_dry_run_receipt_closeout_check_count": 12,
            "controlled_dry_run_package_ready_count": 1,
            "controlled_dry_run_package_check_count": 12,
            "controlled_apply_final_preflight_ready_count": 1,
            "controlled_apply_final_preflight_check_count": 12,
            "authorization_evidence_execution_closeout_ready_count": 1,
            "authorization_evidence_execution_closeout_check_count": 12,
            "authorization_evidence_execution_preflight_ready_count": 1,
            "authorization_evidence_execution_preflight_check_count": 12,
            "database_apply_final_verifier_gate_count": 1,
            "database_apply_authorization_final_verifier_gate_ready_count": 1,
            "controlled_dry_run_runner_readiness_count": 1,
            "controlled_dry_run_runner_readiness_field_count": 12,
            "controlled_dry_run_runner_readiness_acceptance_gate_count": 10,
            "execution_plan_binding_count": 1,
            "execution_plan_binding_field_count": 12,
            "dry_run_result_parser_count": 1,
            "dry_run_result_parser_field_count": 10,
            "receipt_validation_report_count": 1,
            "receipt_validation_field_count": 8,
            "controlled_dry_run_receipt_closeout_count": 1,
            "controlled_dry_run_receipt_closeout_field_count": 12,
            "controlled_dry_run_receipt_closeout_acceptance_gate_count": 10,
            "rollback_binding_count": 1,
            "post_apply_verifier_binding_count": 1,
            "post_apply_verifier_required_count": 1,
            "same_run_truth_required_count": 1,
            "writes_script_count": 0,
            "writes_artifact_count": 0,
            "reads_secret_count": 0,
            "executes_script_count": 0,
            "executes_migration_count": 0,
            "executes_endpoint_count": 0,
            "executes_sql_count": 0,
            "writes_database_count": 0,
            "signs_database_apply_authorization_count": 0,
            "primary_human_gate_count": 0,
            "manual_review_required_count": 0,
            "manual_review_mode": "exception_only",
            "payload_source": "local_contract_fixture",
            "execute_fetch": True,
            "outbound_network": False,
            "business_data_source": False,
            "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding": True,
            "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout": True,
            "controlled_dry_run_runner_readiness_ready": True,
            "execution_plan_bound": True,
            "source_controlled_dry_run_receipt_closeout_ready": True,
            "dry_run_execution_performed": False,
            "ready_for_future_database_apply_controlled_dry_run_runner_readiness": True,
            "target_migration_hash_locked": True,
            "dry_run_only": True,
            "check_mode_only": True,
            "runner_readiness_only": True,
            "execution_plan_preview_only": True,
            "requires_fresh_production_truth": True,
            "requires_post_apply_verifier": True,
            "execution_plan_runner_mode": "future_controlled_dry_run_runner_readiness_only",
            "execution_plan_status": "plan_binding_preview_not_executable",
            "execution_authorized": False,
            "dry_run_execution_authorized": False,
            "runner_execution_authorized": False,
            "shell_execution_included": False,
            "endpoint_execution_included": False,
            "sql_execution_included": False,
            "database_write_included": False,
            "stdout_capture_allowed": False,
            "stderr_capture_allowed": False,
            "receipt_validation_status": "preview_validated_not_executed",
            "validation_execution_performed": False,
            "validation_stdout_included": False,
            "validation_stderr_included": False,
            "validation_database_apply_authorized": False,
            "validation_executes_shell": False,
            "validation_executes_endpoint": False,
            "validation_executes_sql": False,
            "validation_writes_database": False,
            "validation_reads_secret": False,
            "parser_expected_receipt_status": "preview_only_not_executed",
            "parser_execution_required": False,
            "parser_stdout_allowed": False,
            "parser_stderr_allowed": False,
            "parser_database_apply_authorized": False,
            "parser_verification_status": "schema_preview_ready",
            "permits_future_database_apply_controlled_dry_run_execution_plan_binding": True,
            "accepts_plaintext_secret": False,
            "reads_secret_in_preview": False,
            "signature_material_included": False,
            "secret_material_included": False,
            "secret_material_required_in_preview": False,
            "executes_authorization_evidence": False,
            "executes_database_apply": False,
            "executes_endpoint": False,
            "executes_sql": False,
            "ready_for_database_apply_now": False,
            "database_apply_authorized": False,
            "issues_database_apply_authorization": False,
            "signs_database_apply_authorization": False,
            "next_machine_action": (
                "continue_to_pchome_auto_policy_controlled_dry_run_execution_plan_closeout_lane"
            ),
        },
    }


def test_event_router_smoke_reports_queued_deliveries(tmp_path, monkeypatch):
    from services import ai_automation_metrics as metrics
    from services import ai_automation_smoke_service as smoke
    from services import event_router

    queue_path = tmp_path / "failed_deliveries.jsonl"
    queue_path.write_text('{"event_key":"a"}\n{"event_key":"b"}\n', encoding="utf-8")
    monkeypatch.setattr(event_router, "_QUEUE_PATH", str(queue_path))
    metrics.reset_for_tests()
    metrics.record_event_router_dispatch(
        tier="L1",
        event_type="crawler_timeout",
        delivered=False,
        queued=True,
        latency_ms=12,
    )

    result = smoke._event_router_check()

    assert result["status"] == "warning"
    assert result["details"]["queued_deliveries"] == 2
    assert result["details"]["dispatch_metric_total"] == 1
    assert result["details"]["dispatch_sync"] is True


def test_collect_ai_automation_smoke_uses_worst_status(monkeypatch):
    from services import ai_automation_smoke_service as smoke

    monkeypatch.setattr(smoke, "_event_router_check", lambda: smoke._check("event", "ok", "ok"))
    monkeypatch.setattr(smoke, "_gemini_egress_check", lambda: smoke._check("gemini", "ok", "ok"))
    monkeypatch.setattr(smoke, "_autoheal_check", lambda: smoke._check("autoheal", "warning", "warn"))
    monkeypatch.setattr(smoke, "_nemotron_check", lambda: smoke._check("nemotron", "ok", "ok"))
    monkeypatch.setattr(smoke, "_embedding_queue_check", lambda: smoke._check("embedding", "critical", "boom"))
    monkeypatch.setattr(smoke, "_elephant_hitl_check", lambda: smoke._check("elephant", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_controlled_apply_drift_monitor_check", lambda: smoke._check("pchome", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_guard_check", lambda: smoke._check("auto-policy", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_decision_preflight_check", lambda: smoke._check("auto-policy preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_decision_closeout_check", lambda: smoke._check("auto-policy closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_issuer_gate_check", lambda: smoke._check("auto-policy issuer", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_decision_preflight_check", lambda: smoke._check("auto-policy signing preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_decision_closeout_check", lambda: smoke._check("auto-policy signing closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_issuer_guard_check", lambda: smoke._check("auto-policy signing issuer guard", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_issuer_closeout_check", lambda: smoke._check("auto-policy signing issuer closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_execution_preflight_check", lambda: smoke._check("auto-policy signing execution preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_execution_closeout_check", lambda: smoke._check("auto-policy signing execution closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_preflight_check", lambda: smoke._check("auto-policy signed receipt preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_closeout_check", lambda: smoke._check("auto-policy signed receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_evidence_intake_check", lambda: smoke._check("auto-policy signed receipt evidence intake", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_detached_verification_evidence_validation_check", lambda: smoke._check("auto-policy detached verification evidence validation", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_verifier_receipt_closeout_check", lambda: smoke._check("auto-policy verifier receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_evidence_execution_preflight_check", lambda: smoke._check("auto-policy authorization evidence execution preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_evidence_execution_closeout_check", lambda: smoke._check("auto-policy authorization evidence execution closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_apply_final_preflight_check", lambda: smoke._check("auto-policy controlled apply final preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_package_check", lambda: smoke._check("auto-policy controlled dry-run package", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_receipt_closeout_check", lambda: smoke._check("auto-policy controlled dry-run receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_runner_readiness_check", lambda: smoke._check("auto-policy controlled dry-run runner readiness", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_runner_readiness_check", lambda: smoke._check("auto-policy controlled dry-run runner readiness", "ok", "ok"))
    monkeypatch.setattr(smoke, "_ai_surface_html_readback_check", lambda: smoke._check("surface", "ok", "ok"))
    monkeypatch.setattr(smoke, "_sitewide_ui_ux_agent_check", lambda: smoke._check("sitewide", "ok", "ok"))
    monkeypatch.setattr(smoke, "_sitewide_visual_qa_check", lambda: smoke._check("visual", "ok", "ok"))
    monkeypatch.setattr(smoke, "_security_governance_review_check", lambda: smoke._check("security governance", "ok", "ok"))
    monkeypatch.setattr(smoke, "_external_mcp_rag_integration_check", lambda: smoke._check("external mcp rag", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_rag_candidate_replay_check", lambda: smoke._check("pixelrag replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_source_contract_replay_worker_check", lambda: smoke._check("pixelrag source contract", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_adapter_preflight_check", lambda: smoke._check("pixelrag marketplace adapter preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_adapter_dry_run_check", lambda: smoke._check("pixelrag marketplace adapter dry-run", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_identity_matcher_replay_check", lambda: smoke._check("pixelrag marketplace identity matcher replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_promotion_gate_replay_check", lambda: smoke._check("pixelrag marketplace promotion gate replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_embedding_signature_guard_replay_check", lambda: smoke._check("pixelrag marketplace embedding signature guard replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_candidate_knowledge_replay_check", lambda: smoke._check("pixelrag marketplace candidate knowledge replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_ocr_vlm_replay_check", lambda: smoke._check("pixelrag ocr vlm", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_vlm_route_readiness_check", lambda: smoke._check("pixelrag vlm route", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_vlm_replay_worker_check", lambda: smoke._check("pixelrag vlm worker", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_platform_probe_check", lambda: smoke._check("pixelrag platform probe", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_platform_probe_worker_check", lambda: smoke._check("pixelrag platform probe worker", "ok", "ok"))

    result = smoke.collect_ai_automation_smoke(record_history=False)

    assert result["status"] == "critical"
    assert result["summary"] == {"ok": 44, "warning": 1, "critical": 1, "total": 46}


def test_pchome_controlled_apply_drift_monitor_reports_verified_zero_drift(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    class FakeEngine:
        disposed = False

        def dispose(self):
            self.disposed = True

    fake_engine = FakeEngine()
    monkeypatch.setattr(smoke, "_create_pchome_drift_monitor_engine", lambda _path: fake_engine)
    monkeypatch.setattr(
        backlog,
        "build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package",
        lambda **_kwargs: {
            "result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_RECEIPT_REPLAYED",
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 4,
                "executor_receipt_hash_match_count": 1,
            },
        },
    )
    monkeypatch.setattr(
        backlog,
        "build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package",
        lambda **_kwargs: {
            "result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIED",
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 4,
                "drift_count": 0,
                "drift_verified_count": 1,
                "drift_verifier_artifact_materialized_count": 1,
                "drift_verifier_artifact_hash_match_count": 1,
                "writes_database_count": 0,
            },
        },
    )

    result = smoke._pchome_controlled_apply_drift_monitor_check()

    assert result["status"] == "ok"
    assert result["details"]["selector_count"] == 4
    assert result["details"]["drift_count"] == 0
    assert result["details"]["writes_database"] is False
    assert result["details"]["materialize_artifacts"] is False
    assert fake_engine.disposed is True


def test_pchome_auto_policy_authorization_guard_reports_no_write_exception_only(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog
    from services import pchome_revenue_growth_service as growth

    class FakeEngine:
        disposed = False

        def dispose(self):
            self.disposed = True

    fake_engine = FakeEngine()
    monkeypatch.setattr(smoke, "_create_pchome_drift_monitor_engine", lambda _path: fake_engine)
    monkeypatch.setattr(growth, "build_pchome_growth_opportunities", lambda _engine, limit: {"success": True})
    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_lane_guard",
        lambda *_args, **_kwargs: {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_lane_guard",
            "result": "WAITING_FOR_DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT",
            "source_policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_request_closeout",
            "summary": {
                "authorization_lane_guard_ready_count": 0,
                "authorization_request_closeout_ready_count": 0,
                "lane_guard_check_count": 12,
                "lane_guard_pass_count": 11,
                "lane_guard_waiting_count": 1,
                "exact_request_payload_field_count": 10,
                "machine_request_manifest_step_count": 6,
                "lane_entry_requirement_count": 6,
                "reads_secret_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_lane_guard": {
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "requires_fresh_production_truth_in_same_run": True,
            },
            "lane_transfer_contract": {
                "machine_verifiable": True,
                "writes_database": False,
                "issues_database_apply_authorization": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_sql": False,
                "writes_database": False,
                "manual_review_mode": "exception_only",
            },
        },
    )

    result = smoke._pchome_auto_policy_authorization_guard_check()

    assert result["status"] == "ok"
    assert result["details"]["lane_guard_pass_count"] == 11
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["next_machine_action"] == "collect_machine_fetch_evidence_for_authorization_guard"
    assert fake_engine.disposed is True


def test_pchome_auto_policy_decision_preflight_reports_machine_fetch_no_write(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog
    captured = {}

    def fake_preflight(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_preflight",
            "result": "DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_READY",
            "source_policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_lane_guard",
            "summary": {
                "authorization_decision_preflight_ready_count": 1,
                "authorization_lane_guard_ready_count": 1,
                "decision_preflight_check_count": 12,
                "decision_preflight_pass_count": 12,
                "decision_preflight_waiting_count": 0,
                "decision_input_requirement_count": 8,
                "decision_rejection_reason_count": 10,
                "lane_entry_requirement_count": 6,
                "exact_request_payload_field_count": 10,
                "machine_request_manifest_step_count": 6,
                "reads_secret_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_decision_preflight": {
                "ready_for_future_authorization_decision": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "requires_fresh_production_truth_in_same_run": True,
            },
            "decision_preflight_envelope": {
                "allows_authorization_decision_in_future_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_sql": False,
                "writes_database": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_decision_preflight",
        fake_preflight,
    )

    result = smoke._pchome_auto_policy_decision_preflight_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["decision_preflight_pass_count"] == 12
    assert result["details"]["machine_fetch_evidence_ready_count"] == 1
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["next_machine_action"] == "continue_to_pchome_auto_policy_decision_closeout_lane"


def test_pchome_auto_policy_decision_closeout_reports_no_write_package(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog
    captured = {}

    def fake_closeout(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_closeout",
            "result": "DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_READY",
            "source_policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_preflight",
            "summary": {
                "authorization_decision_closeout_ready_count": 1,
                "authorization_decision_preflight_ready_count": 1,
                "decision_closeout_check_count": 12,
                "decision_closeout_pass_count": 12,
                "decision_closeout_waiting_count": 0,
                "decision_input_requirement_count": 8,
                "decision_rejection_reason_count": 10,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "reads_secret_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_decision_closeout": {
                "ready_for_future_authorization_decision_closeout": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
            },
            "future_authorization_decision_package": {
                "ready_for_future_authorization_decision_package": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
            },
            "decision_closeout_contract": {
                "machine_verifiable": True,
                "permits_future_authorization_decision_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "writes_database": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_sql": False,
                "writes_database": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_decision_closeout",
        fake_closeout,
    )

    result = smoke._pchome_auto_policy_decision_closeout_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["decision_closeout_pass_count"] == 12
    assert result["details"]["post_apply_verifier_required_count"] == 1
    assert result["details"]["same_run_truth_required_count"] == 1
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["next_machine_action"] == "continue_to_pchome_auto_policy_authorization_issuer_gate"


def test_pchome_auto_policy_authorization_issuer_gate_reports_no_write_nonsecret_envelope(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog
    captured = {}

    def fake_gate(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_issuer_gate",
            "result": "DB_APPLY_AUTHORIZATION_ISSUER_GATE_READY",
            "source_policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_closeout",
            "summary": {
                "authorization_issuer_gate_ready_count": 1,
                "authorization_decision_closeout_ready_count": 1,
                "issuer_gate_check_count": 12,
                "issuer_gate_pass_count": 12,
                "issuer_gate_waiting_count": 0,
                "decision_closeout_check_count": 12,
                "required_issuer_evidence_count": 9,
                "nonsecret_authorization_claim_count": 8,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "reads_secret_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_issuer_gate": {
                "ready_for_future_authorization_issuer_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
            },
            "final_nonsecret_authorization_envelope": {
                "authorization_material_type": "nonsecret_request_envelope",
                "ready_for_future_authorization_issuer_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "secret_material_included": False,
                "reads_secret_in_preview": False,
                "writes_database_in_preview": False,
            },
            "issuer_gate_contract": {
                "machine_verifiable": True,
                "permits_future_authorization_issuer_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_script": False,
                "executes_sql": False,
                "writes_database": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_issuer_gate",
        fake_gate,
    )

    result = smoke._pchome_auto_policy_authorization_issuer_gate_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["issuer_gate_pass_count"] == 12
    assert result["details"]["required_issuer_evidence_count"] == 9
    assert result["details"]["nonsecret_authorization_claim_count"] == 8
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["permits_future_authorization_issuer_lane"] is True
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signing_decision_preflight_lane"
    )


def test_pchome_auto_policy_signing_decision_preflight_reports_no_write_no_signing(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog
    captured = {}

    def fake_preflight(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_decision_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_READY",
            "source_policy": "read_only_pchome_growth_auto_policy_db_apply_authorization_issuer_gate",
            "summary": {
                "authorization_signing_decision_preflight_ready_count": 1,
                "authorization_issuer_gate_ready_count": 1,
                "signing_decision_preflight_check_count": 12,
                "signing_decision_preflight_pass_count": 12,
                "signing_decision_preflight_waiting_count": 0,
                "issuer_gate_check_count": 12,
                "required_issuer_evidence_count": 9,
                "nonsecret_authorization_claim_count": 8,
                "signing_decision_input_requirement_count": 10,
                "signing_decision_rejection_reason_count": 11,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "reads_secret_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signing_decision_preflight": {
                "ready_for_future_signing_decision_preflight": True,
                "can_enter_authorization_signing_decision_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
            },
            "signing_decision_preflight_envelope": {
                "machine_verifiable": True,
                "allows_future_authorization_signing_decision_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "rejects_direct_database_apply": True,
                "requires_post_apply_verifier": True,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_script": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight",
        fake_preflight,
    )

    result = smoke._pchome_auto_policy_signing_decision_preflight_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signing_decision_preflight_pass_count"] == 12
    assert result["details"]["signing_decision_input_requirement_count"] == 10
    assert result["details"]["signing_decision_rejection_reason_count"] == 11
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["allows_future_authorization_signing_decision_lane"] is True
    assert result["details"]["rejects_direct_database_apply"] is True
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signing_decision_closeout_lane"
    )


def test_pchome_auto_policy_signing_decision_closeout_reports_unsigned_no_write_package(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_closeout(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_decision_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_decision_preflight"
            ),
            "summary": {
                "authorization_signing_decision_closeout_ready_count": 1,
                "authorization_signing_decision_preflight_ready_count": 1,
                "signing_decision_closeout_check_count": 12,
                "signing_decision_closeout_pass_count": 12,
                "signing_decision_closeout_waiting_count": 0,
                "signing_decision_preflight_check_count": 12,
                "signing_decision_input_requirement_count": 10,
                "signing_decision_rejection_reason_count": 11,
                "required_issuer_evidence_count": 9,
                "nonsecret_authorization_claim_count": 8,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "reads_secret_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signing_decision_closeout": {
                "ready_for_future_signing_decision_closeout": True,
                "can_enter_unsigned_signing_decision_package_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
            },
            "unsigned_signing_decision_package": {
                "authorization_material_type": "unsigned_signing_decision_package",
                "ready_for_future_unsigned_signing_decision_package": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "writes_database_in_preview": False,
            },
            "signing_decision_closeout_contract": {
                "machine_verifiable": True,
                "permits_future_unsigned_signing_decision_package_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_script": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout",
        fake_closeout,
    )

    result = smoke._pchome_auto_policy_signing_decision_closeout_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signing_decision_closeout_pass_count"] == 12
    assert result["details"]["signing_decision_input_requirement_count"] == 10
    assert result["details"]["signing_decision_rejection_reason_count"] == 11
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["permits_future_unsigned_signing_decision_package_lane"] is True
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signing_issuer_guard_lane"
    )


def test_pchome_auto_policy_signing_issuer_guard_reports_signable_no_write_boundary(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_guard(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_issuer_guard"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_decision_closeout"
            ),
            "summary": {
                "authorization_signing_issuer_guard_ready_count": 1,
                "signing_issuer_guard_check_count": 12,
                "signing_issuer_guard_pass_count": 12,
                "signing_issuer_guard_waiting_count": 0,
                "authorization_signing_decision_closeout_ready_count": 1,
                "signing_decision_closeout_check_count": 12,
                "signing_decision_input_requirement_count": 10,
                "signing_decision_rejection_reason_count": 11,
                "required_issuer_evidence_count": 9,
                "nonsecret_authorization_claim_count": 8,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signing_issuer_guard": {
                "ready_for_future_signing_issuer_guard": True,
                "can_enter_future_authorization_signing_issuer_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
            },
            "signable_request_boundary": {
                "request_boundary_type": "future_signable_request_boundary",
                "ready_for_future_signable_request_boundary": True,
                "can_enter_future_authorization_signing_issuer_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
            },
            "signing_issuer_guard_contract": {
                "machine_verifiable": True,
                "permits_future_authorization_signing_issuer_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard",
        fake_guard,
    )

    result = smoke._pchome_auto_policy_signing_issuer_guard_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signing_issuer_guard_pass_count"] == 12
    assert result["details"]["signing_decision_closeout_check_count"] == 12
    assert result["details"]["signing_decision_input_requirement_count"] == 10
    assert result["details"]["signing_decision_rejection_reason_count"] == 11
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["ready_for_future_signable_request_boundary"] is True
    assert result["details"]["permits_future_authorization_signing_issuer_lane"] is True
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signing_issuer_closeout_lane"
    )


def test_pchome_auto_policy_signing_issuer_closeout_reports_final_signable_no_write_package(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_closeout(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_issuer_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_issuer_guard"
            ),
            "summary": {
                "authorization_signing_issuer_closeout_ready_count": 1,
                "signing_issuer_closeout_check_count": 12,
                "signing_issuer_closeout_pass_count": 12,
                "signing_issuer_closeout_waiting_count": 0,
                "authorization_signing_issuer_guard_ready_count": 1,
                "signing_issuer_guard_check_count": 12,
                "signing_decision_input_requirement_count": 10,
                "signing_decision_rejection_reason_count": 11,
                "required_issuer_evidence_count": 9,
                "nonsecret_authorization_claim_count": 8,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signing_issuer_closeout": {
                "ready_for_future_signing_issuer_closeout": True,
                "can_enter_future_final_signable_request_package_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
            },
            "final_signable_request_package": {
                "authorization_material_type": "final_signable_request_package",
                "ready_for_future_final_signable_request_package": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
            },
            "signing_issuer_closeout_contract": {
                "machine_verifiable": True,
                "permits_future_final_signable_request_package_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout",
        fake_closeout,
    )

    result = smoke._pchome_auto_policy_signing_issuer_closeout_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signing_issuer_closeout_pass_count"] == 12
    assert result["details"]["signing_issuer_guard_check_count"] == 12
    assert result["details"]["signing_decision_input_requirement_count"] == 10
    assert result["details"]["signing_decision_rejection_reason_count"] == 11
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["ready_for_future_final_signable_request_package"] is True
    assert result["details"]["permits_future_final_signable_request_package_lane"] is True
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signing_execution_preflight_lane"
    )


def test_pchome_auto_policy_signing_execution_preflight_reports_operator_secret_boundary_no_write(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_preflight(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_execution_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_issuer_closeout"
            ),
            "summary": {
                "authorization_signing_execution_preflight_ready_count": 1,
                "signing_execution_preflight_check_count": 12,
                "signing_execution_preflight_pass_count": 12,
                "signing_execution_preflight_waiting_count": 0,
                "authorization_signing_issuer_closeout_ready_count": 1,
                "signing_issuer_closeout_check_count": 12,
                "signing_issuer_closeout_pass_count": 12,
                "final_signable_request_package_ready_count": 1,
                "operator_held_secret_boundary_count": 1,
                "signing_execution_input_requirement_count": 10,
                "signing_execution_abort_condition_count": 8,
                "rollback_boundary_count": 4,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "writes_script_count": 0,
                "writes_artifact_count": 0,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_migration_count": 0,
                "executes_endpoint_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signing_execution_preflight": {
                "ready_for_future_signing_execution_preflight": True,
                "can_enter_future_authorization_signing_execution_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
            },
            "signing_execution_preflight_package": {
                "authorization_material_type": "signing_execution_preflight_package",
                "ready_for_future_signing_execution_preflight": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "required_nonsecret_input_count": 10,
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "executes_shell_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
                "command_preview": {
                    "mode": "future_command_shape_only",
                    "redacts_secret_values": True,
                    "executes_in_preview": False,
                    "signs_database_apply_authorization": False,
                    "writes_database": False,
                },
            },
            "operator_held_secret_boundary_contract": {
                "secret_reference_mode": "external_runtime_reference_only",
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "accepts_plaintext_secret": False,
                "permits_secret_value_logging": False,
            },
            "signing_execution_preflight_contract": {
                "machine_verifiable": True,
                "permits_future_explicit_authorization_signing_execution_lane": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "executes_in_preview": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "writes_file": False,
                "writes_script_in_preview": False,
                "writes_artifact_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight",
        fake_preflight,
    )

    result = smoke._pchome_auto_policy_signing_execution_preflight_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signing_execution_preflight_pass_count"] == 12
    assert result["details"]["signing_issuer_closeout_check_count"] == 12
    assert result["details"]["final_signable_request_package_ready_count"] == 1
    assert result["details"]["operator_held_secret_boundary_count"] == 1
    assert result["details"]["signing_execution_input_requirement_count"] == 10
    assert result["details"]["signing_execution_abort_condition_count"] == 8
    assert result["details"]["rollback_boundary_count"] == 4
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["command_preview_redacts_secret_values"] is True
    assert result["details"]["command_preview_executes_in_preview"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["ready_for_future_signing_execution_preflight"] is True
    assert (
        result["details"]["permits_future_explicit_authorization_signing_execution_lane"]
        is True
    )
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signing_execution_closeout_lane"
    )


def test_pchome_auto_policy_signing_execution_closeout_reports_unsigned_receipt_boundary_no_signing(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_closeout(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_execution_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_execution_preflight"
            ),
            "summary": {
                "authorization_signing_execution_closeout_ready_count": 1,
                "signing_execution_closeout_check_count": 12,
                "signing_execution_closeout_pass_count": 12,
                "signing_execution_closeout_waiting_count": 0,
                "authorization_signing_execution_preflight_ready_count": 1,
                "signing_execution_preflight_check_count": 12,
                "signing_execution_preflight_pass_count": 12,
                "unsigned_signed_authorization_receipt_boundary_count": 1,
                "operator_held_secret_boundary_count": 1,
                "signing_execution_input_requirement_count": 10,
                "signing_execution_abort_condition_count": 8,
                "rollback_boundary_count": 4,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "writes_script_count": 0,
                "writes_artifact_count": 0,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_migration_count": 0,
                "executes_endpoint_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signing_execution_closeout": {
                "ready_for_future_signing_execution_closeout": True,
                "can_enter_future_unsigned_signed_authorization_receipt_boundary": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
            },
            "unsigned_signed_authorization_receipt_boundary": {
                "authorization_material_type": "unsigned_signed_authorization_receipt_boundary",
                "ready_for_future_unsigned_signed_authorization_receipt_boundary": True,
                "ready_for_future_signed_authorization_receipt_lane": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "executes_shell_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "operator_held_secret_boundary_contract": {
                    "secret_reference_mode": "external_runtime_reference_only",
                    "secret_material_included": False,
                    "secret_material_required_in_preview": False,
                    "reads_secret_in_preview": False,
                    "accepts_plaintext_secret": False,
                    "permits_secret_value_logging": False,
                },
                "command_preview": {
                    "mode": "future_command_shape_only",
                    "redacts_secret_values": True,
                    "executes_in_preview": False,
                    "signs_database_apply_authorization": False,
                    "writes_database": False,
                },
            },
            "signing_execution_closeout_contract": {
                "machine_verifiable": True,
                "permits_future_unsigned_signed_authorization_receipt_boundary": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "executes_in_preview": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "writes_file": False,
                "writes_script_in_preview": False,
                "writes_artifact_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout",
        fake_closeout,
    )

    result = smoke._pchome_auto_policy_signing_execution_closeout_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signing_execution_closeout_pass_count"] == 12
    assert result["details"]["signing_execution_preflight_check_count"] == 12
    assert result["details"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert result["details"]["operator_held_secret_boundary_count"] == 1
    assert result["details"]["signing_execution_input_requirement_count"] == 10
    assert result["details"]["signing_execution_abort_condition_count"] == 8
    assert result["details"]["rollback_boundary_count"] == 4
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["command_preview_redacts_secret_values"] is True
    assert result["details"]["command_preview_executes_in_preview"] is False
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["ready_for_future_signing_execution_closeout"] is True
    assert (
        result["details"][
            "ready_for_future_unsigned_signed_authorization_receipt_boundary"
        ]
        is True
    )
    assert result["details"]["ready_for_future_signed_authorization_receipt_lane"] is True
    assert (
        result["details"][
            "permits_future_unsigned_signed_authorization_receipt_boundary"
        ]
        is True
    )
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signed_receipt_preflight_lane"
    )


def test_pchome_auto_policy_signed_receipt_preflight_reports_external_evidence_boundary_no_receipt(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_preflight(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_preflight"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signing_execution_closeout"
            ),
            "summary": {
                "authorization_signed_receipt_preflight_ready_count": 1,
                "signed_receipt_preflight_check_count": 12,
                "signed_receipt_preflight_pass_count": 12,
                "signed_receipt_preflight_waiting_count": 0,
                "authorization_signing_execution_closeout_ready_count": 1,
                "signing_execution_closeout_check_count": 12,
                "unsigned_signed_authorization_receipt_boundary_count": 1,
                "external_signing_receipt_evidence_boundary_count": 1,
                "required_external_receipt_evidence_count": 10,
                "external_receipt_acceptance_gate_count": 8,
                "operator_held_secret_boundary_count": 1,
                "signing_execution_input_requirement_count": 10,
                "signing_execution_abort_condition_count": 8,
                "rollback_boundary_count": 4,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "writes_script_count": 0,
                "writes_artifact_count": 0,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_migration_count": 0,
                "executes_endpoint_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signed_receipt_preflight": {
                "ready_for_future_signed_authorization_receipt_preflight": True,
                "can_enter_future_external_signing_receipt_evidence_boundary": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
            },
            "external_signing_receipt_evidence_boundary": {
                "authorization_material_type": "external_signing_receipt_evidence_boundary",
                "ready_for_future_external_signing_receipt_evidence_boundary": True,
                "ready_for_future_signed_authorization_receipt_lane": True,
                "required_external_receipt_evidence": [
                    "external_receipt_id",
                    "payload_sha256",
                    "receipt_sha256",
                    "signer_key_id_reference",
                    "signature_algorithm_reference",
                    "detached_signature_verification_status",
                    "same_run_production_truth",
                    "post_apply_verifier_endpoint",
                    "rollback_boundary",
                    "abort_conditions",
                ],
                "required_external_receipt_evidence_count": 10,
                "external_receipt_acceptance_gate_count": 8,
                "external_signed_authorization_receipt_required_in_future": True,
                "external_signed_authorization_receipt_included": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "signer_key_id_reference_only": True,
                "signature_algorithm_reference_only": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "executes_shell_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "operator_held_secret_boundary_contract": {
                    "secret_reference_mode": "external_runtime_reference_only",
                    "secret_material_included": False,
                    "secret_material_required_in_preview": False,
                    "reads_secret_in_preview": False,
                    "accepts_plaintext_secret": False,
                    "permits_secret_value_logging": False,
                },
            },
            "signed_receipt_preflight_contract": {
                "machine_verifiable": True,
                "permits_future_external_signing_receipt_evidence_boundary": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "executes_in_preview": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "writes_file": False,
                "writes_script_in_preview": False,
                "writes_artifact_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "persists_receipt": False,
                "updates_mapping": False,
                "dispatches_telegram": False,
                "llm_calls_in_gate": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight",
        fake_preflight,
    )

    result = smoke._pchome_auto_policy_signed_receipt_preflight_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signed_receipt_preflight_pass_count"] == 12
    assert result["details"]["signing_execution_closeout_check_count"] == 12
    assert result["details"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert result["details"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["operator_held_secret_boundary_count"] == 1
    assert result["details"]["signing_execution_input_requirement_count"] == 10
    assert result["details"]["signing_execution_abort_condition_count"] == 8
    assert result["details"]["rollback_boundary_count"] == 4
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["external_signed_authorization_receipt_required_in_future"] is True
    assert result["details"]["external_signed_authorization_receipt_included"] is False
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["signer_key_id_reference_only"] is True
    assert result["details"]["signature_algorithm_reference_only"] is True
    assert result["details"]["detached_signature_verification_required"] is True
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert (
        result["details"]["ready_for_future_signed_authorization_receipt_preflight"]
        is True
    )
    assert (
        result["details"]["can_enter_future_external_signing_receipt_evidence_boundary"]
        is True
    )
    assert (
        result["details"]["ready_for_future_external_signing_receipt_evidence_boundary"]
        is True
    )
    assert result["details"]["ready_for_future_signed_authorization_receipt_lane"] is True
    assert (
        result["details"][
            "permits_future_external_signing_receipt_evidence_boundary"
        ]
        is True
    )
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signed_receipt_closeout_lane"
    )


def test_pchome_auto_policy_signed_receipt_closeout_reports_detached_verification_boundary_no_receipt(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_closeout(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_closeout"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_preflight"
            ),
            "summary": {
                "authorization_signed_receipt_closeout_ready_count": 1,
                "signed_receipt_closeout_check_count": 12,
                "signed_receipt_closeout_pass_count": 12,
                "signed_receipt_closeout_waiting_count": 0,
                "authorization_signed_receipt_preflight_ready_count": 1,
                "signed_receipt_preflight_check_count": 12,
                "external_signing_receipt_evidence_boundary_count": 1,
                "detached_receipt_verification_boundary_count": 1,
                "required_external_receipt_evidence_count": 10,
                "external_receipt_acceptance_gate_count": 8,
                "detached_receipt_verification_check_count": 10,
                "operator_held_secret_boundary_count": 1,
                "signing_execution_input_requirement_count": 10,
                "signing_execution_abort_condition_count": 8,
                "rollback_boundary_count": 4,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "writes_script_count": 0,
                "writes_artifact_count": 0,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_migration_count": 0,
                "executes_endpoint_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_authorization_signed_receipt_closeout": {
                "ready_for_future_signed_authorization_receipt_closeout": True,
                "can_enter_future_detached_receipt_verification_boundary": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "external_signed_authorization_receipt_included": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
            },
            "detached_receipt_verification_boundary": {
                "authorization_material_type": "detached_receipt_verification_boundary",
                "ready_for_future_detached_receipt_verification_boundary": True,
                "ready_for_future_signed_authorization_receipt_verification_lane": True,
                "required_external_receipt_evidence_count": 10,
                "external_receipt_acceptance_gate_count": 8,
                "detached_receipt_verification_check_count": 10,
                "detached_receipt_verification_checks": [
                    "external_receipt_id_present",
                    "payload_sha256_present",
                    "receipt_sha256_present",
                    "signer_key_id_reference_present",
                    "signature_algorithm_reference_present",
                    "detached_signature_verification_status_passed",
                    "same_run_production_truth_present",
                    "post_apply_verifier_endpoint_present",
                    "rollback_boundary_present",
                    "abort_conditions_present",
                ],
                "requires_detached_signature_verification": True,
                "detached_signature_verification_performed": False,
                "external_signed_authorization_receipt_required_in_future": True,
                "external_signed_authorization_receipt_included": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "signer_key_id_reference_only": True,
                "signature_algorithm_reference_only": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "executes_shell_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "target_file": "migrations/045_pchome_auto_policy_evidence_receipts.sql",
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "operator_held_secret_boundary_contract": {
                    "secret_reference_mode": "external_runtime_reference_only",
                    "secret_material_included": False,
                    "secret_material_required_in_preview": False,
                    "reads_secret_in_preview": False,
                    "accepts_plaintext_secret": False,
                    "permits_secret_value_logging": False,
                },
            },
            "signed_receipt_closeout_contract": {
                "machine_verifiable": True,
                "permits_future_detached_receipt_verification_boundary": True,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "executes_in_preview": False,
                "secret_material_required_in_preview": False,
            },
            "safety": {
                "reads_secret_in_preview": False,
                "writes_file": False,
                "writes_script_in_preview": False,
                "writes_artifact_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "persists_receipt": False,
                "updates_mapping": False,
                "dispatches_telegram": False,
                "llm_calls_in_gate": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout",
        fake_closeout,
    )

    result = smoke._pchome_auto_policy_signed_receipt_closeout_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signed_receipt_closeout_pass_count"] == 12
    assert result["details"]["signed_receipt_preflight_check_count"] == 12
    assert result["details"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert result["details"]["detached_receipt_verification_boundary_count"] == 1
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["detached_receipt_verification_check_count"] == 10
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["requires_detached_signature_verification"] is True
    assert result["details"]["detached_signature_verification_performed"] is False
    assert (
        result["details"][
            "external_signed_authorization_receipt_required_in_future"
        ]
        is True
    )
    assert (
        result["details"]["external_signed_authorization_receipt_included"]
        is False
    )
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["signer_key_id_reference_only"] is True
    assert result["details"]["signature_algorithm_reference_only"] is True
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert (
        result["details"]["ready_for_future_signed_authorization_receipt_closeout"]
        is True
    )
    assert (
        result["details"]["can_enter_future_detached_receipt_verification_boundary"]
        is True
    )
    assert (
        result["details"]["ready_for_future_detached_receipt_verification_boundary"]
        is True
    )
    assert (
        result["details"][
            "ready_for_future_signed_authorization_receipt_verification_lane"
        ]
        is True
    )
    assert (
        result["details"]["permits_future_detached_receipt_verification_boundary"]
        is True
    )
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_signed_receipt_evidence_intake_lane"
    )


def test_pchome_auto_policy_signed_receipt_evidence_intake_reports_schema_no_verification(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    from services import pchome_mapping_backlog_service as backlog

    captured = {}

    def fake_intake(*_args, **kwargs):
        captured.update(kwargs)
        return {
            "policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_evidence_intake"
            ),
            "result": "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_READY",
            "source_policy": (
                "read_only_pchome_growth_auto_policy_db_apply_authorization_"
                "signed_receipt_closeout"
            ),
            "summary": {
                "authorization_signed_receipt_evidence_intake_ready_count": 1,
                "signed_receipt_evidence_intake_check_count": 12,
                "signed_receipt_evidence_intake_pass_count": 12,
                "signed_receipt_evidence_intake_waiting_count": 0,
                "authorization_signed_receipt_closeout_ready_count": 1,
                "signed_receipt_closeout_check_count": 12,
                "authorization_signed_receipt_preflight_ready_count": 1,
                "signed_receipt_preflight_check_count": 12,
                "external_signing_receipt_evidence_boundary_count": 1,
                "detached_receipt_verification_boundary_count": 1,
                "detached_verification_evidence_schema_count": 1,
                "required_external_receipt_evidence_count": 10,
                "external_receipt_acceptance_gate_count": 8,
                "detached_receipt_verification_check_count": 10,
                "detached_verification_evidence_field_count": 12,
                "detached_verification_acceptance_gate_count": 10,
                "operator_held_secret_boundary_count": 1,
                "rollback_boundary_count": 4,
                "post_apply_verifier_required_count": 1,
                "same_run_truth_required_count": 1,
                "writes_script_count": 0,
                "writes_artifact_count": 0,
                "reads_secret_count": 0,
                "executes_script_count": 0,
                "executes_migration_count": 0,
                "executes_endpoint_count": 0,
                "executes_sql_count": 0,
                "writes_database_count": 0,
                "signs_database_apply_authorization_count": 0,
                "primary_human_gate_count": 0,
                "manual_review_required_count": 0,
            },
            "future_signed_authorization_receipt_evidence_intake": {
                "ready_for_future_signed_authorization_receipt_evidence_intake": True,
                "can_enter_future_detached_verification_evidence_validation": True,
                "external_signed_authorization_receipt_evidence_schema_ready": True,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "detached_signature_verification_performed": False,
                "external_signed_authorization_receipt_included": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "reads_secret_in_preview": False,
                "manual_review_mode": "exception_only",
            },
            "detached_verification_evidence_schema": {
                "authorization_material_type": "detached_verification_evidence_schema",
                "ready_for_future_detached_verification_evidence_schema": True,
                "required_external_receipt_evidence_count": 10,
                "external_receipt_acceptance_gate_count": 8,
                "detached_receipt_verification_check_count": 10,
                "detached_verification_evidence_fields": [
                    "external_receipt_id",
                    "source_signed_receipt_preflight_id",
                    "source_external_receipt_evidence_boundary_id",
                    "source_signed_receipt_closeout_id",
                    "source_detached_receipt_verification_boundary_id",
                    "payload_sha256",
                    "receipt_sha256",
                    "signer_key_id_reference",
                    "signature_algorithm_reference",
                    "detached_signature_verification_status",
                    "verified_at_utc",
                    "verifier_receipt_sha256",
                ],
                "detached_verification_evidence_field_count": 12,
                "detached_verification_acceptance_gates": [
                    "production_truth_matches_intake_run",
                    "source_detached_boundary_id_matches",
                    "source_external_receipt_evidence_boundary_id_matches",
                    "source_signed_receipt_preflight_id_matches",
                    "payload_hash_matches_final_signable_request_package",
                    "receipt_hash_is_present_and_nonempty",
                    "signer_key_id_is_reference_only",
                    "signature_algorithm_is_reference_only",
                    "detached_signature_verification_status_is_passed",
                    "no_secret_signature_or_signed_receipt_body_in_ai_payload",
                ],
                "detached_verification_acceptance_gate_count": 10,
                "requires_detached_signature_verification": True,
                "detached_signature_verification_performed": False,
                "external_signed_authorization_receipt_required_in_future": True,
                "external_signed_authorization_receipt_included": False,
                "signed_authorization_receipt_included": False,
                "signature_material_included": False,
                "signer_key_id_reference_only": True,
                "signature_algorithm_reference_only": True,
                "secret_material_included": False,
                "secret_material_required_in_preview": False,
                "accepts_plaintext_secret": False,
                "reads_secret_in_preview": False,
                "executes_shell_in_preview": False,
                "executes_sql_in_preview": False,
                "writes_database_in_preview": False,
                "ready_for_database_apply_now": False,
                "issues_database_apply_authorization": False,
                "signs_database_apply_authorization": False,
                "target_file": "migrations/045_pchome_auto_policy_evidence_receipts.sql",
                "hash_matches": True,
                "requires_post_apply_verifier": True,
                "requires_fresh_production_truth_in_same_run": True,
                "operator_held_secret_boundary_contract": {
                    "secret_reference_mode": "external_runtime_reference_only",
                    "secret_material_included": False,
                    "secret_material_required_in_preview": False,
                    "reads_secret_in_preview": False,
                    "accepts_plaintext_secret": False,
                    "permits_secret_value_logging": False,
                },
            },
            "signed_receipt_evidence_intake_contract": {
                "machine_verifiable": True,
                "permits_future_detached_verification_evidence_validation": True,
                "accepts_plaintext_secret": False,
                "detached_signature_verification_performed": False,
                "issues_database_apply_authorization": False,
                "ready_for_database_apply_now": False,
                "signs_database_apply_authorization": False,
                "writes_database": False,
                "executes_in_preview": False,
                "secret_material_required_in_preview": False,
                "manual_review_mode": "exception_only",
            },
            "safety": {
                "reads_secret_in_preview": False,
                "writes_file": False,
                "writes_script_in_preview": False,
                "writes_artifact_in_preview": False,
                "executes_script": False,
                "executes_endpoint": False,
                "executes_migration": False,
                "executes_sql": False,
                "writes_database": False,
                "signs_database_apply_authorization": False,
                "performs_detached_signature_verification": False,
                "persists_receipt": False,
                "updates_mapping": False,
                "dispatches_telegram": False,
                "llm_calls_in_gate": False,
                "manual_review_mode": "exception_only",
            },
        }

    monkeypatch.setattr(
        backlog,
        "build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake",
        fake_intake,
    )

    result = smoke._pchome_auto_policy_signed_receipt_evidence_intake_check()

    assert result["status"] == "ok"
    assert captured["execute_fetch"] is True
    assert captured["http_get"] is smoke._pchome_auto_policy_machine_fetch_evidence_get
    assert result["details"]["signed_receipt_evidence_intake_pass_count"] == 12
    assert result["details"]["signed_receipt_closeout_check_count"] == 12
    assert result["details"]["detached_verification_evidence_schema_count"] == 1
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["detached_receipt_verification_check_count"] == 10
    assert result["details"]["detached_verification_evidence_field_count"] == 12
    assert result["details"]["detached_verification_acceptance_gate_count"] == 10
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["requires_detached_signature_verification"] is True
    assert result["details"]["detached_signature_verification_performed"] is False
    assert (
        result["details"]["external_signed_authorization_receipt_required_in_future"]
        is True
    )
    assert (
        result["details"]["external_signed_authorization_receipt_included"]
        is False
    )
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["signer_key_id_reference_only"] is True
    assert result["details"]["signature_algorithm_reference_only"] is True
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["accepts_plaintext_secret"] is False
    assert (
        result["details"][
            "ready_for_future_signed_authorization_receipt_evidence_intake"
        ]
        is True
    )
    assert (
        result["details"][
            "can_enter_future_detached_verification_evidence_validation"
        ]
        is True
    )
    assert (
        result["details"][
            "external_signed_authorization_receipt_evidence_schema_ready"
        ]
        is True
    )
    assert (
        result["details"]["ready_for_future_detached_verification_evidence_schema"]
        is True
    )
    assert (
        result["details"][
            "permits_future_detached_verification_evidence_validation"
        ]
        is True
    )
    assert result["details"]["performs_detached_signature_verification"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_detached_verification_evidence_validation_lane"
    )


def test_pchome_auto_policy_detached_verification_evidence_validation_reports_boundary_no_persist():
    from services import ai_automation_smoke_service as smoke

    result = (
        smoke._pchome_auto_policy_detached_verification_evidence_validation_check()
    )

    assert result["status"] == "ok"
    assert result["details"]["result"] == (
        "DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_READY"
    )
    assert (
        result["details"][
            "detached_verification_evidence_validation_pass_count"
        ]
        == 12
    )
    assert result["details"]["signed_receipt_evidence_intake_check_count"] == 12
    assert result["details"]["detached_verification_evidence_schema_count"] == 1
    assert result["details"]["verifier_receipt_closeout_boundary_count"] == 1
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["detached_receipt_verification_check_count"] == 10
    assert result["details"]["detached_verification_evidence_field_count"] == 12
    assert result["details"]["detached_verification_acceptance_gate_count"] == 10
    assert result["details"]["verifier_receipt_field_count"] == 12
    assert result["details"]["verifier_receipt_acceptance_gate_count"] == 10
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["requires_detached_signature_verification"] is True
    assert result["details"]["detached_signature_verification_performed"] is False
    assert result["details"]["verifier_receipt_persisted"] is False
    assert (
        result["details"]["external_signed_authorization_receipt_required_in_future"]
        is True
    )
    assert result["details"]["external_signed_authorization_receipt_included"] is False
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["accepts_plaintext_secret"] is False
    assert (
        result["details"][
            "ready_for_future_detached_verification_evidence_validation"
        ]
        is True
    )
    assert result["details"]["can_enter_future_verifier_receipt_closeout"] is True
    assert result["details"]["verifier_receipt_closeout_boundary_ready"] is True
    assert (
        result["details"]["ready_for_future_verifier_receipt_closeout_boundary"]
        is True
    )
    assert result["details"]["permits_future_verifier_receipt_closeout"] is True
    assert result["details"]["persists_verifier_receipt"] is False
    assert result["details"]["performs_detached_signature_verification"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_verifier_receipt_closeout_lane"
    )


def test_pchome_auto_policy_verifier_receipt_closeout_reports_handoff_no_persist():
    from services import ai_automation_smoke_service as smoke

    result = smoke._pchome_auto_policy_verifier_receipt_closeout_check()

    assert result["status"] == "ok"
    assert result["details"]["result"] == (
        "DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_READY"
    )
    assert result["details"]["verifier_receipt_closeout_pass_count"] == 12
    assert result["details"]["verifier_receipt_closeout_check_count"] == 12
    assert (
        result["details"][
            "detached_verification_evidence_validation_check_count"
        ]
        == 12
    )
    assert result["details"]["signed_receipt_evidence_intake_check_count"] == 12
    assert result["details"]["verifier_receipt_closeout_boundary_count"] == 1
    assert result["details"]["verifier_receipt_evidence_handoff_count"] == 1
    assert result["details"]["verifier_receipt_field_count"] == 12
    assert result["details"]["verifier_receipt_acceptance_gate_count"] == 10
    assert result["details"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert result["details"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["detached_verification_evidence_field_count"] == 12
    assert result["details"]["detached_verification_acceptance_gate_count"] == 10
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["manual_review_required_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["executes_script_count"] == 0
    assert result["details"]["executes_sql_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert result["details"]["secret_reference_mode"] == "external_runtime_reference_only"
    assert result["details"]["requires_detached_signature_verification"] is True
    assert result["details"]["detached_signature_verification_performed"] is False
    assert result["details"]["verifier_receipt_persisted"] is False
    assert (
        result["details"]["external_signed_authorization_receipt_required_in_future"]
        is True
    )
    assert result["details"]["external_signed_authorization_receipt_included"] is False
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["accepts_plaintext_secret"] is False
    assert result["details"]["ready_for_future_verifier_receipt_closeout"] is True
    assert (
        result["details"][
            "can_enter_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert result["details"]["verifier_receipt_evidence_handoff_ready"] is True
    assert (
        result["details"]["ready_for_future_verifier_receipt_evidence_handoff"]
        is True
    )
    assert (
        result["details"][
            "permits_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert result["details"]["persists_verifier_receipt"] is False
    assert result["details"]["performs_detached_signature_verification"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_database_apply_authorization_verifier_handoff_lane"
    )


def test_pchome_auto_policy_authorization_evidence_execution_preflight_reports_handoff_no_execution():
    from services import ai_automation_smoke_service as smoke

    result = (
        smoke._pchome_auto_policy_authorization_evidence_execution_preflight_check()
    )

    assert result["status"] == "ok"
    assert result["details"]["result"] == (
        "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_READY"
    )
    assert (
        result["details"][
            "authorization_evidence_execution_preflight_pass_count"
        ]
        == 12
    )
    assert (
        result["details"][
            "authorization_evidence_execution_preflight_check_count"
        ]
        == 12
    )
    assert result["details"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert result["details"]["verifier_receipt_closeout_check_count"] == 12
    assert (
        result["details"][
            "detached_verification_evidence_validation_check_count"
        ]
        == 12
    )
    assert result["details"]["verifier_receipt_evidence_handoff_count"] == 1
    assert result["details"]["authorization_evidence_execution_preflight_count"] == 1
    assert result["details"]["authorization_evidence_execution_field_count"] == 12
    assert (
        result["details"]["authorization_evidence_execution_acceptance_gate_count"]
        == 10
    )
    assert result["details"]["verifier_receipt_field_count"] == 12
    assert result["details"]["verifier_receipt_acceptance_gate_count"] == 10
    assert result["details"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert result["details"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["post_apply_verifier_required_count"] == 1
    assert result["details"]["same_run_truth_required_count"] == 1
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["manual_review_required_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["executes_script_count"] == 0
    assert result["details"]["executes_sql_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert (
        result["details"][
            "ready_for_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert (
        result["details"]["can_enter_future_authorization_evidence_execution_closeout"]
        is True
    )
    assert (
        result["details"]["authorization_evidence_execution_preflight_ready"]
        is True
    )
    assert (
        result["details"][
            "ready_for_future_authorization_evidence_execution_preflight"
        ]
        is True
    )
    assert (
        result["details"][
            "permits_future_authorization_evidence_execution_closeout"
        ]
        is True
    )
    assert result["details"]["requires_detached_signature_verification"] is True
    assert result["details"]["detached_signature_verification_performed"] is False
    assert result["details"]["verifier_receipt_persisted"] is False
    assert (
        result["details"]["external_signed_authorization_receipt_required_in_future"]
        is True
    )
    assert result["details"]["external_signed_authorization_receipt_included"] is False
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["accepts_plaintext_secret"] is False
    assert result["details"]["reads_secret_in_preview"] is False
    assert result["details"]["executes_authorization_evidence"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_authorization_evidence_execution_closeout_lane"
    )


def test_pchome_auto_policy_authorization_evidence_execution_closeout_reports_final_gate_no_apply():
    from services import ai_automation_smoke_service as smoke

    result = (
        smoke._pchome_auto_policy_authorization_evidence_execution_closeout_check()
    )

    assert result["status"] == "ok"
    assert result["details"]["result"] == (
        "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_READY"
    )
    assert (
        result["details"][
            "authorization_evidence_execution_closeout_pass_count"
        ]
        == 12
    )
    assert (
        result["details"][
            "authorization_evidence_execution_closeout_check_count"
        ]
        == 12
    )
    assert (
        result["details"][
            "authorization_evidence_execution_closeout_waiting_count"
        ]
        == 0
    )
    assert result["details"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert result["details"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert result["details"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert result["details"]["verifier_receipt_closeout_check_count"] == 12
    assert (
        result["details"][
            "detached_verification_evidence_validation_check_count"
        ]
        == 12
    )
    assert result["details"]["verifier_receipt_evidence_handoff_count"] == 1
    assert result["details"]["authorization_evidence_execution_preflight_count"] == 1
    assert result["details"]["authorization_evidence_execution_closeout_count"] == 1
    assert result["details"]["database_apply_final_verifier_gate_count"] == 1
    assert (
        result["details"][
            "database_apply_authorization_final_verifier_gate_ready_count"
        ]
        == 1
    )
    assert result["details"]["authorization_evidence_execution_closeout_field_count"] == 12
    assert (
        result["details"][
            "authorization_evidence_execution_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert result["details"]["authorization_evidence_execution_field_count"] == 12
    assert (
        result["details"]["authorization_evidence_execution_acceptance_gate_count"]
        == 10
    )
    assert result["details"]["verifier_receipt_field_count"] == 12
    assert result["details"]["verifier_receipt_acceptance_gate_count"] == 10
    assert result["details"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert result["details"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert result["details"]["required_external_receipt_evidence_count"] == 10
    assert result["details"]["external_receipt_acceptance_gate_count"] == 8
    assert result["details"]["post_apply_verifier_required_count"] == 1
    assert result["details"]["same_run_truth_required_count"] == 1
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["manual_review_required_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["executes_script_count"] == 0
    assert result["details"]["executes_sql_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert (
        result["details"][
            "ready_for_future_database_apply_authorization_final_verifier_gate"
        ]
        is True
    )
    assert (
        result["details"][
            "can_enter_future_database_apply_controlled_apply_final_preflight"
        ]
        is True
    )
    assert (
        result["details"]["authorization_evidence_execution_closeout_ready"]
        is True
    )
    assert (
        result["details"][
            "ready_for_future_authorization_evidence_execution_closeout"
        ]
        is True
    )
    assert (
        result["details"][
            "permits_future_database_apply_authorization_final_verifier_gate"
        ]
        is True
    )
    assert (
        result["details"][
            "permits_future_database_apply_controlled_apply_final_preflight"
        ]
        is True
    )
    assert result["details"]["requires_detached_signature_verification"] is True
    assert result["details"]["detached_signature_verification_performed"] is False
    assert result["details"]["verifier_receipt_persisted"] is False
    assert result["details"]["external_signed_authorization_receipt_included"] is False
    assert result["details"]["signed_authorization_receipt_included"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["accepts_plaintext_secret"] is False
    assert result["details"]["reads_secret_in_preview"] is False
    assert result["details"]["executes_authorization_evidence"] is False
    assert result["details"]["executes_database_apply"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["database_apply_authorized"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_database_apply_controlled_apply_final_preflight_lane"
    )


def test_pchome_auto_policy_controlled_apply_final_preflight_reports_bindings_no_apply():
    from services import ai_automation_smoke_service as smoke

    result = smoke._pchome_auto_policy_controlled_apply_final_preflight_check()

    assert result["status"] == "ok"
    assert result["details"]["result"] == (
        "DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_READY"
    )
    assert result["details"]["controlled_apply_final_preflight_pass_count"] == 12
    assert result["details"]["controlled_apply_final_preflight_check_count"] == 12
    assert result["details"]["controlled_apply_final_preflight_waiting_count"] == 0
    assert (
        result["details"]["authorization_evidence_execution_closeout_ready_count"]
        == 1
    )
    assert (
        result["details"]["authorization_evidence_execution_closeout_check_count"]
        == 12
    )
    assert result["details"]["database_apply_final_verifier_gate_count"] == 1
    assert (
        result["details"][
            "database_apply_authorization_final_verifier_gate_ready_count"
        ]
        == 1
    )
    assert result["details"]["controlled_apply_final_preflight_count"] == 1
    assert result["details"]["controlled_apply_final_preflight_field_count"] == 12
    assert (
        result["details"]["controlled_apply_final_preflight_acceptance_gate_count"]
        == 10
    )
    assert result["details"]["rollback_binding_count"] == 1
    assert result["details"]["rollback_binding_field_count"] == 8
    assert result["details"]["post_apply_verifier_binding_count"] == 1
    assert result["details"]["post_apply_verifier_binding_field_count"] == 8
    assert result["details"]["post_apply_verifier_required_count"] == 1
    assert result["details"]["same_run_truth_required_count"] == 1
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["manual_review_required_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["executes_script_count"] == 0
    assert result["details"]["executes_endpoint_count"] == 0
    assert result["details"]["executes_sql_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert (
        result["details"][
            "ready_for_future_database_apply_controlled_apply_final_preflight"
        ]
        is True
    )
    assert (
        result["details"]["can_enter_future_database_apply_controlled_dry_run_package"]
        is True
    )
    assert result["details"]["controlled_apply_final_preflight_ready"] is True
    assert result["details"]["rollback_binding_ready"] is True
    assert result["details"]["post_apply_verifier_binding_ready"] is True
    assert result["details"]["rollback_bound"] is True
    assert result["details"]["post_apply_verifier_bound"] is True
    assert result["details"]["dry_run_only"] is True
    assert result["details"]["check_mode_only"] is True
    assert result["details"]["rollback_execution_authorized"] is False
    assert result["details"]["rollback_executes_sql"] is False
    assert result["details"]["rollback_writes_database"] is False
    assert result["details"]["rollback_reads_secret"] is False
    assert result["details"]["rollback_requires_same_run_truth"] is True
    assert result["details"]["post_apply_verifier_must_run_after_apply"] is True
    assert (
        result["details"]["post_apply_verifier_execution_authorized_in_preview"]
        is False
    )
    assert (
        result["details"]["permits_future_database_apply_controlled_dry_run_package"]
        is True
    )
    assert result["details"]["accepts_plaintext_secret"] is False
    assert result["details"]["reads_secret_in_preview"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["executes_authorization_evidence"] is False
    assert result["details"]["executes_database_apply"] is False
    assert result["details"]["executes_endpoint"] is False
    assert result["details"]["executes_sql"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["database_apply_authorized"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_package_lane"
    )


def test_pchome_auto_policy_controlled_dry_run_package_reports_preview_no_execution():
    from services import ai_automation_smoke_service as smoke

    result = smoke._pchome_auto_policy_controlled_dry_run_package_check()

    assert result["status"] == "ok"
    assert result["details"]["result"] == "DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_READY"
    assert result["details"]["controlled_dry_run_package_pass_count"] == 12
    assert result["details"]["controlled_dry_run_package_check_count"] == 12
    assert result["details"]["controlled_dry_run_package_waiting_count"] == 0
    assert result["details"]["controlled_apply_final_preflight_ready_count"] == 1
    assert result["details"]["controlled_apply_final_preflight_check_count"] == 12
    assert result["details"]["controlled_dry_run_package_count"] == 1
    assert result["details"]["controlled_dry_run_package_field_count"] == 12
    assert result["details"]["controlled_dry_run_acceptance_gate_count"] == 10
    assert result["details"]["dry_run_execution_receipt_preview_count"] == 1
    assert result["details"]["dry_run_execution_receipt_field_count"] == 8
    assert result["details"]["dry_run_result_parser_count"] == 1
    assert result["details"]["dry_run_result_parser_field_count"] == 10
    assert result["details"]["rollback_binding_count"] == 1
    assert result["details"]["post_apply_verifier_binding_count"] == 1
    assert result["details"]["post_apply_verifier_required_count"] == 1
    assert result["details"]["same_run_truth_required_count"] == 1
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["manual_review_required_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["executes_script_count"] == 0
    assert result["details"]["executes_endpoint_count"] == 0
    assert result["details"]["executes_sql_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert (
        result["details"][
            "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is True
    )
    assert (
        result["details"][
            "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is True
    )
    assert result["details"]["controlled_dry_run_package_ready"] is True
    assert result["details"]["dry_run_execution_performed"] is False
    assert (
        result["details"][
            "ready_for_future_database_apply_controlled_dry_run_package"
        ]
        is True
    )
    assert result["details"]["target_migration_hash_locked"] is True
    assert result["details"]["dry_run_only"] is True
    assert result["details"]["check_mode_only"] is True
    assert result["details"]["requires_fresh_production_truth"] is True
    assert result["details"]["requires_post_apply_verifier"] is True
    assert result["details"]["command_shape_dry_run_only"] is True
    assert result["details"]["command_shape_check_mode_only"] is True
    assert result["details"]["command_shape_execution_allowed"] is False
    assert result["details"]["command_shape_shell_command_included"] is False
    assert result["details"]["command_shape_sql_included"] is False
    assert result["details"]["command_shape_endpoint_execution_included"] is False
    assert result["details"]["command_shape_database_write_included"] is False
    assert result["details"]["receipt_dry_run_status"] == "preview_only_not_executed"
    assert result["details"]["receipt_execution_performed"] is False
    assert result["details"]["receipt_stdout_included"] is False
    assert result["details"]["receipt_stderr_included"] is False
    assert result["details"]["receipt_database_apply_authorized"] is False
    assert result["details"]["receipt_executes_shell"] is False
    assert result["details"]["receipt_executes_endpoint"] is False
    assert result["details"]["receipt_executes_sql"] is False
    assert result["details"]["receipt_writes_database"] is False
    assert result["details"]["receipt_reads_secret"] is False
    assert result["details"]["parser_expected_receipt_status"] == (
        "preview_only_not_executed"
    )
    assert result["details"]["parser_execution_required"] is False
    assert result["details"]["parser_stdout_allowed"] is False
    assert result["details"]["parser_stderr_allowed"] is False
    assert result["details"]["parser_database_apply_authorized"] is False
    assert result["details"]["parser_verification_status"] == "schema_preview_ready"
    assert (
        result["details"][
            "permits_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is True
    )
    assert result["details"]["accepts_plaintext_secret"] is False
    assert result["details"]["reads_secret_in_preview"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["executes_authorization_evidence"] is False
    assert result["details"]["executes_database_apply"] is False
    assert result["details"]["executes_endpoint"] is False
    assert result["details"]["executes_sql"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["database_apply_authorized"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_receipt_closeout_lane"
    )


def test_pchome_auto_policy_controlled_dry_run_receipt_closeout_reports_parser_closeout_no_execution():
    from services import ai_automation_smoke_service as smoke

    result = smoke._pchome_auto_policy_controlled_dry_run_receipt_closeout_check()

    assert result["status"] == "ok"
    assert (
        result["details"]["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_READY"
    )
    assert result["details"]["controlled_dry_run_receipt_closeout_pass_count"] == 12
    assert result["details"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert result["details"]["controlled_dry_run_receipt_closeout_waiting_count"] == 0
    assert result["details"]["controlled_dry_run_package_ready_count"] == 1
    assert result["details"]["controlled_dry_run_package_check_count"] == 12
    assert result["details"]["controlled_apply_final_preflight_ready_count"] == 1
    assert result["details"]["controlled_dry_run_receipt_closeout_count"] == 1
    assert result["details"]["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert (
        result["details"]["controlled_dry_run_receipt_closeout_acceptance_gate_count"]
        == 10
    )
    assert result["details"]["dry_run_result_parser_count"] == 1
    assert result["details"]["dry_run_result_parser_field_count"] == 10
    assert result["details"]["receipt_validation_report_count"] == 1
    assert result["details"]["receipt_validation_field_count"] == 8
    assert result["details"]["dry_run_execution_receipt_preview_count"] == 1
    assert result["details"]["dry_run_execution_receipt_field_count"] == 8
    assert result["details"]["rollback_binding_count"] == 1
    assert result["details"]["post_apply_verifier_binding_count"] == 1
    assert result["details"]["post_apply_verifier_required_count"] == 1
    assert result["details"]["same_run_truth_required_count"] == 1
    assert result["details"]["payload_source"] == "local_contract_fixture"
    assert result["details"]["machine_fetch_evidence_source"] == "local_schema_fixture"
    assert result["details"]["outbound_network"] is False
    assert result["details"]["business_data_source"] is False
    assert result["details"]["primary_human_gate_count"] == 0
    assert result["details"]["manual_review_required_count"] == 0
    assert result["details"]["reads_secret_count"] == 0
    assert result["details"]["executes_script_count"] == 0
    assert result["details"]["executes_endpoint_count"] == 0
    assert result["details"]["executes_sql_count"] == 0
    assert result["details"]["writes_database_count"] == 0
    assert result["details"]["signs_database_apply_authorization_count"] == 0
    assert (
        result["details"][
            "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
        ]
        is True
    )
    assert (
        result["details"][
            "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is True
    )
    assert result["details"]["controlled_dry_run_receipt_closeout_ready"] is True
    assert result["details"]["source_controlled_dry_run_package_ready"] is True
    assert result["details"]["dry_run_execution_performed"] is False
    assert (
        result["details"][
            "ready_for_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is True
    )
    assert result["details"]["target_migration_hash_locked"] is True
    assert result["details"]["dry_run_only"] is True
    assert result["details"]["check_mode_only"] is True
    assert result["details"]["receipt_preview_only"] is True
    assert result["details"]["requires_fresh_production_truth"] is True
    assert result["details"]["requires_post_apply_verifier"] is True
    assert (
        result["details"]["receipt_validation_status"]
        == "preview_validated_not_executed"
    )
    assert result["details"]["validation_execution_performed"] is False
    assert result["details"]["validation_stdout_included"] is False
    assert result["details"]["validation_stderr_included"] is False
    assert result["details"]["validation_database_apply_authorized"] is False
    assert result["details"]["validation_executes_shell"] is False
    assert result["details"]["validation_executes_endpoint"] is False
    assert result["details"]["validation_executes_sql"] is False
    assert result["details"]["validation_writes_database"] is False
    assert result["details"]["validation_reads_secret"] is False
    assert result["details"]["parser_expected_receipt_status"] == (
        "preview_only_not_executed"
    )
    assert result["details"]["parser_execution_required"] is False
    assert result["details"]["parser_stdout_allowed"] is False
    assert result["details"]["parser_stderr_allowed"] is False
    assert result["details"]["parser_database_apply_authorized"] is False
    assert result["details"]["parser_verification_status"] == "schema_preview_ready"
    assert (
        result["details"][
            "permits_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is True
    )
    assert result["details"]["accepts_plaintext_secret"] is False
    assert result["details"]["reads_secret_in_preview"] is False
    assert result["details"]["signature_material_included"] is False
    assert result["details"]["secret_material_included"] is False
    assert result["details"]["secret_material_required_in_preview"] is False
    assert result["details"]["executes_authorization_evidence"] is False
    assert result["details"]["executes_database_apply"] is False
    assert result["details"]["executes_endpoint"] is False
    assert result["details"]["executes_sql"] is False
    assert result["details"]["ready_for_database_apply_now"] is False
    assert result["details"]["database_apply_authorized"] is False
    assert result["details"]["issues_database_apply_authorization"] is False
    assert result["details"]["signs_database_apply_authorization"] is False
    assert result["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_runner_readiness_lane"
    )


def test_collect_ai_automation_smoke_persists_recent_history(tmp_path, monkeypatch):
    from services import ai_automation_smoke_service as smoke

    history_path = tmp_path / "smoke_history.jsonl"
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))
    monkeypatch.setattr(smoke, "_HISTORY_LIMIT", 2)
    monkeypatch.setattr(smoke, "_event_router_check", lambda: smoke._check("event", "ok", "ok"))
    monkeypatch.setattr(smoke, "_gemini_egress_check", lambda: smoke._check("gemini", "ok", "ok"))
    monkeypatch.setattr(smoke, "_autoheal_check", lambda: smoke._check("autoheal", "ok", "ok"))
    monkeypatch.setattr(smoke, "_nemotron_check", lambda: smoke._check("nemotron", "ok", "ok"))
    monkeypatch.setattr(smoke, "_embedding_queue_check", lambda: smoke._check("embedding", "ok", "ok"))
    monkeypatch.setattr(smoke, "_elephant_hitl_check", lambda: smoke._check("elephant", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_controlled_apply_drift_monitor_check", lambda: smoke._check("pchome", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_guard_check", lambda: smoke._check("auto-policy", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_decision_preflight_check", lambda: smoke._check("auto-policy preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_decision_closeout_check", lambda: smoke._check("auto-policy closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_issuer_gate_check", lambda: smoke._check("auto-policy issuer", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_decision_preflight_check", lambda: smoke._check("auto-policy signing preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_decision_closeout_check", lambda: smoke._check("auto-policy signing closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_issuer_guard_check", lambda: smoke._check("auto-policy signing issuer guard", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_issuer_closeout_check", lambda: smoke._check("auto-policy signing issuer closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_execution_preflight_check", lambda: smoke._check("auto-policy signing execution preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_execution_closeout_check", lambda: smoke._check("auto-policy signing execution closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_preflight_check", lambda: smoke._check("auto-policy signed receipt preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_closeout_check", lambda: smoke._check("auto-policy signed receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_evidence_intake_check", lambda: smoke._check("auto-policy signed receipt evidence intake", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_detached_verification_evidence_validation_check", lambda: smoke._check("auto-policy detached verification evidence validation", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_verifier_receipt_closeout_check", lambda: smoke._check("auto-policy verifier receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_evidence_execution_preflight_check", lambda: smoke._check("auto-policy authorization evidence execution preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_evidence_execution_closeout_check", lambda: smoke._check("auto-policy authorization evidence execution closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_apply_final_preflight_check", lambda: smoke._check("auto-policy controlled apply final preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_package_check", lambda: smoke._check("auto-policy controlled dry-run package", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_receipt_closeout_check", lambda: smoke._check("auto-policy controlled dry-run receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_runner_readiness_check", lambda: smoke._check("auto-policy controlled dry-run runner readiness", "ok", "ok"))
    monkeypatch.setattr(smoke, "_ai_surface_html_readback_check", lambda: smoke._check("surface", "ok", "ok"))
    monkeypatch.setattr(smoke, "_sitewide_ui_ux_agent_check", lambda: smoke._check("sitewide", "ok", "ok"))
    monkeypatch.setattr(smoke, "_sitewide_visual_qa_check", lambda: smoke._check("visual", "ok", "ok"))
    monkeypatch.setattr(smoke, "_security_governance_review_check", lambda: smoke._check("security governance", "ok", "ok"))
    monkeypatch.setattr(smoke, "_external_mcp_rag_integration_check", lambda: smoke._check("external mcp rag", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_rag_candidate_replay_check", lambda: smoke._check("pixelrag replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_source_contract_replay_worker_check", lambda: smoke._check("pixelrag source contract", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_adapter_preflight_check", lambda: smoke._check("pixelrag marketplace adapter preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_adapter_dry_run_check", lambda: smoke._check("pixelrag marketplace adapter dry-run", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_identity_matcher_replay_check", lambda: smoke._check("pixelrag marketplace identity matcher replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_promotion_gate_replay_check", lambda: smoke._check("pixelrag marketplace promotion gate replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_embedding_signature_guard_replay_check", lambda: smoke._check("pixelrag marketplace embedding signature guard replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_candidate_knowledge_replay_check", lambda: smoke._check("pixelrag marketplace candidate knowledge replay", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_ocr_vlm_replay_check", lambda: smoke._check("pixelrag ocr vlm", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_vlm_route_readiness_check", lambda: smoke._check("pixelrag vlm route", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_vlm_replay_worker_check", lambda: smoke._check("pixelrag vlm worker", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_platform_probe_check", lambda: smoke._check("pixelrag platform probe", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pixelrag_platform_probe_worker_check", lambda: smoke._check("pixelrag platform probe worker", "ok", "ok"))

    first = smoke.collect_ai_automation_smoke(history_limit=5)
    second = smoke.collect_ai_automation_smoke(history_limit=5)
    third = smoke.collect_ai_automation_smoke(history_limit=5)

    assert first["status"] == "ok"
    assert second["history"]["counts"]["ok"] == 2
    assert third["history"]["counts"]["ok"] == 2
    assert len(history_path.read_text(encoding="utf-8").strip().splitlines()) == 2


def test_smoke_history_export_and_clear(tmp_path, monkeypatch):
    from services import ai_automation_smoke_service as smoke

    history_path = tmp_path / "smoke_history.jsonl"
    history_path.write_text(
        '{"generated_at":"2026-04-29T01:00:00","status":"ok"}\n'
        '{"generated_at":"2026-04-29T02:00:00","status":"warning"}\n',
        encoding="utf-8",
    )
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))

    export = smoke.export_smoke_history_jsonl()
    cleared = smoke.clear_smoke_history()

    assert export["count"] == 2
    assert '"status":"warning"' in export["content"]
    assert cleared["cleared"] == 2
    assert not history_path.exists()


def test_smoke_history_daily_summary():
    from services import ai_automation_smoke_service as smoke

    summary = smoke._history_summary([
        {"generated_at": "2026-04-28T23:00:00", "status": "ok"},
        {"generated_at": "2026-04-29T01:00:00", "status": "warning"},
        {"generated_at": "2026-04-29T02:00:00", "status": "critical"},
    ])

    assert summary["daily"] == [
        {"date": "2026-04-28", "ok": 1, "warning": 0, "critical": 0, "total": 1},
        {"date": "2026-04-29", "ok": 0, "warning": 1, "critical": 1, "total": 2},
    ]


def test_scheduled_automation_health_summary_reads_history_without_side_effects(tmp_path, monkeypatch):
    from datetime import datetime
    from services import ai_automation_smoke_service as smoke

    monkeypatch.setattr(
        smoke,
        "_security_governance_review_check",
        lambda: smoke._check(
            "Security governance automation review",
            "ok",
            "security governance ok",
            {"next_machine_action": "keep_monitoring"},
        ),
    )

    history_path = tmp_path / "smoke_history.jsonl"
    history_path.write_text(
        json.dumps({
            "generated_at": datetime.now().isoformat(timespec="seconds"),
            "status": "ok",
            "summary": {"ok": 45, "warning": 0, "critical": 0, "total": 45},
            "checks": [
                {
                    "name": "PChome 受控落地 drift monitor",
                    "status": "ok",
                    "summary": "PChome controlled apply drift 已驗證 4/4，目前 0 drift",
                    "details": {
                        "result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIED",
                        "source_receipt_replay_result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_RECEIPT_REPLAYED",
                        "selector_count": 4,
                        "readback_pass_count": 4,
                        "drift_count": 0,
                    },
                },
                _auto_policy_guard_history_check(),
                _auto_policy_decision_preflight_history_check(),
                _auto_policy_decision_closeout_history_check(),
                _auto_policy_authorization_issuer_gate_history_check(),
                _auto_policy_signing_decision_preflight_history_check(),
                _auto_policy_signing_decision_closeout_history_check(),
                _auto_policy_signing_issuer_guard_history_check(),
                _auto_policy_signing_issuer_closeout_history_check(),
                _auto_policy_signing_execution_preflight_history_check(),
                _auto_policy_signing_execution_closeout_history_check(),
                _auto_policy_signed_receipt_preflight_history_check(),
                _auto_policy_signed_receipt_closeout_history_check(),
                _auto_policy_signed_receipt_evidence_intake_history_check(),
                _auto_policy_detached_verification_evidence_validation_history_check(),
                _auto_policy_verifier_receipt_closeout_history_check(),
                _auto_policy_authorization_evidence_execution_preflight_history_check(),
                _auto_policy_authorization_evidence_execution_closeout_history_check(),
                _auto_policy_controlled_apply_final_preflight_history_check(),
                _auto_policy_controlled_dry_run_package_history_check(),
                _auto_policy_controlled_dry_run_receipt_closeout_history_check(),
                _auto_policy_controlled_dry_run_runner_readiness_history_check(),
                {
                    "name": "AI surface HTML readback",
                    "status": "ok",
                    "summary": "AI surface HTML readback 通過 10/10，無產品面 raw wording",
                    "details": {
                        "policy": "read_only_ai_surface_html_readback_v1",
                        "checked_surface_count": 10,
                        "pass_count": 10,
                        "failed_count": 0,
                        "forbidden_leak_count": 0,
                    },
                },
                {
                    "name": "Sitewide UI/UX Agent readback",
                    "status": "ok",
                    "summary": "Sitewide UI/UX Agent ok/no-op，整站專業化 surface 無退化",
                    "details": {
                        "policy": "read_only_sitewide_ui_ux_agent_inventory_v1",
                        "template_count": 55,
                        "high_priority_template_count": 31,
                        "compact_guardrail_count": 29,
                        "issue_surface_count": 0,
                        "raw_engineering_issue_count": 0,
                        "repair_package_status": "no_op",
                        "repair_action_count": 0,
                    },
                },
                    {
                        "name": "Sitewide visual QA readback",
                        "status": "ok",
                        "summary": "Sitewide visual QA ok，12 routes x 3 viewports 無 overflow 退化",
                    "details": {
                        "policy": "read_only_sitewide_visual_qa_readback_v1",
                        "result_count": 36,
                        "route_count": 12,
                        "viewport_count": 3,
                        "failed_count": 0,
                        "overflow_issue_count": 0,
                        "visual_offender_count": 0,
                        "artifact_path": "data/ai_automation/sitewide_visual_qa_latest.json",
                        "artifact_generated_at": datetime.now().isoformat(timespec="seconds"),
                            "stale": False,
                        },
                    },
                    {
                        "name": "External MCP/RAG integration readback",
                        "status": "ok",
                        "summary": "External MCP/RAG registry 9/9 absorbed; unresolved=0; runtime mcp=True rag=True",
                        "details": {
                            "policy": "read_only_external_mcp_rag_integration_readback_v1",
                            "integration_status": "fully_integrated",
                            "total_capabilities": 9,
                            "absorbed_count": 9,
                            "unresolved_count": 0,
                            "mcp_router_enabled": True,
                            "rag_enabled": True,
                            "gemini_hard_disabled": True,
                            "next_machine_action": "keep_external_mcp_rag_runtime_monitoring",
                        },
                    },
                    {
                        "name": "PixelRAG RAG candidate replay",
                        "status": "ok",
                        "summary": "PixelRAG RAG candidate replay receipts=1, eligible=1, blocked=0, invalid=0, barriers=0",
                        "details": {
                            "policy": "read_only_pixelrag_rag_candidate_replay_v1",
                            "receipt_count": 1,
                            "eligible_count": 1,
                            "blocked_count": 0,
                            "invalid_count": 0,
                            "visual_barrier_count": 0,
                            "blocked_pages_are_not_product_data": True,
                            "next_machine_action": "run_ocr_vlm_replay_then_promotion_gate",
                        },
                    },
                    {
                        "name": "PixelRAG source-contract replay worker",
                        "status": "ok",
                        "summary": "PixelRAG source-contract replay worker candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0",
                        "details": {
                            "policy": "controlled_pixelrag_source_contract_replay_worker_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_pixelrag_source_contract_replay_worker_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG marketplace adapter preflight",
                        "status": "ok",
                        "summary": "PixelRAG marketplace adapter preflight candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0",
                        "details": {
                            "policy": "controlled_pixelrag_marketplace_source_contract_adapter_preflight_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_marketplace_source_contract_adapter_preflight_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG marketplace adapter dry-run",
                        "status": "ok",
                        "summary": "PixelRAG marketplace adapter dry-run candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0, fields=14, outputs=2",
                        "details": {
                            "policy": "controlled_pixelrag_marketplace_source_contract_adapter_dry_run_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "field_contract_count": 14,
                            "dry_run_output_contract_count": 2,
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_marketplace_source_contract_adapter_dry_run_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG marketplace identity matcher replay",
                        "status": "ok",
                        "summary": "PixelRAG marketplace identity matcher replay candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0, identity_candidates=2",
                        "details": {
                            "policy": "controlled_pixelrag_marketplace_identity_matcher_replay_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "identity_candidate_count": 2,
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_marketplace_adapter_identity_matcher_replay_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG marketplace PromotionGate replay",
                        "status": "ok",
                        "summary": "PixelRAG marketplace PromotionGate replay candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0, promotion_candidates=2, embedding_ready=2",
                        "details": {
                            "policy": "controlled_pixelrag_marketplace_promotion_gate_replay_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "promotion_candidate_count": 2,
                            "embedding_signature_guard_ready_count": 2,
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_marketplace_promotion_gate_replay_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG marketplace embedding signature guard replay",
                        "status": "ok",
                        "summary": "PixelRAG marketplace embedding signature guard replay candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0, signature_candidates=2, knowledge_ready=2, signatures=8c8063c66dbe",
                        "details": {
                            "policy": "controlled_pixelrag_marketplace_embedding_signature_guard_replay_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "signature_guard_candidate_count": 2,
                            "candidate_knowledge_ready_count": 2,
                            "expected_embedding_signatures": ["8c8063c66dbe"],
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "embedding_generation_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_marketplace_embedding_signature_guard_replay_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG marketplace candidate knowledge replay",
                        "status": "ok",
                        "summary": "PixelRAG marketplace candidate knowledge replay candidates=1, ready=1, blocked=0, dry_run=1, executed=0, receipts=0, knowledge_candidates=2, internal_rag_ready=2, signatures=8c8063c66dbe",
                        "details": {
                            "policy": "controlled_pixelrag_marketplace_candidate_knowledge_replay_v1",
                            "candidate_count": 1,
                            "ready_count": 1,
                            "blocked_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "receipt_written_count": 0,
                            "capture_runtime_gap_count": 0,
                            "knowledge_candidate_count": 2,
                            "internal_rag_ready_count": 2,
                            "expected_embedding_signatures": ["8c8063c66dbe"],
                            "network_call_performed": False,
                            "model_call_performed": False,
                            "embedding_generation_performed": False,
                            "artifact_write_performed": False,
                            "writes_ai_insights": False,
                            "writes_price_tables": False,
                            "next_machine_action": "run_marketplace_candidate_knowledge_replay_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG OCR/VLM replay contract",
                        "status": "ok",
                        "summary": "PixelRAG OCR/VLM replay contract receipts=1, ready=1, blocked=0, invalid=0, field_contracts=7",
                        "details": {
                            "policy": "read_only_pixelrag_ocr_vlm_replay_contract_v1",
                            "receipt_count": 1,
                            "replay_ready_count": 1,
                            "blocked_count": 0,
                            "invalid_count": 0,
                            "tile_input_count": 4,
                            "field_contract_count": 7,
                            "extraction_execution_performed": False,
                            "blocked_pages_are_not_product_data": True,
                            "next_machine_action": "run_ollama_first_vlm_replay_worker",
                        },
                    },
                    {
                        "name": "PixelRAG VLM route readiness",
                        "status": "ok",
                        "summary": "PixelRAG VLM route readiness hosts=1/5, configured=minicpm-v:latest, configured_available=1, candidate=minicpm-v:latest",
                        "details": {
                            "policy": "read_only_pixelrag_vlm_route_readiness_v1",
                            "host_count": 5,
                            "reachable_host_count": 1,
                            "configured_model": "minicpm-v:latest",
                            "configured_model_available_count": 1,
                            "candidate_model": "minicpm-v:latest",
                            "candidate_host": "http://34.21.145.224:11434",
                            "candidate_provider": "ollama_secondary",
                            "model_route_ready": True,
                            "model_call_performed": False,
                            "next_machine_action": "run_pixelrag_vlm_replay_worker_execute",
                        },
                    },
                    {
                        "name": "PixelRAG VLM replay worker",
                        "status": "ok",
                        "summary": "PixelRAG VLM replay worker receipts=1, ready=1, dry_run=1, skipped=0, executed=0",
                        "details": {
                            "policy": "controlled_pixelrag_ollama_vlm_replay_worker_v1",
                            "receipt_count": 1,
                            "ready_count": 1,
                            "skipped_count": 0,
                            "dry_run_count": 1,
                            "executed_count": 0,
                            "executed_ok_count": 0,
                            "executed_warning_count": 0,
                            "model_error_count": 0,
                            "model_route_not_ready_count": 0,
                            "parse_error_count": 0,
                            "receipt_written_count": 0,
                            "model_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_pixelrag_vlm_replay_worker_execute",
                        },
                    },
                    {
                        "name": "PixelRAG platform probe readiness",
                        "status": "ok",
                        "summary": "PixelRAG platform probe candidates=1, ready=1, shopee_context=1, structured_fallback=1",
                        "details": {
                            "policy": "read_only_pixelrag_platform_probe_readiness_v1",
                            "probe_candidate_count": 1,
                            "ready_for_probe_count": 1,
                            "shopee_public_context_probe_count": 1,
                            "language_or_region_interstitial_count": 1,
                            "traffic_verification_count": 0,
                            "access_denied_count": 0,
                            "structured_source_fallback_count": 1,
                            "next_machine_action": "run_platform_probe_or_structured_source_fallback",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    },
                    {
                        "name": "PixelRAG platform probe worker",
                        "status": "ok",
                        "summary": "PixelRAG platform probe worker candidates=1, ready=1, capture_ready=1, structured_fallback=0, execute=false",
                        "details": {
                            "policy": "controlled_pixelrag_platform_probe_worker_v1",
                            "probe_candidate_count": 1,
                            "ready_count": 1,
                            "dry_run_count": 1,
                            "capture_ready_count": 1,
                            "capture_execute_count": 0,
                            "capture_ok_count": 0,
                            "capture_error_count": 0,
                            "structured_fallback_count": 0,
                            "receipt_written_count": 0,
                            "network_call_performed": False,
                            "artifact_write_performed": False,
                            "next_machine_action": "run_pixelrag_platform_probe_worker_execute",
                            "writes_database_count": 0,
                            "primary_human_gate_count": 0,
                        },
                    }
                ],
            }, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))

    summary = smoke.build_scheduled_automation_health_summary(
        history_limit=5,
        freshness_max_age_hours=9999,
    )

    pchome_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_controlled_apply_drift_monitor"
    )
    assert summary["policy"] == "read_only_ai_automation_scheduled_health_summary"
    assert summary["status"] == "ok"
    assert summary["summary"]["total"] == 43
    assert summary["summary"]["primary_human_gate_count"] == 0
    assert summary["summary"]["writes_database_count"] == 0
    assert pchome_family["status"] == "ok"
    assert pchome_family["details"]["drift_count"] == 0
    auto_policy_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_authorization_guard"
    )
    assert auto_policy_family["status"] == "ok"
    assert auto_policy_family["details"]["lane_guard_pass_count"] == 11
    assert auto_policy_family["details"]["primary_human_gate_count"] == 0
    assert auto_policy_family["details"]["writes_database_count"] == 0
    preflight_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_decision_preflight"
    )
    assert preflight_family["status"] == "ok"
    assert preflight_family["details"]["decision_preflight_pass_count"] == 12
    assert preflight_family["details"]["machine_fetch_evidence_ready_count"] == 1
    assert preflight_family["details"]["payload_source"] == "local_contract_fixture"
    assert preflight_family["details"]["outbound_network"] is False
    assert preflight_family["details"]["business_data_source"] is False
    assert preflight_family["details"]["primary_human_gate_count"] == 0
    assert preflight_family["details"]["writes_database_count"] == 0
    closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_decision_closeout"
    )
    assert closeout_family["status"] == "ok"
    assert closeout_family["details"]["decision_closeout_pass_count"] == 12
    assert closeout_family["details"]["post_apply_verifier_required_count"] == 1
    assert closeout_family["details"]["same_run_truth_required_count"] == 1
    assert closeout_family["details"]["payload_source"] == "local_contract_fixture"
    assert closeout_family["details"]["outbound_network"] is False
    assert closeout_family["details"]["business_data_source"] is False
    assert closeout_family["details"]["primary_human_gate_count"] == 0
    assert closeout_family["details"]["writes_database_count"] == 0
    issuer_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_authorization_issuer_gate"
    )
    assert issuer_family["status"] == "ok"
    assert issuer_family["details"]["issuer_gate_pass_count"] == 12
    assert issuer_family["details"]["required_issuer_evidence_count"] == 9
    assert issuer_family["details"]["nonsecret_authorization_claim_count"] == 8
    assert issuer_family["details"]["payload_source"] == "local_contract_fixture"
    assert issuer_family["details"]["outbound_network"] is False
    assert issuer_family["details"]["business_data_source"] is False
    assert issuer_family["details"]["primary_human_gate_count"] == 0
    assert issuer_family["details"]["writes_database_count"] == 0
    assert issuer_family["details"]["signs_database_apply_authorization_count"] == 0
    assert issuer_family["details"]["signs_database_apply_authorization"] is False
    assert issuer_family["details"]["secret_material_included"] is False
    signing_preflight_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signing_decision_preflight"
    )
    assert signing_preflight_family["status"] == "ok"
    assert signing_preflight_family["details"]["signing_decision_preflight_pass_count"] == 12
    assert signing_preflight_family["details"]["signing_decision_input_requirement_count"] == 10
    assert signing_preflight_family["details"]["signing_decision_rejection_reason_count"] == 11
    assert signing_preflight_family["details"]["payload_source"] == "local_contract_fixture"
    assert signing_preflight_family["details"]["outbound_network"] is False
    assert signing_preflight_family["details"]["business_data_source"] is False
    assert signing_preflight_family["details"]["primary_human_gate_count"] == 0
    assert signing_preflight_family["details"]["writes_database_count"] == 0
    assert signing_preflight_family["details"]["signs_database_apply_authorization_count"] == 0
    assert signing_preflight_family["details"]["signs_database_apply_authorization"] is False
    assert signing_preflight_family["details"]["secret_material_required_in_preview"] is False
    signing_closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signing_decision_closeout"
    )
    assert signing_closeout_family["status"] == "ok"
    assert signing_closeout_family["details"]["signing_decision_closeout_pass_count"] == 12
    assert signing_closeout_family["details"]["signing_decision_input_requirement_count"] == 10
    assert signing_closeout_family["details"]["signing_decision_rejection_reason_count"] == 11
    assert signing_closeout_family["details"]["payload_source"] == "local_contract_fixture"
    assert signing_closeout_family["details"]["outbound_network"] is False
    assert signing_closeout_family["details"]["business_data_source"] is False
    assert signing_closeout_family["details"]["primary_human_gate_count"] == 0
    assert signing_closeout_family["details"]["writes_database_count"] == 0
    assert signing_closeout_family["details"]["signs_database_apply_authorization_count"] == 0
    assert signing_closeout_family["details"]["signs_database_apply_authorization"] is False
    assert signing_closeout_family["details"]["secret_material_included"] is False
    assert signing_closeout_family["details"]["secret_material_required_in_preview"] is False
    signing_issuer_guard_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signing_issuer_guard"
    )
    assert signing_issuer_guard_family["status"] == "ok"
    assert signing_issuer_guard_family["details"]["signing_issuer_guard_pass_count"] == 12
    assert signing_issuer_guard_family["details"]["signing_decision_closeout_check_count"] == 12
    assert signing_issuer_guard_family["details"]["signing_decision_input_requirement_count"] == 10
    assert signing_issuer_guard_family["details"]["signing_decision_rejection_reason_count"] == 11
    assert signing_issuer_guard_family["details"]["payload_source"] == "local_contract_fixture"
    assert signing_issuer_guard_family["details"]["outbound_network"] is False
    assert signing_issuer_guard_family["details"]["business_data_source"] is False
    assert signing_issuer_guard_family["details"]["primary_human_gate_count"] == 0
    assert signing_issuer_guard_family["details"]["writes_database_count"] == 0
    assert signing_issuer_guard_family["details"]["signs_database_apply_authorization_count"] == 0
    assert signing_issuer_guard_family["details"]["signs_database_apply_authorization"] is False
    assert signing_issuer_guard_family["details"]["secret_material_included"] is False
    assert signing_issuer_guard_family["details"]["secret_material_required_in_preview"] is False
    assert signing_issuer_guard_family["details"]["ready_for_future_signable_request_boundary"] is True
    signing_issuer_closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signing_issuer_closeout"
    )
    assert signing_issuer_closeout_family["status"] == "ok"
    assert (
        signing_issuer_closeout_family["details"]["signing_issuer_closeout_pass_count"]
        == 12
    )
    assert (
        signing_issuer_closeout_family["details"]["signing_issuer_guard_check_count"]
        == 12
    )
    assert (
        signing_issuer_closeout_family["details"][
            "signing_decision_input_requirement_count"
        ]
        == 10
    )
    assert (
        signing_issuer_closeout_family["details"][
            "signing_decision_rejection_reason_count"
        ]
        == 11
    )
    assert (
        signing_issuer_closeout_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert signing_issuer_closeout_family["details"]["outbound_network"] is False
    assert signing_issuer_closeout_family["details"]["business_data_source"] is False
    assert signing_issuer_closeout_family["details"]["primary_human_gate_count"] == 0
    assert signing_issuer_closeout_family["details"]["writes_database_count"] == 0
    assert (
        signing_issuer_closeout_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        signing_issuer_closeout_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert signing_issuer_closeout_family["details"]["secret_material_included"] is False
    assert (
        signing_issuer_closeout_family["details"]["secret_material_required_in_preview"]
        is False
    )
    assert (
        signing_issuer_closeout_family["details"][
            "ready_for_future_final_signable_request_package"
        ]
        is True
    )
    signing_execution_preflight_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signing_execution_preflight"
    )
    assert signing_execution_preflight_family["status"] == "ok"
    assert (
        signing_execution_preflight_family["details"][
            "signing_execution_preflight_pass_count"
        ]
        == 12
    )
    assert (
        signing_execution_preflight_family["details"][
            "signing_issuer_closeout_check_count"
        ]
        == 12
    )
    assert (
        signing_execution_preflight_family["details"][
            "final_signable_request_package_ready_count"
        ]
        == 1
    )
    assert (
        signing_execution_preflight_family["details"][
            "operator_held_secret_boundary_count"
        ]
        == 1
    )
    assert (
        signing_execution_preflight_family["details"][
            "signing_execution_input_requirement_count"
        ]
        == 10
    )
    assert (
        signing_execution_preflight_family["details"][
            "signing_execution_abort_condition_count"
        ]
        == 8
    )
    assert signing_execution_preflight_family["details"]["rollback_boundary_count"] == 4
    assert (
        signing_execution_preflight_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert signing_execution_preflight_family["details"]["outbound_network"] is False
    assert signing_execution_preflight_family["details"]["business_data_source"] is False
    assert signing_execution_preflight_family["details"]["primary_human_gate_count"] == 0
    assert signing_execution_preflight_family["details"]["reads_secret_count"] == 0
    assert signing_execution_preflight_family["details"]["writes_database_count"] == 0
    assert (
        signing_execution_preflight_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        signing_execution_preflight_family["details"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert (
        signing_execution_preflight_family["details"][
            "command_preview_redacts_secret_values"
        ]
        is True
    )
    assert (
        signing_execution_preflight_family["details"][
            "command_preview_executes_in_preview"
        ]
        is False
    )
    assert (
        signing_execution_preflight_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        signing_execution_preflight_family["details"]["secret_material_included"]
        is False
    )
    assert (
        signing_execution_preflight_family["details"][
            "ready_for_future_signing_execution_preflight"
        ]
        is True
    )
    signing_execution_closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signing_execution_closeout"
    )
    assert signing_execution_closeout_family["status"] == "ok"
    assert (
        signing_execution_closeout_family["details"][
            "signing_execution_closeout_pass_count"
        ]
        == 12
    )
    assert (
        signing_execution_closeout_family["details"][
            "signing_execution_preflight_check_count"
        ]
        == 12
    )
    assert (
        signing_execution_closeout_family["details"][
            "unsigned_signed_authorization_receipt_boundary_count"
        ]
        == 1
    )
    assert (
        signing_execution_closeout_family["details"][
            "operator_held_secret_boundary_count"
        ]
        == 1
    )
    assert (
        signing_execution_closeout_family["details"][
            "signing_execution_input_requirement_count"
        ]
        == 10
    )
    assert (
        signing_execution_closeout_family["details"][
            "signing_execution_abort_condition_count"
        ]
        == 8
    )
    assert signing_execution_closeout_family["details"]["rollback_boundary_count"] == 4
    assert (
        signing_execution_closeout_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert signing_execution_closeout_family["details"]["outbound_network"] is False
    assert signing_execution_closeout_family["details"]["business_data_source"] is False
    assert signing_execution_closeout_family["details"]["primary_human_gate_count"] == 0
    assert signing_execution_closeout_family["details"]["reads_secret_count"] == 0
    assert signing_execution_closeout_family["details"]["writes_database_count"] == 0
    assert (
        signing_execution_closeout_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        signing_execution_closeout_family["details"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert (
        signing_execution_closeout_family["details"][
            "command_preview_redacts_secret_values"
        ]
        is True
    )
    assert (
        signing_execution_closeout_family["details"][
            "command_preview_executes_in_preview"
        ]
        is False
    )
    assert (
        signing_execution_closeout_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signing_execution_closeout_family["details"]["signature_material_included"]
        is False
    )
    assert (
        signing_execution_closeout_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        signing_execution_closeout_family["details"]["secret_material_included"]
        is False
    )
    assert (
        signing_execution_closeout_family["details"][
            "ready_for_future_signing_execution_closeout"
        ]
        is True
    )
    assert (
        signing_execution_closeout_family["details"][
            "ready_for_future_unsigned_signed_authorization_receipt_boundary"
        ]
        is True
    )
    signed_receipt_preflight_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signed_receipt_preflight"
    )
    assert signed_receipt_preflight_family["status"] == "ok"
    assert (
        signed_receipt_preflight_family["details"][
            "signed_receipt_preflight_pass_count"
        ]
        == 12
    )
    assert (
        signed_receipt_preflight_family["details"][
            "signing_execution_closeout_check_count"
        ]
        == 12
    )
    assert (
        signed_receipt_preflight_family["details"][
            "unsigned_signed_authorization_receipt_boundary_count"
        ]
        == 1
    )
    assert (
        signed_receipt_preflight_family["details"][
            "external_signing_receipt_evidence_boundary_count"
        ]
        == 1
    )
    assert (
        signed_receipt_preflight_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        signed_receipt_preflight_family["details"][
            "external_receipt_acceptance_gate_count"
        ]
        == 8
    )
    assert (
        signed_receipt_preflight_family["details"][
            "operator_held_secret_boundary_count"
        ]
        == 1
    )
    assert (
        signed_receipt_preflight_family["details"][
            "signing_execution_input_requirement_count"
        ]
        == 10
    )
    assert (
        signed_receipt_preflight_family["details"][
            "signing_execution_abort_condition_count"
        ]
        == 8
    )
    assert signed_receipt_preflight_family["details"]["rollback_boundary_count"] == 4
    assert (
        signed_receipt_preflight_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert signed_receipt_preflight_family["details"]["outbound_network"] is False
    assert signed_receipt_preflight_family["details"]["business_data_source"] is False
    assert signed_receipt_preflight_family["details"]["primary_human_gate_count"] == 0
    assert signed_receipt_preflight_family["details"]["reads_secret_count"] == 0
    assert signed_receipt_preflight_family["details"]["writes_database_count"] == 0
    assert (
        signed_receipt_preflight_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        signed_receipt_preflight_family["details"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert (
        signed_receipt_preflight_family["details"][
            "external_signed_authorization_receipt_required_in_future"
        ]
        is True
    )
    assert (
        signed_receipt_preflight_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signed_receipt_preflight_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signed_receipt_preflight_family["details"]["signature_material_included"]
        is False
    )
    assert (
        signed_receipt_preflight_family["details"]["signer_key_id_reference_only"]
        is True
    )
    assert (
        signed_receipt_preflight_family["details"][
            "signature_algorithm_reference_only"
        ]
        is True
    )
    assert (
        signed_receipt_preflight_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        signed_receipt_preflight_family["details"]["secret_material_included"]
        is False
    )
    assert (
        signed_receipt_preflight_family["details"][
            "ready_for_future_signed_authorization_receipt_preflight"
        ]
        is True
    )
    assert (
        signed_receipt_preflight_family["details"][
            "ready_for_future_external_signing_receipt_evidence_boundary"
        ]
        is True
    )
    signed_receipt_closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signed_receipt_closeout"
    )
    assert signed_receipt_closeout_family["status"] == "ok"
    assert (
        signed_receipt_closeout_family["details"][
            "signed_receipt_closeout_pass_count"
        ]
        == 12
    )
    assert (
        signed_receipt_closeout_family["details"][
            "signed_receipt_preflight_check_count"
        ]
        == 12
    )
    assert (
        signed_receipt_closeout_family["details"][
            "external_signing_receipt_evidence_boundary_count"
        ]
        == 1
    )
    assert (
        signed_receipt_closeout_family["details"][
            "detached_receipt_verification_boundary_count"
        ]
        == 1
    )
    assert (
        signed_receipt_closeout_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        signed_receipt_closeout_family["details"][
            "external_receipt_acceptance_gate_count"
        ]
        == 8
    )
    assert (
        signed_receipt_closeout_family["details"][
            "detached_receipt_verification_check_count"
        ]
        == 10
    )
    assert (
        signed_receipt_closeout_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert signed_receipt_closeout_family["details"]["outbound_network"] is False
    assert signed_receipt_closeout_family["details"]["business_data_source"] is False
    assert signed_receipt_closeout_family["details"]["primary_human_gate_count"] == 0
    assert signed_receipt_closeout_family["details"]["reads_secret_count"] == 0
    assert signed_receipt_closeout_family["details"]["writes_database_count"] == 0
    assert (
        signed_receipt_closeout_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        signed_receipt_closeout_family["details"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert (
        signed_receipt_closeout_family["details"][
            "requires_detached_signature_verification"
        ]
        is True
    )
    assert (
        signed_receipt_closeout_family["details"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        signed_receipt_closeout_family["details"][
            "external_signed_authorization_receipt_required_in_future"
        ]
        is True
    )
    assert (
        signed_receipt_closeout_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signed_receipt_closeout_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signed_receipt_closeout_family["details"]["signature_material_included"]
        is False
    )
    assert (
        signed_receipt_closeout_family["details"]["signer_key_id_reference_only"]
        is True
    )
    assert (
        signed_receipt_closeout_family["details"][
            "signature_algorithm_reference_only"
        ]
        is True
    )
    assert (
        signed_receipt_closeout_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        signed_receipt_closeout_family["details"]["secret_material_included"]
        is False
    )
    assert (
        signed_receipt_closeout_family["details"][
            "ready_for_future_signed_authorization_receipt_closeout"
        ]
        is True
    )
    assert (
        signed_receipt_closeout_family["details"][
            "ready_for_future_detached_receipt_verification_boundary"
        ]
        is True
    )
    assert (
        signed_receipt_closeout_family["details"][
            "permits_future_detached_receipt_verification_boundary"
        ]
        is True
    )
    signed_receipt_intake_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_signed_receipt_evidence_intake"
    )
    assert signed_receipt_intake_family["status"] == "ok"
    assert (
        signed_receipt_intake_family["details"][
            "signed_receipt_evidence_intake_pass_count"
        ]
        == 12
    )
    assert (
        signed_receipt_intake_family["details"][
            "signed_receipt_closeout_check_count"
        ]
        == 12
    )
    assert (
        signed_receipt_intake_family["details"][
            "detached_verification_evidence_schema_count"
        ]
        == 1
    )
    assert (
        signed_receipt_intake_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        signed_receipt_intake_family["details"][
            "external_receipt_acceptance_gate_count"
        ]
        == 8
    )
    assert (
        signed_receipt_intake_family["details"][
            "detached_receipt_verification_check_count"
        ]
        == 10
    )
    assert (
        signed_receipt_intake_family["details"][
            "detached_verification_evidence_field_count"
        ]
        == 12
    )
    assert (
        signed_receipt_intake_family["details"][
            "detached_verification_acceptance_gate_count"
        ]
        == 10
    )
    assert (
        signed_receipt_intake_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert signed_receipt_intake_family["details"]["outbound_network"] is False
    assert signed_receipt_intake_family["details"]["business_data_source"] is False
    assert signed_receipt_intake_family["details"]["primary_human_gate_count"] == 0
    assert signed_receipt_intake_family["details"]["reads_secret_count"] == 0
    assert signed_receipt_intake_family["details"]["writes_database_count"] == 0
    assert (
        signed_receipt_intake_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        signed_receipt_intake_family["details"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert (
        signed_receipt_intake_family["details"][
            "requires_detached_signature_verification"
        ]
        is True
    )
    assert (
        signed_receipt_intake_family["details"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        signed_receipt_intake_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signed_receipt_intake_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        signed_receipt_intake_family["details"]["signature_material_included"]
        is False
    )
    assert (
        signed_receipt_intake_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        signed_receipt_intake_family["details"]["secret_material_included"]
        is False
    )
    assert signed_receipt_intake_family["details"]["accepts_plaintext_secret"] is False
    assert (
        signed_receipt_intake_family["details"][
            "ready_for_future_signed_authorization_receipt_evidence_intake"
        ]
        is True
    )
    assert (
        signed_receipt_intake_family["details"][
            "ready_for_future_detached_verification_evidence_schema"
        ]
        is True
    )
    assert (
        signed_receipt_intake_family["details"][
            "permits_future_detached_verification_evidence_validation"
        ]
        is True
    )
    assert (
        signed_receipt_intake_family["details"][
            "performs_detached_signature_verification"
        ]
        is False
    )
    detached_validation_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_detached_verification_evidence_validation"
    )
    assert detached_validation_family["status"] == "ok"
    assert (
        detached_validation_family["details"][
            "detached_verification_evidence_validation_pass_count"
        ]
        == 12
    )
    assert (
        detached_validation_family["details"][
            "signed_receipt_evidence_intake_check_count"
        ]
        == 12
    )
    assert (
        detached_validation_family["details"][
            "detached_verification_evidence_schema_count"
        ]
        == 1
    )
    assert (
        detached_validation_family["details"][
            "verifier_receipt_closeout_boundary_count"
        ]
        == 1
    )
    assert (
        detached_validation_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        detached_validation_family["details"][
            "external_receipt_acceptance_gate_count"
        ]
        == 8
    )
    assert (
        detached_validation_family["details"][
            "detached_receipt_verification_check_count"
        ]
        == 10
    )
    assert (
        detached_validation_family["details"][
            "detached_verification_evidence_field_count"
        ]
        == 12
    )
    assert (
        detached_validation_family["details"][
            "detached_verification_acceptance_gate_count"
        ]
        == 10
    )
    assert detached_validation_family["details"]["verifier_receipt_field_count"] == 12
    assert (
        detached_validation_family["details"][
            "verifier_receipt_acceptance_gate_count"
        ]
        == 10
    )
    assert (
        detached_validation_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert detached_validation_family["details"]["outbound_network"] is False
    assert detached_validation_family["details"]["business_data_source"] is False
    assert detached_validation_family["details"]["primary_human_gate_count"] == 0
    assert detached_validation_family["details"]["reads_secret_count"] == 0
    assert detached_validation_family["details"]["writes_database_count"] == 0
    assert (
        detached_validation_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        detached_validation_family["details"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert (
        detached_validation_family["details"][
            "requires_detached_signature_verification"
        ]
        is True
    )
    assert (
        detached_validation_family["details"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert detached_validation_family["details"]["verifier_receipt_persisted"] is False
    assert (
        detached_validation_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        detached_validation_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        detached_validation_family["details"]["signature_material_included"]
        is False
    )
    assert (
        detached_validation_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert detached_validation_family["details"]["secret_material_included"] is False
    assert detached_validation_family["details"]["accepts_plaintext_secret"] is False
    assert (
        detached_validation_family["details"][
            "ready_for_future_detached_verification_evidence_validation"
        ]
        is True
    )
    assert (
        detached_validation_family["details"][
            "can_enter_future_verifier_receipt_closeout"
        ]
        is True
    )
    assert (
        detached_validation_family["details"][
            "verifier_receipt_closeout_boundary_ready"
        ]
        is True
    )
    assert (
        detached_validation_family["details"][
            "ready_for_future_verifier_receipt_closeout_boundary"
        ]
        is True
    )
    assert (
        detached_validation_family["details"][
            "permits_future_verifier_receipt_closeout"
        ]
        is True
    )
    assert detached_validation_family["details"]["persists_verifier_receipt"] is False
    assert (
        detached_validation_family["details"][
            "performs_detached_signature_verification"
        ]
        is False
    )
    verifier_receipt_closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_verifier_receipt_closeout"
    )
    assert verifier_receipt_closeout_family["status"] == "ok"
    assert (
        verifier_receipt_closeout_family["details"][
            "verifier_receipt_closeout_pass_count"
        ]
        == 12
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "detached_verification_evidence_validation_check_count"
        ]
        == 12
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "verifier_receipt_evidence_handoff_count"
        ]
        == 1
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "verifier_receipt_evidence_handoff_field_count"
        ]
        == 12
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "verifier_receipt_handoff_acceptance_gate_count"
        ]
        == 10
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "external_receipt_acceptance_gate_count"
        ]
        == 8
    )
    assert (
        verifier_receipt_closeout_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert verifier_receipt_closeout_family["details"]["outbound_network"] is False
    assert verifier_receipt_closeout_family["details"]["business_data_source"] is False
    assert (
        verifier_receipt_closeout_family["details"]["primary_human_gate_count"]
        == 0
    )
    assert verifier_receipt_closeout_family["details"]["reads_secret_count"] == 0
    assert verifier_receipt_closeout_family["details"]["writes_database_count"] == 0
    assert (
        verifier_receipt_closeout_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "requires_detached_signature_verification"
        ]
        is True
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"]["verifier_receipt_persisted"]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"]["signature_material_included"]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"]["secret_material_included"]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"]["accepts_plaintext_secret"]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "ready_for_future_verifier_receipt_closeout"
        ]
        is True
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "can_enter_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "verifier_receipt_evidence_handoff_ready"
        ]
        is True
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "ready_for_future_verifier_receipt_evidence_handoff"
        ]
        is True
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "permits_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert (
        verifier_receipt_closeout_family["details"]["persists_verifier_receipt"]
        is False
    )
    assert (
        verifier_receipt_closeout_family["details"][
            "performs_detached_signature_verification"
        ]
        is False
    )
    authorization_evidence_preflight_family = next(
        item for item in summary["families"]
        if (
            item["key"]
            == "pchome_auto_policy_authorization_evidence_execution_preflight"
        )
    )
    assert authorization_evidence_preflight_family["status"] == "ok"
    assert (
        authorization_evidence_preflight_family["details"][
            "authorization_evidence_execution_preflight_pass_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "authorization_verifier_receipt_closeout_ready_count"
        ]
        == 1
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "verifier_receipt_closeout_check_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "verifier_receipt_evidence_handoff_count"
        ]
        == 1
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "authorization_evidence_execution_field_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "authorization_evidence_execution_acceptance_gate_count"
        ]
        == 10
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "verifier_receipt_evidence_handoff_field_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "verifier_receipt_handoff_acceptance_gate_count"
        ]
        == 10
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "external_receipt_acceptance_gate_count"
        ]
        == 8
    )
    assert (
        authorization_evidence_preflight_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert (
        authorization_evidence_preflight_family["details"]["outbound_network"]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"]["business_data_source"]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "primary_human_gate_count"
        ]
        == 0
    )
    assert (
        authorization_evidence_preflight_family["details"]["reads_secret_count"]
        == 0
    )
    assert (
        authorization_evidence_preflight_family["details"]["writes_database_count"]
        == 0
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "ready_for_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "can_enter_future_authorization_evidence_execution_closeout"
        ]
        is True
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "authorization_evidence_execution_preflight_ready"
        ]
        is True
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "permits_future_authorization_evidence_execution_closeout"
        ]
        is True
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "verifier_receipt_persisted"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "signature_material_included"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"]["secret_material_included"]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"]["accepts_plaintext_secret"]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        authorization_evidence_preflight_family["details"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    authorization_evidence_closeout_family = next(
        item for item in summary["families"]
        if (
            item["key"]
            == "pchome_auto_policy_authorization_evidence_execution_closeout"
        )
    )
    assert authorization_evidence_closeout_family["status"] == "ok"
    assert (
        authorization_evidence_closeout_family["details"][
            "authorization_evidence_execution_closeout_pass_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "authorization_evidence_execution_preflight_ready_count"
        ]
        == 1
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "database_apply_authorization_final_verifier_gate_ready_count"
        ]
        == 1
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "authorization_evidence_execution_closeout_field_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "authorization_evidence_execution_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "verifier_receipt_evidence_handoff_field_count"
        ]
        == 12
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "required_external_receipt_evidence_count"
        ]
        == 10
    )
    assert (
        authorization_evidence_closeout_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert (
        authorization_evidence_closeout_family["details"]["outbound_network"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["business_data_source"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["primary_human_gate_count"]
        == 0
    )
    assert (
        authorization_evidence_closeout_family["details"]["reads_secret_count"]
        == 0
    )
    assert (
        authorization_evidence_closeout_family["details"]["writes_database_count"]
        == 0
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "ready_for_future_database_apply_authorization_final_verifier_gate"
        ]
        is True
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "can_enter_future_database_apply_controlled_apply_final_preflight"
        ]
        is True
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "permits_future_database_apply_authorization_final_verifier_gate"
        ]
        is True
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "permits_future_database_apply_controlled_apply_final_preflight"
        ]
        is True
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["verifier_receipt_persisted"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["signature_material_included"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["secret_material_included"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["accepts_plaintext_secret"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["executes_database_apply"]
        is False
    )
    assert (
        authorization_evidence_closeout_family["details"]["database_apply_authorized"]
        is False
    )
    controlled_final_preflight_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_controlled_apply_final_preflight"
    )
    assert controlled_final_preflight_family["status"] == "ok"
    assert controlled_final_preflight_family["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_package_lane"
    )
    assert controlled_final_preflight_family["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_package_lane"
    )
    assert (
        controlled_final_preflight_family["details"][
            "controlled_apply_final_preflight_pass_count"
        ]
        == 12
    )
    assert (
        controlled_final_preflight_family["details"][
            "authorization_evidence_execution_closeout_ready_count"
        ]
        == 1
    )
    assert (
        controlled_final_preflight_family["details"][
            "database_apply_authorization_final_verifier_gate_ready_count"
        ]
        == 1
    )
    assert controlled_final_preflight_family["details"]["rollback_binding_count"] == 1
    assert (
        controlled_final_preflight_family["details"]["rollback_binding_field_count"]
        == 8
    )
    assert (
        controlled_final_preflight_family["details"]["post_apply_verifier_binding_count"]
        == 1
    )
    assert (
        controlled_final_preflight_family["details"][
            "post_apply_verifier_binding_field_count"
        ]
        == 8
    )
    assert (
        controlled_final_preflight_family["details"]["payload_source"]
        == "local_contract_fixture"
    )
    assert controlled_final_preflight_family["details"]["outbound_network"] is False
    assert controlled_final_preflight_family["details"]["business_data_source"] is False
    assert (
        controlled_final_preflight_family["details"]["primary_human_gate_count"]
        == 0
    )
    assert controlled_final_preflight_family["details"]["reads_secret_count"] == 0
    assert controlled_final_preflight_family["details"]["writes_database_count"] == 0
    assert (
        controlled_final_preflight_family["details"][
            "signs_database_apply_authorization_count"
        ]
        == 0
    )
    assert (
        controlled_final_preflight_family["details"][
            "ready_for_future_database_apply_controlled_apply_final_preflight"
        ]
        is True
    )
    assert (
        controlled_final_preflight_family["details"][
            "can_enter_future_database_apply_controlled_dry_run_package"
        ]
        is True
    )
    assert (
        controlled_final_preflight_family["details"][
            "controlled_apply_final_preflight_ready"
        ]
        is True
    )
    assert controlled_final_preflight_family["details"]["rollback_binding_ready"] is True
    assert (
        controlled_final_preflight_family["details"]["post_apply_verifier_binding_ready"]
        is True
    )
    assert controlled_final_preflight_family["details"]["rollback_bound"] is True
    assert controlled_final_preflight_family["details"]["post_apply_verifier_bound"] is True
    assert controlled_final_preflight_family["details"]["dry_run_only"] is True
    assert controlled_final_preflight_family["details"]["check_mode_only"] is True
    assert (
        controlled_final_preflight_family["details"]["rollback_execution_authorized"]
        is False
    )
    assert controlled_final_preflight_family["details"]["rollback_executes_sql"] is False
    assert controlled_final_preflight_family["details"]["rollback_writes_database"] is False
    assert (
        controlled_final_preflight_family["details"][
            "post_apply_verifier_execution_authorized_in_preview"
        ]
        is False
    )
    assert (
        controlled_final_preflight_family["details"][
            "permits_future_database_apply_controlled_dry_run_package"
        ]
        is True
    )
    assert (
        controlled_final_preflight_family["details"]["executes_database_apply"]
        is False
    )
    assert (
        controlled_final_preflight_family["details"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        controlled_final_preflight_family["details"]["database_apply_authorized"]
        is False
    )
    controlled_dry_run_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_controlled_dry_run_package"
    )
    assert controlled_dry_run_family["status"] == "ok"
    assert controlled_dry_run_family["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_receipt_closeout_lane"
    )
    assert controlled_dry_run_family["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_receipt_closeout_lane"
    )
    assert controlled_dry_run_family["details"]["controlled_dry_run_package_pass_count"] == 12
    assert controlled_dry_run_family["details"]["controlled_dry_run_package_check_count"] == 12
    assert controlled_dry_run_family["details"]["controlled_dry_run_package_field_count"] == 12
    assert controlled_dry_run_family["details"]["controlled_dry_run_acceptance_gate_count"] == 10
    assert controlled_dry_run_family["details"]["dry_run_execution_receipt_preview_count"] == 1
    assert controlled_dry_run_family["details"]["dry_run_execution_receipt_field_count"] == 8
    assert controlled_dry_run_family["details"]["dry_run_result_parser_count"] == 1
    assert controlled_dry_run_family["details"]["dry_run_result_parser_field_count"] == 10
    assert controlled_dry_run_family["details"]["rollback_binding_count"] == 1
    assert controlled_dry_run_family["details"]["post_apply_verifier_binding_count"] == 1
    assert controlled_dry_run_family["details"]["payload_source"] == "local_contract_fixture"
    assert controlled_dry_run_family["details"]["outbound_network"] is False
    assert controlled_dry_run_family["details"]["business_data_source"] is False
    assert controlled_dry_run_family["details"]["primary_human_gate_count"] == 0
    assert controlled_dry_run_family["details"]["reads_secret_count"] == 0
    assert controlled_dry_run_family["details"]["writes_database_count"] == 0
    assert controlled_dry_run_family["details"]["signs_database_apply_authorization_count"] == 0
    assert (
        controlled_dry_run_family["details"][
            "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is True
    )
    assert (
        controlled_dry_run_family["details"][
            "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is True
    )
    assert controlled_dry_run_family["details"]["controlled_dry_run_package_ready"] is True
    assert controlled_dry_run_family["details"]["dry_run_execution_performed"] is False
    assert controlled_dry_run_family["details"]["target_migration_hash_locked"] is True
    assert controlled_dry_run_family["details"]["dry_run_only"] is True
    assert controlled_dry_run_family["details"]["check_mode_only"] is True
    assert controlled_dry_run_family["details"]["command_shape_execution_allowed"] is False
    assert controlled_dry_run_family["details"]["command_shape_shell_command_included"] is False
    assert controlled_dry_run_family["details"]["command_shape_sql_included"] is False
    assert controlled_dry_run_family["details"]["receipt_dry_run_status"] == "preview_only_not_executed"
    assert controlled_dry_run_family["details"]["receipt_execution_performed"] is False
    assert controlled_dry_run_family["details"]["receipt_stdout_included"] is False
    assert controlled_dry_run_family["details"]["receipt_stderr_included"] is False
    assert controlled_dry_run_family["details"]["receipt_database_apply_authorized"] is False
    assert controlled_dry_run_family["details"]["parser_execution_required"] is False
    assert controlled_dry_run_family["details"]["parser_verification_status"] == "schema_preview_ready"
    assert (
        controlled_dry_run_family["details"][
            "permits_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is True
    )
    assert controlled_dry_run_family["details"]["accepts_plaintext_secret"] is False
    assert controlled_dry_run_family["details"]["reads_secret_in_preview"] is False
    assert controlled_dry_run_family["details"]["executes_authorization_evidence"] is False
    assert controlled_dry_run_family["details"]["executes_database_apply"] is False
    assert controlled_dry_run_family["details"]["executes_endpoint"] is False
    assert controlled_dry_run_family["details"]["executes_sql"] is False
    assert controlled_dry_run_family["details"]["ready_for_database_apply_now"] is False
    assert controlled_dry_run_family["details"]["database_apply_authorized"] is False
    controlled_dry_run_closeout_family = next(
        item for item in summary["families"]
        if item["key"] == "pchome_auto_policy_controlled_dry_run_receipt_closeout"
    )
    assert controlled_dry_run_closeout_family["status"] == "ok"
    assert controlled_dry_run_closeout_family["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_runner_readiness_lane"
    )
    assert controlled_dry_run_closeout_family["details"]["next_machine_action"] == (
        "continue_to_pchome_auto_policy_controlled_dry_run_runner_readiness_lane"
    )
    assert (
        controlled_dry_run_closeout_family["details"][
            "controlled_dry_run_receipt_closeout_pass_count"
        ]
        == 12
    )
    assert (
        controlled_dry_run_closeout_family["details"][
            "controlled_dry_run_receipt_closeout_check_count"
        ]
        == 12
    )
    assert (
        controlled_dry_run_closeout_family["details"][
            "controlled_dry_run_receipt_closeout_field_count"
        ]
        == 12
    )
    assert (
        controlled_dry_run_closeout_family["details"][
            "controlled_dry_run_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert controlled_dry_run_closeout_family["details"]["receipt_validation_report_count"] == 1
    assert controlled_dry_run_closeout_family["details"]["receipt_validation_field_count"] == 8
    assert controlled_dry_run_closeout_family["details"]["payload_source"] == "local_contract_fixture"
    assert controlled_dry_run_closeout_family["details"]["outbound_network"] is False
    assert controlled_dry_run_closeout_family["details"]["business_data_source"] is False
    assert controlled_dry_run_closeout_family["details"]["primary_human_gate_count"] == 0
    assert controlled_dry_run_closeout_family["details"]["reads_secret_count"] == 0
    assert controlled_dry_run_closeout_family["details"]["writes_database_count"] == 0
    assert (
        controlled_dry_run_closeout_family["details"][
            "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is True
    )
    assert (
        controlled_dry_run_closeout_family["details"][
            "receipt_validation_status"
        ]
        == "preview_validated_not_executed"
    )
    assert controlled_dry_run_closeout_family["details"]["validation_execution_performed"] is False
    assert controlled_dry_run_closeout_family["details"]["validation_stdout_included"] is False
    assert controlled_dry_run_closeout_family["details"]["validation_stderr_included"] is False
    assert controlled_dry_run_closeout_family["details"]["validation_database_apply_authorized"] is False
    assert controlled_dry_run_closeout_family["details"]["executes_database_apply"] is False
    assert controlled_dry_run_closeout_family["details"]["ready_for_database_apply_now"] is False
    assert controlled_dry_run_closeout_family["details"]["database_apply_authorized"] is False
    surface_family = next(
        item for item in summary["families"]
        if item["key"] == "ai_surface_html_readback"
    )
    assert surface_family["status"] == "ok"
    assert surface_family["details"]["checked_surface_count"] == 10
    sitewide_family = next(
        item for item in summary["families"]
        if item["key"] == "sitewide_ui_ux_agent"
    )
    assert sitewide_family["status"] == "ok"
    assert sitewide_family["details"]["issue_surface_count"] == 0
    assert sitewide_family["details"]["repair_package_status"] == "no_op"
    visual_family = next(
        item for item in summary["families"]
        if item["key"] == "sitewide_visual_qa"
    )
    assert visual_family["status"] == "ok"
    assert visual_family["details"]["route_count"] == 12
    assert visual_family["details"]["failed_count"] == 0
    external_mcp_rag_family = next(
        item for item in summary["families"]
        if item["key"] == "external_mcp_rag_integration"
    )
    assert external_mcp_rag_family["status"] == "ok"
    assert external_mcp_rag_family["details"]["unresolved_count"] == 0
    pixelrag_rag_replay_family = next(
        item for item in summary["families"]
        if item["key"] == "pixelrag_rag_candidate_replay"
    )
    assert pixelrag_rag_replay_family["status"] == "ok"
    assert pixelrag_rag_replay_family["details"]["eligible_count"] == 1
    pixelrag_ocr_vlm_replay_family = next(
        item for item in summary["families"]
        if item["key"] == "pixelrag_ocr_vlm_replay"
    )
    assert pixelrag_ocr_vlm_replay_family["status"] == "ok"
    assert pixelrag_ocr_vlm_replay_family["details"]["replay_ready_count"] == 1
    assert pixelrag_ocr_vlm_replay_family["details"]["extraction_execution_performed"] is False
    pixelrag_vlm_route_readiness_family = next(
        item for item in summary["families"]
        if item["key"] == "pixelrag_vlm_route_readiness"
    )
    assert pixelrag_vlm_route_readiness_family["status"] == "ok"
    assert pixelrag_vlm_route_readiness_family["details"]["model_route_ready"] is True
    assert pixelrag_vlm_route_readiness_family["details"]["model_call_performed"] is False
    assert pixelrag_vlm_route_readiness_family["details"]["writes_database_count"] == 0
    pixelrag_vlm_replay_worker_family = next(
        item for item in summary["families"]
        if item["key"] == "pixelrag_vlm_replay_worker"
    )
    assert pixelrag_vlm_replay_worker_family["status"] == "ok"
    assert pixelrag_vlm_replay_worker_family["details"]["ready_count"] == 1
    assert pixelrag_vlm_replay_worker_family["details"]["dry_run_count"] == 1
    assert pixelrag_vlm_replay_worker_family["details"]["model_call_performed"] is False
    assert pixelrag_vlm_replay_worker_family["details"]["writes_database_count"] == 0
    pixelrag_platform_probe_family = next(
        item for item in summary["families"]
        if item["key"] == "pixelrag_platform_probe"
    )
    assert pixelrag_platform_probe_family["status"] == "ok"
    assert pixelrag_platform_probe_family["details"]["ready_for_probe_count"] == 1
    assert pixelrag_platform_probe_family["details"]["primary_human_gate_count"] == 0
    pixelrag_platform_probe_worker_family = next(
        item for item in summary["families"]
        if item["key"] == "pixelrag_platform_probe_worker"
    )
    assert pixelrag_platform_probe_worker_family["status"] == "ok"
    assert pixelrag_platform_probe_worker_family["details"]["ready_count"] == 1
    assert pixelrag_platform_probe_worker_family["details"]["dry_run_count"] == 1
    assert pixelrag_platform_probe_worker_family["details"]["network_call_performed"] is False
    assert pixelrag_platform_probe_worker_family["details"]["writes_database_count"] == 0
    assert summary["scheduled_outputs"]["telegram_send_in_preview"] is False
    assert summary["scheduled_outputs"]["writes_database"] is False
    assert summary["automation_policy"]["primary_flow"] == "ai_controlled"
    assert summary["safety"]["writes_database"] is False


def test_scheduled_automation_health_summary_can_use_current_smoke_without_recording_history(tmp_path, monkeypatch):
    from services import ai_automation_smoke_service as smoke

    history_path = tmp_path / "smoke_history.jsonl"
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))
    current_smoke = {
        "generated_at": "2026-07-02T12:00:00",
        "status": "critical",
        "summary": {"ok": 29, "warning": 0, "critical": 1, "total": 30},
        "checks": [
            {
                "name": "PChome 受控落地 drift monitor",
                "status": "critical",
                "summary": "PChome controlled apply 偵測到 1 筆 drift",
                "details": {"drift_count": 1, "selector_count": 4, "readback_pass_count": 3},
            },
            _auto_policy_guard_history_check(),
            _auto_policy_decision_preflight_history_check(),
            _auto_policy_decision_closeout_history_check(),
            _auto_policy_authorization_issuer_gate_history_check(),
            _auto_policy_signing_decision_preflight_history_check(),
            _auto_policy_signing_decision_closeout_history_check(),
            _auto_policy_signing_issuer_guard_history_check(),
            _auto_policy_signing_issuer_closeout_history_check(),
            _auto_policy_signing_execution_preflight_history_check(),
            _auto_policy_signing_execution_closeout_history_check(),
            _auto_policy_signed_receipt_preflight_history_check(),
            _auto_policy_signed_receipt_closeout_history_check(),
            _auto_policy_signed_receipt_evidence_intake_history_check(),
            _auto_policy_detached_verification_evidence_validation_history_check(),
            _auto_policy_verifier_receipt_closeout_history_check(),
            _auto_policy_authorization_evidence_execution_preflight_history_check(),
            _auto_policy_authorization_evidence_execution_closeout_history_check(),
            _auto_policy_controlled_apply_final_preflight_history_check(),
            _auto_policy_controlled_dry_run_package_history_check(),
            _auto_policy_controlled_dry_run_receipt_closeout_history_check(),
            {
                "name": "AI surface HTML readback",
                "status": "ok",
                "summary": "AI surface HTML readback 通過 10/10，無產品面 raw wording",
                "details": {"checked_surface_count": 10, "pass_count": 10, "failed_count": 0},
            },
            {
                "name": "Sitewide UI/UX Agent readback",
                "status": "ok",
                "summary": "Sitewide UI/UX Agent ok/no-op，整站專業化 surface 無退化",
                "details": {
                    "template_count": 55,
                    "compact_guardrail_count": 29,
                    "issue_surface_count": 0,
                    "repair_package_status": "no_op",
                    "repair_action_count": 0,
                },
            },
            {
                "name": "Sitewide visual QA readback",
                "status": "ok",
                "summary": "Sitewide visual QA ok，12 routes x 3 viewports 無 overflow 退化",
                "details": {
                    "route_count": 12,
                    "viewport_count": 3,
                    "failed_count": 0,
                    "overflow_issue_count": 0,
                    "visual_offender_count": 0,
                    "stale": False,
                },
            }
        ],
    }

    summary = smoke.build_scheduled_automation_health_summary(
        current_smoke=current_smoke,
        freshness_max_age_hours=9999,
    )

    assert summary["status"] == "critical"
    assert "run_pchome_drift_verifier_and_recovery_package" in summary["next_machine_actions"]
    assert summary["safety"]["include_current_smoke"] is True
    assert not history_path.exists()


def test_scheduled_automation_health_summary_falls_back_to_visual_qa_artifact(tmp_path, monkeypatch):
    from datetime import datetime
    from services import ai_automation_smoke_service as smoke
    from services import ai_surface_html_readback_service as surface_service

    history_path = tmp_path / "smoke_history.jsonl"
    history_path.write_text(
        json.dumps({
            "generated_at": datetime.now().isoformat(timespec="seconds"),
            "status": "ok",
            "summary": {"ok": 27, "warning": 0, "critical": 0, "total": 27},
            "checks": [],
        }, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_guard_check",
        lambda: _auto_policy_guard_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_decision_preflight_check",
        lambda: _auto_policy_decision_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_decision_closeout_check",
        lambda: _auto_policy_decision_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_issuer_gate_check",
        lambda: _auto_policy_authorization_issuer_gate_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_decision_preflight_check",
        lambda: _auto_policy_signing_decision_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_decision_closeout_check",
        lambda: _auto_policy_signing_decision_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_issuer_guard_check",
        lambda: _auto_policy_signing_issuer_guard_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_issuer_closeout_check",
        lambda: _auto_policy_signing_issuer_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_execution_preflight_check",
        lambda: _auto_policy_signing_execution_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_execution_closeout_check",
        lambda: _auto_policy_signing_execution_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signed_receipt_preflight_check",
        lambda: _auto_policy_signed_receipt_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signed_receipt_closeout_check",
        lambda: _auto_policy_signed_receipt_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signed_receipt_evidence_intake_check",
        lambda: _auto_policy_signed_receipt_evidence_intake_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_detached_verification_evidence_validation_check",
        lambda: _auto_policy_detached_verification_evidence_validation_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_verifier_receipt_closeout_check",
        lambda: _auto_policy_verifier_receipt_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_evidence_execution_preflight_check",
        lambda: _auto_policy_authorization_evidence_execution_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_evidence_execution_closeout_check",
        lambda: _auto_policy_authorization_evidence_execution_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_controlled_apply_final_preflight_check",
        lambda: _auto_policy_controlled_apply_final_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_controlled_dry_run_package_check",
        lambda: _auto_policy_controlled_dry_run_package_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_controlled_dry_run_receipt_closeout_check",
        lambda: _auto_policy_controlled_dry_run_receipt_closeout_history_check(),
    )
    monkeypatch.setattr(
        surface_service,
        "build_sitewide_visual_qa_readback",
        lambda **_kwargs: {
            "policy": "read_only_sitewide_visual_qa_readback_v1",
            "status": "ok",
            "artifact_path": "data/ai_automation/sitewide_visual_qa_latest.json",
            "artifact_exists": True,
            "artifact_generated_at": "2026-07-03T07:40:00",
            "next_machine_action": "keep_sitewide_visual_qa_monitoring",
            "summary": {
                "result_count": 147,
                "route_count": 49,
                "viewport_count": 3,
                "pass_count": 147,
                "failed_count": 0,
                "overflow_issue_count": 0,
                "visual_offender_count": 0,
                "stale": False,
            },
        },
    )

    summary = smoke.build_scheduled_automation_health_summary(
        history_limit=5,
        freshness_max_age_hours=9999,
    )

    visual_family = next(
        item for item in summary["families"]
        if item["key"] == "sitewide_visual_qa"
    )
    assert visual_family["status"] == "ok"
    assert visual_family["details"]["route_count"] == 49
    assert visual_family["details"]["failed_count"] == 0


def test_scheduled_automation_health_summary_route_returns_compact_payload(tmp_path, monkeypatch):
    from datetime import datetime
    from flask import Flask
    from routes import system_public_routes as routes
    from services import ai_automation_smoke_service as smoke

    history_path = tmp_path / "smoke_history.jsonl"
    history_path.write_text(
        json.dumps({
            "generated_at": datetime.now().isoformat(timespec="seconds"),
            "status": "ok",
            "summary": {"ok": 30, "warning": 0, "critical": 0, "total": 30},
            "checks": [],
        }, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_guard_check",
        lambda: _auto_policy_guard_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_decision_preflight_check",
        lambda: _auto_policy_decision_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_decision_closeout_check",
        lambda: _auto_policy_decision_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_issuer_gate_check",
        lambda: _auto_policy_authorization_issuer_gate_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_decision_preflight_check",
        lambda: _auto_policy_signing_decision_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_decision_closeout_check",
        lambda: _auto_policy_signing_decision_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_issuer_guard_check",
        lambda: _auto_policy_signing_issuer_guard_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_issuer_closeout_check",
        lambda: _auto_policy_signing_issuer_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_execution_preflight_check",
        lambda: _auto_policy_signing_execution_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signing_execution_closeout_check",
        lambda: _auto_policy_signing_execution_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signed_receipt_preflight_check",
        lambda: _auto_policy_signed_receipt_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signed_receipt_closeout_check",
        lambda: _auto_policy_signed_receipt_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_signed_receipt_evidence_intake_check",
        lambda: _auto_policy_signed_receipt_evidence_intake_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_detached_verification_evidence_validation_check",
        lambda: _auto_policy_detached_verification_evidence_validation_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_verifier_receipt_closeout_check",
        lambda: _auto_policy_verifier_receipt_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_evidence_execution_preflight_check",
        lambda: _auto_policy_authorization_evidence_execution_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_authorization_evidence_execution_closeout_check",
        lambda: _auto_policy_authorization_evidence_execution_closeout_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_controlled_apply_final_preflight_check",
        lambda: _auto_policy_controlled_apply_final_preflight_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_controlled_dry_run_package_check",
        lambda: _auto_policy_controlled_dry_run_package_history_check(),
    )
    monkeypatch.setattr(
        smoke,
        "_pchome_auto_policy_controlled_dry_run_receipt_closeout_check",
        lambda: _auto_policy_controlled_dry_run_receipt_closeout_history_check(),
    )

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai-automation/scheduled-health-summary?history_limit=5&freshness_max_age_hours=9999"
    ):
        response = routes.ai_automation_scheduled_health_summary_api.__wrapped__()

    payload = response.get_json()
    assert payload["policy"] == "read_only_ai_automation_scheduled_health_summary"
    assert payload["scheduled_outputs"]["health_summary_endpoint"] == (
        "/api/ai-automation/scheduled-health-summary"
    )
    assert payload["safety"]["writes_database"] is False


def test_surface_html_readback_service_reports_compact_contracts():
    from services.ai_surface_html_readback_service import build_ai_surface_html_readback

    payload = build_ai_surface_html_readback()

    assert payload["policy"] == "read_only_ai_surface_html_readback_v1"
    assert payload["status"] == "ok"
    assert payload["summary"]["checked_surface_count"] == 10
    assert payload["summary"]["pass_count"] == 10
    assert payload["summary"]["forbidden_leak_count"] == 0
    assert payload["summary"]["primary_human_gate_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["writes_database"] is False


def test_surface_html_readback_service_detects_regression():
    from services.ai_surface_html_readback_service import build_ai_surface_html_readback

    payload = build_ai_surface_html_readback(
        rendered_html_by_route={
            "/observability/overview": "<section>PPT_VISION_ENABLED=false</section>"
        }
    )

    assert payload["status"] == "critical"
    assert payload["summary"]["failed_count"] == 1
    failed = payload["failed_surfaces"][0]
    assert failed["route"] == "/observability/overview"
    assert "compact-observability-workbench" in failed["missing_markers"]
    assert "PPT_VISION_ENABLED=" in failed["forbidden_leaks"]


def test_surface_html_repair_package_builds_controlled_actions():
    from services.ai_surface_html_readback_service import (
        build_ai_surface_html_readback,
        build_ai_surface_html_repair_package,
    )

    readback = build_ai_surface_html_readback(
        rendered_html_by_route={
            "/observability/overview": "<section>PPT_VISION_ENABLED=false</section>"
        }
    )
    package = build_ai_surface_html_repair_package(source_readback=readback)

    assert package["policy"] == "read_only_ai_surface_html_repair_package_v1"
    assert package["status"] == "repair_ready"
    assert package["summary"]["controlled_action_count"] == 2
    assert package["summary"]["primary_human_gate_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert package["summary"]["executes_shell_count"] == 0
    assert package["next_machine_action"] == "apply_ai_surface_html_contract_repair"
    assert package["safety"]["read_only_package"] is True
    actions = package["repair_items"][0]["controlled_actions"]
    assert {item["action"] for item in actions} == {
        "restore_density_guardrail_marker",
        "remove_raw_engineering_copy_from_product_surface",
    }


def test_sitewide_ui_ux_agent_inventory_scans_real_pages():
    from services.ai_surface_html_readback_service import build_sitewide_ui_ux_agent_inventory

    inventory = build_sitewide_ui_ux_agent_inventory()

    assert inventory["policy"] == "read_only_sitewide_ui_ux_agent_inventory_v1"
    assert inventory["summary"]["template_count"] >= 50
    assert inventory["summary"]["high_priority_template_count"] >= 20
    assert inventory["summary"]["compact_guardrail_count"] >= 29
    assert inventory["summary"]["issue_surface_count"] == 0
    assert inventory["summary"]["primary_human_gate_count"] == 0
    assert inventory["summary"]["writes_database_count"] == 0
    assert inventory["safety"]["writes_database"] is False
    templates = {item["template"] for item in inventory["surfaces"]}
    issue_templates = {item["template"] for item in inventory["issue_surfaces"]}
    assert "templates/base.html" not in templates
    assert not any("/components/" in item for item in templates)
    assert not any("/." in item or item.startswith("templates/.") for item in templates)
    assert "templates/ai_history.html" not in issue_templates
    assert "templates/ai_recommend.html" not in issue_templates
    assert "templates/admin/ppt_audit_preview.html" not in issue_templates
    assert "templates/cicd_dashboard.html" not in issue_templates
    assert "templates/daily_sales.html" not in issue_templates
    assert "templates/dashboard.html" not in issue_templates
    assert "templates/edm_dashboard.html" not in issue_templates
    assert "templates/growth_analysis.html" not in issue_templates
    assert "templates/pchome_crawler.html" not in issue_templates
    assert "templates/price_comparison.html" not in issue_templates
    assert "templates/sales_analysis.html" not in issue_templates
    assert "templates/vendor_stockout_history_v2.html" not in issue_templates
    assert "templates/vendor_stockout_import_v2.html" not in issue_templates
    assert "templates/vendor_stockout_index_v2.html" not in issue_templates
    assert "templates/vendor_stockout_list_v2.html" not in issue_templates
    assert "templates/vendor_stockout_send_email_v2.html" not in issue_templates
    assert "templates/vendor_stockout_vendor_management_v2.html" not in issue_templates


def test_sitewide_ui_ux_repair_package_prioritizes_controlled_template_repairs():
    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()
    package = build_sitewide_ui_ux_repair_package(source_inventory=inventory, limit=3)

    assert package["policy"] == "read_only_sitewide_ui_ux_repair_package_v1"
    assert package["summary"]["selected_surface_count"] <= 3
    assert package["summary"]["primary_human_gate_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert package["summary"]["executes_shell_count"] == 0
    assert package["safety"]["read_only_package"] is True
    assert "templates/**/*.html" in package["controlled_apply_contract"]["allowed_target_globs"]
    if package["repair_items"]:
        assert package["next_machine_action"] == "apply_sitewide_ui_ux_controlled_repairs"
        assert package["repair_items"][0]["controlled_actions"]


def test_sitewide_ui_ux_agent_reports_non_utf8_templates(tmp_path):
    from services.ai_surface_html_readback_service import (
        build_sitewide_ui_ux_agent_inventory,
        build_sitewide_ui_ux_repair_package,
    )

    template_dir = tmp_path / "templates"
    template_dir.mkdir()
    routes_dir = tmp_path / "routes"
    routes_dir.mkdir()
    (template_dir / "legacy_dashboard.html").write_bytes(b"\xa3 legacy dashboard")
    (template_dir / "._legacy_dashboard.html").write_bytes(b"\xa3 apple metadata")
    (routes_dir / "legacy_routes.py").write_bytes(b"\xa3 legacy route source")

    inventory = build_sitewide_ui_ux_agent_inventory(root=tmp_path)
    issue = inventory["issue_surfaces"][0]
    package = build_sitewide_ui_ux_repair_package(source_inventory=inventory)

    assert inventory["status"] == "warning"
    assert inventory["summary"]["template_count"] == 1
    assert issue["status"] == "critical"
    assert issue["findings"][0]["type"] == "template_encoding_error"
    assert package["repair_items"][0]["controlled_actions"][0]["action"] == (
        "normalize_template_encoding_utf8"
    )
    assert package["safety"]["writes_database"] is False


def test_sitewide_visual_qa_readback_consumes_artifact_payload():
    from datetime import datetime
    from services.ai_surface_html_readback_service import build_sitewide_visual_qa_readback

    payload = build_sitewide_visual_qa_readback(
        artifact_payload={
            "generated_at": datetime.now().isoformat(timespec="seconds"),
            "results": [
                {"route": "/ai_intelligence", "viewport": "desktop-1440", "passed": True},
                {"route": "/ai_intelligence", "viewport": "mobile-390", "passed": True},
                {"route": "/observability/overview", "viewport": "mobile-390", "passed": True},
            ],
        }
    )

    assert payload["policy"] == "read_only_sitewide_visual_qa_readback_v1"
    assert payload["status"] == "ok"
    assert payload["summary"]["result_count"] == 3
    assert payload["summary"]["route_count"] == 2
    assert payload["summary"]["viewport_count"] == 2
    assert payload["summary"]["failed_count"] == 0
    assert payload["summary"]["primary_human_gate_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["requires_browser_for_readback"] is False
    assert payload["safety"]["requires_browser_for_artifact_generation"] is True


def test_sitewide_visual_qa_readback_reports_visual_failures():
    from datetime import datetime
    from services.ai_surface_html_readback_service import build_sitewide_visual_qa_readback

    payload = build_sitewide_visual_qa_readback(
        artifact_payload={
            "generated_at": datetime.now().isoformat(timespec="seconds"),
            "results": [
                {
                    "route": "/price_comparison",
                    "viewport": "mobile-390",
                    "passed": False,
                    "error": "body horizontal overflow 24px",
                }
            ],
        }
    )

    assert payload["status"] == "critical"
    assert payload["summary"]["failed_count"] == 1
    assert payload["summary"]["overflow_issue_count"] == 1
    assert payload["next_machine_action"] == "run_sitewide_visual_qa_and_publish_artifact"
    assert payload["failed_results"][0]["route"] == "/price_comparison"


def test_surface_html_readback_check_is_part_of_ai_smoke(monkeypatch):
    from services import ai_automation_smoke_service as smoke

    monkeypatch.setattr(smoke, "_event_router_check", lambda: smoke._check("event", "ok", "ok"))
    monkeypatch.setattr(smoke, "_gemini_egress_check", lambda: smoke._check("gemini", "ok", "ok"))
    monkeypatch.setattr(smoke, "_autoheal_check", lambda: smoke._check("autoheal", "ok", "ok"))
    monkeypatch.setattr(smoke, "_nemotron_check", lambda: smoke._check("nemotron", "ok", "ok"))
    monkeypatch.setattr(smoke, "_embedding_queue_check", lambda: smoke._check("embedding", "ok", "ok"))
    monkeypatch.setattr(smoke, "_elephant_hitl_check", lambda: smoke._check("elephant", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_controlled_apply_drift_monitor_check", lambda: smoke._check("pchome", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_guard_check", lambda: smoke._check("auto-policy", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_decision_preflight_check", lambda: smoke._check("auto-policy preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_decision_closeout_check", lambda: smoke._check("auto-policy closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_issuer_gate_check", lambda: smoke._check("auto-policy issuer", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_decision_preflight_check", lambda: smoke._check("auto-policy signing preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_decision_closeout_check", lambda: smoke._check("auto-policy signing closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_issuer_guard_check", lambda: smoke._check("auto-policy signing issuer guard", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_issuer_closeout_check", lambda: smoke._check("auto-policy signing issuer closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_execution_preflight_check", lambda: smoke._check("auto-policy signing execution preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signing_execution_closeout_check", lambda: smoke._check("auto-policy signing execution closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_preflight_check", lambda: smoke._check("auto-policy signed receipt preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_closeout_check", lambda: smoke._check("auto-policy signed receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_signed_receipt_evidence_intake_check", lambda: smoke._check("auto-policy signed receipt evidence intake", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_detached_verification_evidence_validation_check", lambda: smoke._check("auto-policy detached verification evidence validation", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_verifier_receipt_closeout_check", lambda: smoke._check("auto-policy verifier receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_evidence_execution_preflight_check", lambda: smoke._check("auto-policy authorization evidence execution preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_authorization_evidence_execution_closeout_check", lambda: smoke._check("auto-policy authorization evidence execution closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_apply_final_preflight_check", lambda: smoke._check("auto-policy controlled apply final preflight", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_package_check", lambda: smoke._check("auto-policy controlled dry-run package", "ok", "ok"))
    monkeypatch.setattr(smoke, "_pchome_auto_policy_controlled_dry_run_receipt_closeout_check", lambda: smoke._check("auto-policy controlled dry-run receipt closeout", "ok", "ok"))
    monkeypatch.setattr(smoke, "_sitewide_visual_qa_check", lambda: smoke._check(
        "Sitewide visual QA readback",
        "ok",
        "visual ok",
        {"route_count": 12, "viewport_count": 3, "failed_count": 0},
    ))
    monkeypatch.setattr(smoke, "_security_governance_review_check", lambda: smoke._check(
        "Security governance automation review",
        "ok",
        "security governance ok",
    ))
    monkeypatch.setattr(smoke, "_external_mcp_rag_integration_check", lambda: smoke._check(
        "External MCP/RAG integration readback",
        "ok",
        "external mcp rag ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_rag_candidate_replay_check", lambda: smoke._check(
        "PixelRAG RAG candidate replay",
        "ok",
        "pixelrag replay ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_source_contract_replay_worker_check", lambda: smoke._check(
        "PixelRAG source-contract replay worker",
        "ok",
        "pixelrag source contract ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_adapter_preflight_check", lambda: smoke._check(
        "PixelRAG marketplace adapter preflight",
        "ok",
        "pixelrag marketplace adapter preflight ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_adapter_dry_run_check", lambda: smoke._check(
        "PixelRAG marketplace adapter dry-run",
        "ok",
        "pixelrag marketplace adapter dry-run ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_identity_matcher_replay_check", lambda: smoke._check(
        "PixelRAG marketplace identity matcher replay",
        "ok",
        "pixelrag marketplace identity matcher replay ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_promotion_gate_replay_check", lambda: smoke._check(
        "PixelRAG marketplace PromotionGate replay",
        "ok",
        "pixelrag marketplace PromotionGate replay ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_embedding_signature_guard_replay_check", lambda: smoke._check(
        "PixelRAG marketplace embedding signature guard replay",
        "ok",
        "pixelrag marketplace embedding signature guard replay ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_marketplace_candidate_knowledge_replay_check", lambda: smoke._check(
        "PixelRAG marketplace candidate knowledge replay",
        "ok",
        "pixelrag marketplace candidate knowledge replay ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_ocr_vlm_replay_check", lambda: smoke._check(
        "PixelRAG OCR/VLM replay contract",
        "ok",
        "pixelrag ocr vlm ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_vlm_route_readiness_check", lambda: smoke._check(
        "PixelRAG VLM route readiness",
        "ok",
        "pixelrag vlm route ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_vlm_replay_worker_check", lambda: smoke._check(
        "PixelRAG VLM replay worker",
        "ok",
        "pixelrag vlm worker ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_platform_probe_check", lambda: smoke._check(
        "PixelRAG platform probe readiness",
        "ok",
        "pixelrag platform probe ok",
    ))
    monkeypatch.setattr(smoke, "_pixelrag_platform_probe_worker_check", lambda: smoke._check(
        "PixelRAG platform probe worker",
        "ok",
        "pixelrag platform probe worker ok",
    ))

    result = smoke.collect_ai_automation_smoke(record_history=False)

    surface_check = next(
        item for item in result["checks"]
        if item["name"] == "AI surface HTML readback"
    )
    sitewide_check = next(
        item for item in result["checks"]
        if item["name"] == "Sitewide UI/UX Agent readback"
    )
    visual_check = next(
        item for item in result["checks"]
        if item["name"] == "Sitewide visual QA readback"
    )
    assert result["summary"]["total"] == 46
    assert surface_check["status"] == "ok"
    assert surface_check["details"]["checked_surface_count"] == 10
    assert sitewide_check["status"] == "ok"
    assert sitewide_check["details"]["issue_surface_count"] == 0
    assert sitewide_check["details"]["repair_package_status"] == "no_op"
    assert visual_check["status"] == "ok"
    assert visual_check["details"]["route_count"] == 12


def test_surface_html_readback_route_returns_payload(monkeypatch):
    from flask import Flask
    from routes import system_public_routes as routes

    app = Flask(__name__)
    with app.test_request_context("/api/ai-automation/surface-html-readback"):
        response = routes.ai_automation_surface_html_readback_api.__wrapped__()

    payload = response.get_json()
    assert payload["policy"] == "read_only_ai_surface_html_readback_v1"
    assert payload["summary"]["checked_surface_count"] == 10
    assert payload["safety"]["writes_database"] is False


def test_surface_and_sitewide_ui_ux_agent_routes_return_payloads():
    from flask import Flask
    from routes import system_public_routes as routes

    app = Flask(__name__)
    route_cases = [
        (
            "/api/ai-automation/surface-html-repair-package",
            routes.ai_automation_surface_html_repair_package_api.__wrapped__,
            "read_only_ai_surface_html_repair_package_v1",
        ),
        (
            "/api/ai-automation/sitewide-ui-ux-agent",
            routes.ai_automation_sitewide_ui_ux_agent_api.__wrapped__,
            "read_only_sitewide_ui_ux_agent_inventory_v1",
        ),
        (
            "/api/ai-automation/sitewide-ui-ux-repair-package?limit=3",
            routes.ai_automation_sitewide_ui_ux_repair_package_api.__wrapped__,
            "read_only_sitewide_ui_ux_repair_package_v1",
        ),
        (
            "/api/ai-automation/sitewide-visual-qa-readback?max_age_hours=9999",
            routes.ai_automation_sitewide_visual_qa_readback_api.__wrapped__,
            "read_only_sitewide_visual_qa_readback_v1",
        ),
    ]

    for path, view_func, policy in route_cases:
        with app.test_request_context(path):
            response = view_func()
        payload = response.get_json()
        assert payload["policy"] == policy
        assert payload["safety"].get("writes_database") is False


def test_gemini_egress_check_ok_when_no_calls(monkeypatch):
    from services import ai_automation_smoke_service as smoke

    class FakeResult:
        def fetchone(self):
            return {"calls": 0, "tokens": 0, "cost_usd": 0, "last_called": None}

        def fetchall(self):
            return []

    class FakeSession:
        closed = False

        def execute(self, *_args, **_kwargs):
            return FakeResult()

        def close(self):
            self.closed = True

    fake_session = FakeSession()
    monkeypatch.setattr(smoke, "get_session", lambda: fake_session)
    monkeypatch.delenv("GEMINI_API_HARD_DISABLED", raising=False)

    result = smoke._gemini_egress_check()

    assert result["status"] == "ok"
    assert result["details"]["calls"] == 0
    assert result["details"]["hard_disabled"] is True
    assert fake_session.closed is True


def test_gemini_egress_check_critical_when_hard_disabled_has_calls(monkeypatch):
    from services import ai_automation_smoke_service as smoke

    class FakeSummaryResult:
        def fetchone(self):
            return {
                "calls": 2,
                "tokens": 1234,
                "cost_usd": 0.012345,
                "last_called": "2026-05-21 07:00:00+00",
            }

    class FakeTopResult:
        def fetchall(self):
            return [{
                "caller": "code_review_openclaw_gemini",
                "model": "gemini-2.5-flash",
                "calls": 2,
                "tokens": 1234,
                "cost_usd": 0.012345,
                "last_called": "2026-05-21 07:00:00+00",
            }]

    class FakeSession:
        def __init__(self):
            self.calls = 0

        def execute(self, *_args, **_kwargs):
            self.calls += 1
            return FakeSummaryResult() if self.calls == 1 else FakeTopResult()

        def close(self):
            pass

    monkeypatch.setattr(smoke, "get_session", lambda: FakeSession())
    monkeypatch.delenv("GEMINI_API_HARD_DISABLED", raising=False)

    result = smoke._gemini_egress_check()

    assert result["status"] == "critical"
    assert "Hard-disabled" in result["summary"]
    assert result["details"]["calls"] == 2
    assert result["details"]["top_callers"][0]["caller"] == "code_review_openclaw_gemini"


def test_nemotron_smoke_detects_current_dispatcher_fallback(monkeypatch):
    from services import ai_automation_smoke_service as smoke
    import services.nemoton_dispatcher_service as nemotron

    monkeypatch.delattr(nemotron, "NemotronDispatcherService", raising=False)
    monkeypatch.setattr(nemotron, "NIM_API_KEY", "")

    result = smoke._nemotron_check()

    assert result["status"] == "warning"
    assert result["details"]["fallback_ready"] is True
    assert result["details"]["dispatcher_class"] == "NemotronDispatcher"


def test_build_smoke_daily_summary_message_escapes_history(tmp_path, monkeypatch):
    from services import ai_automation_smoke_service as smoke

    history_path = tmp_path / "smoke_history.jsonl"
    history_path.write_text(
        '{"generated_at":"2026-04-29T01:00:00","status":"warning",'
        '"summary":{"ok":0,"warning":1,"critical":0,"total":1},'
        '"checks":[{"name":"<script>","status":"warning","summary":"bad"}]}\n',
        encoding="utf-8",
    )
    monkeypatch.setattr(smoke, "_HISTORY_PATH", str(history_path))

    message = smoke.build_smoke_daily_summary_message()

    assert "AI 自動化 Smoke 每日摘要" in message
    assert "WARNING" in message
    assert "最近異常檢查" in message
    assert "<script>" not in message


def test_send_smoke_daily_summary_uses_telegram_result(monkeypatch):
    from services import ai_automation_smoke_service as smoke

    monkeypatch.setattr(smoke, "build_smoke_daily_summary_message", lambda: "hello")
    monkeypatch.setattr(
        "services.telegram_templates.send_telegram_with_result",
        lambda message, chat_ids=None: {
            "ok": True,
            "sent": 1,
            "failed": 0,
            "chat_ids": chat_ids or [123],
            "errors": [],
        },
    )

    result = smoke.send_smoke_daily_summary(chat_ids=[999])

    assert result["status"] == "sent"
    assert result["telegram"]["chat_ids"] == [999]
