import hashlib
import json
from pathlib import Path

from scripts.ops import report_pchome_mapping_backlog as report
from services.pchome_mapping_backlog_service import (
    build_pchome_auto_policy_apply_readiness_closeout,
    build_pchome_auto_policy_db_apply_controlled_apply_final_preflight,
    build_pchome_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_package,
    build_pchome_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_runner_readiness,
    build_pchome_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout,
    build_pchome_auto_policy_db_apply_authorization_decision_closeout,
    build_pchome_auto_policy_db_apply_authorization_decision_preflight,
    build_pchome_auto_policy_db_apply_authorization_evidence_execution_closeout,
    build_pchome_auto_policy_db_apply_authorization_evidence_execution_preflight,
    build_pchome_auto_policy_db_apply_authorization_issuer_gate,
    build_pchome_auto_policy_db_apply_authorization_lane_guard,
    build_pchome_auto_policy_db_apply_authorization_request_closeout,
    build_pchome_auto_policy_db_apply_authorization_request_intake,
    build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout,
    build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight,
    build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout,
    build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight,
    build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout,
    build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard,
    build_pchome_auto_policy_db_apply_authorization_detached_verification_evidence_validation,
    build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout,
    build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake,
    build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight,
    build_pchome_auto_policy_db_apply_authorization_verifier_receipt_closeout,
    build_pchome_auto_policy_db_apply_authorization_package,
    build_pchome_auto_policy_db_apply_controlled_dry_run_shell_closeout,
    build_pchome_auto_policy_db_apply_controlled_dry_run_shell_preview,
    build_pchome_auto_policy_db_apply_execution_preflight,
    build_pchome_auto_policy_db_apply_final_handoff_package,
    build_pchome_auto_policy_db_apply_request_gate_preview,
    build_pchome_auto_policy_db_apply_verifier_artifact_preview,
    build_pchome_auto_policy_migration_apply_gate_preview,
    build_pchome_auto_policy_migration_file_generation_request,
    build_pchome_auto_policy_migration_file_preview,
    build_pchome_auto_policy_persistence_gate,
    build_pchome_auto_policy_receipt_gate,
    build_pchome_auto_policy_schema_migration_preview,
    build_pchome_evidence_enrichment_preview,
    build_pchome_evidence_fetch_gate,
    build_pchome_evidence_merge_preview,
    build_pchome_evidence_source_preview,
    build_pchome_direct_mapping_auto_search_package,
    build_pchome_direct_mapping_candidate_decision_package,
    build_pchome_direct_mapping_candidate_exception_auto_resolution_package,
    build_pchome_direct_mapping_candidate_exception_resolution_closeout_package,
    build_pchome_direct_mapping_retry_candidate_decision_package,
    build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_artifact_retention_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_compact_readback_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_recovery_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_executor_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_preflight_package,
    build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package,
    build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_package,
    build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_package,
    build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_package,
    build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_input_package,
    build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package,
    build_pchome_growth_ai_automation_readiness,
    build_pchome_growth_ai_automation_surface_summary,
    build_pchome_mapping_operator_preview,
    parse_pchome_product_page_evidence_html,
    parse_unit_package_basis,
    summarize_pchome_mapping_backlog,
)


ROOT = Path(__file__).resolve().parents[1]


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


def test_with_limit_preserves_existing_query_and_clamps_limit():
    url = report.with_limit("https://example.test/path?refresh=1", 99)

    assert url == "https://example.test/path?refresh=1&limit=50"


def test_summarize_payload_turns_growth_api_into_mapping_backlog():
    summary = report.summarize_payload(_payload())

    assert summary["policy"] == "read_only_pchome_growth_mapping_backlog"
    assert summary["result"] == "NEEDS_MAPPING"
    assert summary["stats"]["mapping_rate"] == 25.0
    assert summary["stats"]["needs_mapping_count"] == 3
    assert summary["backlog"]["direct_mapping_count"] == 2
    assert summary["backlog"]["review_candidate_count"] == 1
    assert summary["backlog"]["mapped_opportunity_count"] == 1
    assert summary["backlog"]["top_needs_mapping"][0]["pchome_product_id"] == "PCH-2"
    assert summary["backlog"]["top_needs_mapping"][0]["product_url"] == "https://24h.pchome.com.tw/prod/PCH-2"
    direct_evidence = summary["backlog"]["top_needs_mapping"][0]["evidence_completeness"]
    assert "stable_product_id" in direct_evidence["present_fields"]
    assert "unit_price_or_package_basis" in direct_evidence["present_fields"]
    assert direct_evidence["unit_package_basis"]["package_basis"] == "multi_pack_quantity_candidate"
    assert direct_evidence["unit_package_basis"]["estimated_total_quantity"] == 80
    assert "image" in direct_evidence["missing_fields"]
    assert "availability" in direct_evidence["missing_fields"]
    assert direct_evidence["auto_accept_ready"] is False
    assert direct_evidence["human_review_required"] is False
    assert direct_evidence["legacy_human_review_required"] is True
    assert direct_evidence["ai_exception_required"] is True
    assert direct_evidence["primary_human_gate_count"] == 0
    assert summary["backlog"]["top_review_candidates"][0]["review_candidate"]["momo_sku"] == "5868343"


def test_shared_service_is_the_single_mapping_backlog_summary_source():
    assert report.summarize_payload(_payload()) == summarize_pchome_mapping_backlog(_payload())


def test_operator_preview_is_read_only_and_requires_write_gate():
    preview = build_pchome_mapping_operator_preview(_payload(), batch_size=1)

    assert preview["policy"] == "read_only_pchome_growth_mapping_operator_preview"
    assert preview["result"] == "READY_FOR_OPERATOR_PREVIEW"
    assert preview["operator_batch"]["selected_direct_mapping_count"] == 1
    assert preview["operator_batch"]["direct_mapping_targets"][0]["pchome_product_id"] == "PCH-2"
    assert preview["operator_batch"]["direct_mapping_targets"][0]["evidence_completeness"]["auto_accept_ready"] is False
    assert preview["command_preview"]["endpoint"] == "/api/ai/pchome-growth/backfill-momo-candidates"
    assert preview["command_preview"]["writes_database"] is True
    assert preview["command_preview"]["write_gate_required"] is True
    assert preview["external_benchmark_alignment"]["references"][0]["source"] == "Google Merchant Center product data specification"
    assert any(
        item["field"] == "image" and item["status"] == "missing_in_current_growth_payload"
        for item in preview["external_benchmark_alignment"]["required_evidence_fields"]
    )
    assert preview["ai_automation_plan"]["policy"] == "ollama_first_read_only_ai_assist"
    assert preview["ai_automation_plan"]["llm_calls_in_preview"] is False
    assert preview["ai_automation_plan"]["gemini_allowed"] is False
    assert preview["ai_automation_plan"]["automation_readiness"]["can_execute_write"] is False
    assert preview["safety"]["read_only_preview"] is True
    assert preview["safety"]["writes_database"] is False
    assert preview["safety"]["executes_search"] is False


def test_direct_mapping_auto_search_package_builds_p1_no_write_search_terms():
    package = build_pchome_direct_mapping_auto_search_package(_payload(), batch_size=1)

    target = package["search_package"]["targets"][0]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_auto_search_package"
    assert package["result"] == "DIRECT_MAPPING_SEARCH_PACKAGE_READY"
    assert package["source_policy"] == "read_only_pchome_growth_mapping_operator_preview"
    assert package["summary"]["direct_mapping_count"] == 2
    assert package["summary"]["selected_direct_mapping_count"] == 1
    assert package["summary"]["search_ready_target_count"] == 1
    assert package["summary"]["planned_search_term_count"] >= 1
    assert package["summary"]["execute_search_count"] == 0
    assert package["summary"]["candidates_found_count"] == 0
    assert target["pchome_product_id"] == "PCH-2"
    assert target["can_execute_read_only_search"] is True
    assert "40ml" in " ".join(target["search_terms"]).lower()
    assert target["identity_anchors"]["stable_product_id"] is True
    assert target["identity_anchors"]["unit_basis_present"] is True
    assert "no_database_write_from_search_package" in target["candidate_acceptance_gates"]
    assert package["search_execution"]["executed"] is False
    assert package["search_execution"]["writes_database"] is False
    assert package["candidate_acceptance_policy"]["routes_manual_review_to_machine_verifiable_decision"] is True
    assert package["safety"]["executes_search"] is False
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["syncs_external_offers"] is False


def test_direct_mapping_auto_search_package_executes_fake_search_without_db_write():
    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        assert targets[0]["product_id"] == "PCH-2"
        assert max_products == 1
        assert limit_per_product == 3
        assert max_terms_per_product == 2
        assert min_score == 0.5
        return True, "found", [
            {
                "product_id": "MOMO-1",
                "name": "Direct mapping product 40ml x2",
                "price": 999,
                "target_pchome_product_id": "PCH-2",
                "target_match_score": 0.92,
                "auto_compare_type": "total_price",
                "target_hard_veto": False,
            }
        ]

    package = build_pchome_direct_mapping_auto_search_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        limit_per_product=3,
        max_terms_per_product=2,
        min_score=0.5,
        search_func=fake_search,
    )

    target = package["search_package"]["targets"][0]
    assert package["result"] == "DIRECT_MAPPING_CANDIDATES_FOUND"
    assert package["summary"]["execute_search_count"] == 1
    assert package["summary"]["candidates_found_count"] == 1
    assert package["summary"]["auto_compare_candidate_count"] == 1
    assert package["summary"]["review_candidate_count"] == 0
    assert target["candidate_count"] == 1
    assert target["candidate_ids"] == ["MOMO-1"]
    assert package["search_execution"]["executed"] is True
    assert package["search_execution"]["search_success"] is True
    assert package["search_execution"]["candidate_count"] == 1
    assert package["search_execution"]["writes_database"] is False
    assert package["search_execution"]["syncs_external_offers"] is False
    assert package["candidate_preview"][0]["target_pchome_product_id"] == "PCH-2"
    assert package["safety"]["executes_search"] is True
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["persists_candidate"] is False


def test_direct_mapping_auto_search_package_does_not_count_hard_veto_as_auto_candidate():
    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Unit candidate with hard veto",
                "price": 999,
                "target_pchome_product_id": "PCH-2",
                "target_match_score": 0.92,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_auto_search_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        search_func=fake_search,
    )

    assert package["summary"]["candidates_found_count"] == 1
    assert package["summary"]["auto_compare_candidate_count"] == 0
    assert package["summary"]["review_candidate_count"] == 1
    assert package["candidate_preview"][0]["auto_compare_type"] == "unit_price"
    assert package["candidate_preview"][0]["target_hard_veto"] is True
    assert package["safety"]["writes_database"] is False


def test_direct_mapping_candidate_decision_package_waits_for_search_candidates_without_db_write():
    package = build_pchome_direct_mapping_candidate_decision_package(_payload(), batch_size=1)

    assert package["policy"] == "read_only_pchome_growth_direct_mapping_candidate_decision_package"
    assert package["result"] == "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"
    assert package["source_policy"] == "read_only_pchome_growth_direct_mapping_auto_search_package"
    assert package["summary"]["direct_mapping_count"] == 2
    assert package["summary"]["selected_direct_mapping_count"] == 1
    assert package["summary"]["candidate_decision_count"] == 0
    assert package["summary"]["auto_compare_decision_count"] == 0
    assert package["summary"]["machine_review_decision_count"] == 0
    assert package["summary"]["can_auto_persist_now_count"] == 0
    assert package["decision_package"]["candidate_decisions"] == []
    assert package["decision_package"]["manual_review_mode"] == "exception_only"
    assert package["decision_acceptance_policy"]["writes_database"] is False
    assert package["safety"]["executes_search"] is False
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["persists_candidate"] is False


def test_direct_mapping_candidate_decision_package_routes_candidates_to_machine_verifiable_actions():
    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        return True, "found", [
            {
                "product_id": "MOMO-1",
                "name": "Direct mapping product 40ml x2",
                "price": 999,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.92,
                "auto_compare_type": "total_price",
                "target_hard_veto": False,
                "target_price_basis": "total_price",
                "target_gap_pct": 16.8,
                "target_search_term": "direct mapping product 40ml x2",
            },
            {
                "product_id": "MOMO-2",
                "name": "Variant candidate",
                "price": 899,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.51,
                "auto_compare_type": "manual_review",
                "target_hard_veto": False,
            },
        ]

    package = build_pchome_direct_mapping_candidate_decision_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        limit_per_product=3,
        max_terms_per_product=2,
        min_score=0.5,
        search_func=fake_search,
    )

    decisions = package["decision_package"]["candidate_decisions"]
    exception_receipts = package["decision_package"]["machine_review_exception_receipts"]
    assert package["result"] == "DIRECT_MAPPING_CANDIDATE_DECISION_PACKAGE_READY"
    assert package["summary"]["candidates_found_count"] == 2
    assert package["summary"]["candidate_decision_count"] == 2
    assert package["summary"]["auto_compare_decision_count"] == 1
    assert package["summary"]["machine_review_decision_count"] == 1
    assert package["summary"]["machine_review_exception_receipt_count"] == 1
    assert package["summary"]["can_auto_persist_now_count"] == 0
    assert decisions[0]["decision_id"].startswith("pchome-direct-mapping-candidate-")
    assert decisions[0]["decision"] == "route_to_no_write_auto_compare_receipt"
    assert decisions[0]["data_quality"] == "ready_for_no_write_receipt"
    assert decisions[0]["guardrails"]["machine_actionable"] is True
    assert decisions[0]["guardrails"]["can_auto_execute"] is False
    assert decisions[0]["guardrails"]["writes_database"] is False
    assert decisions[0]["guardrails"]["persists_candidate"] is False
    assert decisions[0]["guardrails"]["manual_review_mode"] == "exception_only"
    assert decisions[1]["decision"] == "route_to_machine_review_decision"
    assert decisions[1]["failure_reasons"] == ["auto_compare_type_not_receipt_ready"]
    assert exception_receipts[0]["receipt_id"].startswith("pchome-direct-mapping-exception-")
    assert exception_receipts[0]["source_decision_id"] == decisions[1]["decision_id"]
    assert exception_receipts[0]["failure_reasons"] == ["auto_compare_type_not_receipt_ready"]
    assert exception_receipts[0]["next_machine_actions"] == [
        "run_variant_bundle_discriminator",
        "build_named_candidate_evidence_delta",
    ]
    assert exception_receipts[0]["guardrails"]["writes_database"] is False
    assert package["safety"]["executes_search"] is True
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["persists_candidate"] is False


def test_direct_mapping_candidate_exception_auto_resolution_builds_machine_artifacts():
    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        return True, "found", [
            {
                "product_id": "MOMO-VARIANT",
                "name": "Direct mapping product 40ml 多款任選",
                "price": 899,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.51,
                "auto_compare_type": "manual_review",
                "target_hard_veto": False,
            },
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            },
        ]

    package = build_pchome_direct_mapping_candidate_exception_auto_resolution_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        search_func=fake_search,
    )

    artifacts = package["auto_resolution_package"]["auto_resolution_artifacts"]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_candidate_exception_auto_resolution"
    assert package["result"] == "DIRECT_MAPPING_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
    assert package["summary"]["machine_review_exception_receipt_count"] == 2
    assert package["summary"]["exception_auto_resolution_artifact_count"] == 2
    assert package["summary"]["variant_bundle_discriminator_count"] == 1
    assert package["summary"]["named_candidate_evidence_delta_count"] == 1
    assert package["summary"]["unit_basis_search_expansion_count"] == 1
    assert package["summary"]["retry_search_action_count"] == 1
    assert artifacts[0]["artifact_id"].startswith("pchome-direct-mapping-exception-resolution-")
    assert artifacts[0]["resolution_status"] == "AUTO_RESOLUTION_ARTIFACT_READY"
    assert artifacts[0]["execution_receipt"]["resolver_artifact_built"] is True
    assert artifacts[0]["execution_receipt"]["ready_for_evidence_delta"] is True
    assert artifacts[0]["resolvers"]["variant_bundle_discriminator"]["writes_database"] is False
    assert artifacts[0]["resolvers"]["named_candidate_evidence_delta"]["resolution"] == "ready_for_retry_search"
    assert "unit_basis_search_expansion" in artifacts[1]["resolvers"]
    assert any("40ml" in term.lower() for term in artifacts[1]["resolvers"]["unit_basis_search_expansion"]["expanded_search_terms"])
    assert artifacts[1]["execution_receipt"]["ready_for_retry_search"] is True
    assert artifacts[1]["guardrails"]["can_auto_execute_read_only"] is True
    assert package["summary"]["writes_database_count"] == 0
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["persists_candidate"] is False


def test_direct_mapping_candidate_exception_resolution_closeout_executes_retry_search_without_db_write():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY",
                    "name": "Direct mapping product 40ml 單入",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_match_score": 0.82,
                    "auto_compare_type": "unit_price",
                    "target_hard_veto": False,
                }
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_candidate_exception_resolution_closeout_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
    )

    receipts = package["closeout_package"]["closeout_receipts"]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_candidate_exception_resolution_closeout"
    assert package["result"] == "DIRECT_MAPPING_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
    assert package["summary"]["exception_resolution_closeout_receipt_count"] == 1
    assert package["summary"]["retry_search_ready_count"] == 1
    assert package["summary"]["retry_search_executed_count"] == 1
    assert package["summary"]["retry_candidate_count"] == 1
    assert package["summary"]["ready_for_next_candidate_decision_count"] == 1
    assert receipts[0]["resolution_status"] == "AUTO_RESOLUTION_CLOSEOUT_READY"
    assert receipts[0]["retry_search"]["executed"] is True
    assert receipts[0]["retry_search"]["candidate_count"] == 1
    assert receipts[0]["retry_search"]["candidates"][0]["source_resolution_artifact_id"] == receipts[0]["source_artifact_id"]
    assert receipts[0]["guardrails"]["writes_database"] is False
    assert package["safety"]["executes_retry_search"] is True
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_decision_package_routes_retry_candidates_to_verifier_inputs():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-READY",
                    "name": "Direct mapping product 40ml 單入",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.88,
                    "auto_compare_type": "unit_price",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.72,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_decision_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
    )

    verifier_receipts = package["retry_candidate_decision_package"]["no_write_verifier_receipts"]
    exception_receipts = package["retry_candidate_decision_package"]["machine_review_exception_receipts"]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_decision_package"
    assert package["result"] == "DIRECT_MAPPING_RETRY_CANDIDATE_DECISION_PACKAGE_READY"
    assert package["summary"]["retry_candidate_count"] == 2
    assert package["summary"]["retry_candidate_decision_count"] == 2
    assert package["summary"]["retry_no_write_verifier_input_count"] == 1
    assert package["summary"]["retry_machine_review_exception_count"] == 1
    assert package["summary"]["ready_for_no_write_verifier_count"] == 1
    assert verifier_receipts[0]["receipt_status"] == "NO_WRITE_VERIFIER_INPUT_READY"
    assert verifier_receipts[0]["ready_for_no_write_verifier"] is True
    assert verifier_receipts[0]["guardrails"]["writes_database"] is False
    assert exception_receipts[0]["failure_reasons"] == ["auto_compare_type_not_receipt_ready"]
    assert package["summary"]["writes_database_count"] == 0
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_exception_auto_resolution_package_builds_artifacts():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-VETO",
                    "name": "Direct mapping product 40ml 單入",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "unit_price",
                    "target_hard_veto": True,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
    )

    artifacts = package["retry_exception_auto_resolution_package"]["retry_exception_auto_resolution_artifacts"]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution"
    assert package["result"] == "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
    assert package["summary"]["retry_candidate_count"] == 2
    assert package["summary"]["retry_candidate_decision_count"] == 2
    assert package["summary"]["retry_machine_review_exception_count"] == 2
    assert package["summary"]["retry_exception_auto_resolution_artifact_count"] == 2
    assert package["summary"]["variant_bundle_discriminator_count"] == 1
    assert package["summary"]["named_candidate_evidence_delta_count"] == 1
    assert package["summary"]["unit_basis_search_expansion_count"] == 1
    assert package["summary"]["writes_database_count"] == 0
    assert artifacts[0]["resolution_status"] == "AUTO_RESOLUTION_ARTIFACT_READY"
    assert artifacts[0]["guardrails"]["writes_database"] is False
    assert package["retry_exception_auto_resolution_package"]["resolution_mode"] == "ai_controlled_read_only"
    assert package["safety"]["executes_retry_search"] is True
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_exception_resolution_closeout_package_builds_receipts():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-VETO",
                    "name": "Direct mapping product 40ml 單入",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "unit_price",
                    "target_hard_veto": True,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
    )

    receipts = package["retry_exception_resolution_closeout_package"]["closeout_receipts"]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout"
    assert package["result"] == "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
    assert package["summary"]["retry_exception_auto_resolution_artifact_count"] == 2
    assert package["summary"]["retry_exception_resolution_closeout_receipt_count"] == 2
    assert package["summary"]["exception_resolution_closeout_receipt_count"] == 2
    assert package["summary"]["evidence_delta_closeout_count"] == 1
    assert package["summary"]["retry_search_ready_count"] == 1
    assert package["summary"]["retry_search_executed_count"] == 1
    assert package["summary"]["retry_candidate_count"] == 2
    assert receipts[0]["resolution_status"] == "AUTO_RESOLUTION_CLOSEOUT_READY"
    assert receipts[0]["guardrails"]["writes_database"] is False
    assert package["retry_exception_resolution_closeout_package"]["resolution_mode"] == "ai_controlled_read_only"
    assert package["safety"]["executes_retry_search"] is True
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 3


def test_direct_mapping_retry_candidate_exception_closeout_verifier_input_package_builds_receipts():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-VETO",
                    "name": "Direct mapping product 40ml 單入",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "unit_price",
                    "target_hard_veto": True,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_input_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
    )

    verifier_receipts = package["retry_exception_closeout_verifier_input_package"]["no_write_verifier_receipts"]
    assert package["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_input"
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_INPUT_READY"
    assert package["summary"]["retry_exception_resolution_closeout_receipt_count"] == 2
    assert package["summary"]["closeout_no_write_verifier_input_count"] == 2
    assert package["summary"]["ready_closeout_no_write_verifier_input_count"] == 1
    assert package["summary"]["blocked_closeout_no_write_verifier_input_count"] == 1
    assert package["summary"]["retry_candidate_pending_count"] == 2
    assert verifier_receipts[0]["receipt_status"] == "NO_WRITE_VERIFIER_INPUT_READY"
    assert verifier_receipts[0]["ready_for_no_write_verifier"] is True
    assert verifier_receipts[1]["receipt_status"] == "NO_WRITE_VERIFIER_INPUT_BLOCKED"
    assert verifier_receipts[0]["guardrails"]["writes_database"] is False
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 3


def test_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_package_builds_manifest():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-REVIEW-2",
                    "name": "Direct mapping product 40ml 限量組",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
    )

    preview = package["retry_exception_closeout_verifier_artifact_preview"]
    artifact_keys = [schema["key"] for schema in package["artifact_schemas"]]
    assert package["policy"] == (
        "read_only_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview"
    )
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW_READY"
    assert package["summary"]["verifier_artifact_preview_ready_count"] == 1
    assert package["summary"]["ready_closeout_no_write_verifier_input_count"] == 2
    assert package["summary"]["blocked_closeout_no_write_verifier_input_count"] == 0
    assert package["summary"]["artifact_schema_count"] == 3
    assert package["summary"]["artifact_generation_step_count"] == 5
    assert package["summary"]["verifier_manifest_check_count"] == 15
    assert package["summary"]["writes_artifact_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert preview["preview_id"].startswith("pchome-retry-closeout-verifier-artifacts-")
    assert preview["ready_for_future_artifact_generation"] is True
    assert preview["ready_to_write_artifacts_now"] is False
    assert preview["ready_for_controlled_apply_now"] is False
    assert "retry_exception_closeout_verifier_input_artifact" in artifact_keys
    assert "retry_exception_identity_readback_artifact" in artifact_keys
    assert "retry_exception_controlled_apply_preflight_artifact" in artifact_keys
    assert package["artifact_generation_plan"]["writes_artifact_in_preview"] is False
    assert package["verifier_manifest"]["writes_artifact_in_preview"] is False
    assert package["safety"]["writes_artifact_in_preview"] is False
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_writes_artifacts(tmp_path):
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            if call_count["search"] > 2:
                return True, "retry_clear", []
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-REVIEW-2",
                    "name": "Direct mapping product 40ml 限量組",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
        materialize_artifacts=True,
        artifact_root=tmp_path,
    )

    materialization = package["artifact_materialization_package"]
    assert package["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization"
    )
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACTS_MATERIALIZED"
    assert package["summary"]["artifact_materialization_ready_count"] == 1
    assert package["summary"]["artifact_payload_count"] == 3
    assert package["summary"]["artifact_materialized_count"] == 3
    assert package["summary"]["artifact_write_count"] == 3
    assert package["summary"]["rollback_step_count"] == 3
    assert package["summary"]["post_materialization_verifier_check_count"] == 9
    assert package["summary"]["writes_database_count"] == 0
    assert materialization["run_id"].startswith("pchome-retry-closeout-verifier-run-")
    assert materialization["ready_for_artifact_write"] is True
    assert materialization["ready_for_controlled_apply_now"] is False
    assert package["rollback_plan"]["writes_database"] is False
    assert package["post_materialization_verifier"]["writes_database"] is False
    assert package["safety"]["writes_artifact_count"] == 3
    assert package["safety"]["writes_database"] is False
    assert len(package["materialized_artifacts"]) == 3
    for artifact in package["materialized_artifacts"]:
        artifact_path = Path(artifact["absolute_path"])
        assert artifact_path.exists()
        assert hashlib.sha256(artifact_path.read_bytes()).hexdigest() == artifact["payload_sha256"]
        payload = json.loads(artifact_path.read_text(encoding="utf-8"))
        assert payload["run_id"] == materialization["run_id"]
        assert payload["preview_id"] == materialization["source_preview_id"]
        assert payload["safety"]["writes_database"] is False
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_passes_after_materialization(tmp_path):
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-REVIEW-2",
                    "name": "Direct mapping product 40ml 限量組",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
        materialize_artifacts=True,
        artifact_root=tmp_path,
    )

    verifier = package["artifact_preflight_verifier"]
    assert package["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier"
    )
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACT_PREFLIGHT_VERIFIED"
    assert package["summary"]["artifact_preflight_verifier_ready_count"] == 1
    assert package["summary"]["artifact_payload_count"] == 3
    assert package["summary"]["artifact_readback_count"] == 3
    assert package["summary"]["artifact_readback_pass_count"] == 3
    assert package["summary"]["artifact_readback_fail_count"] == 0
    assert package["summary"]["artifact_hash_match_count"] == 3
    assert package["summary"]["missing_required_field_count"] == 0
    assert package["summary"]["controlled_apply_preflight_contract_count"] == 1
    assert package["summary"]["writes_artifact_count"] == 3
    assert package["summary"]["writes_database_count"] == 0
    assert verifier["ready_for_controlled_apply_preflight"] is True
    assert verifier["ready_for_database_apply_now"] is False
    assert package["controlled_apply_preflight_contract"]["contract_ready"] is True
    assert package["controlled_apply_preflight_contract"]["allows_database_write_now"] is False
    assert all(readback["passed"] for readback in package["artifact_readbacks"])
    assert all(readback["hash_match"] for readback in package["artifact_readbacks"])
    assert package["safety"]["reads_artifact_files"] is True
    assert package["safety"]["writes_database"] is False

    drift_payload = json.loads(json.dumps(_payload()))
    drift_payload["generated_at"] = "2026-07-01T23:59:59"
    drift_package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_package(
        drift_payload,
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
        materialize_artifacts=False,
        artifact_root=tmp_path,
    )
    assert drift_package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_VERIFIER_ARTIFACT_PREFLIGHT_VERIFIED"
    assert drift_package["summary"]["artifact_readback_pass_count"] == 3
    assert drift_package["summary"]["artifact_hash_match_count"] == 3
    assert drift_package["summary"]["writes_artifact_count"] == 0
    assert drift_package["safety"]["writes_database"] is False
    assert call_count["search"] == 4


def test_direct_mapping_retry_candidate_exception_controlled_apply_preflight_builds_executor_guard(tmp_path):
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-REVIEW-2",
                    "name": "Direct mapping product 40ml 限量組",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_preflight_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
        materialize_artifacts=True,
        artifact_root=tmp_path,
    )

    preflight = package["controlled_apply_preflight"]
    assert package["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_preflight"
    )
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_PREFLIGHT_READY"
    assert package["summary"]["controlled_apply_preflight_ready_count"] == 1
    assert package["summary"]["target_selector_count"] == 2
    assert package["summary"]["mutation_plan_count"] == 2
    assert package["summary"]["rollback_step_count"] == 2
    assert package["summary"]["post_apply_readback_check_count"] == 5
    assert package["summary"]["guard_check_count"] == 9
    assert package["summary"]["guard_fail_count"] == 0
    assert package["summary"]["executes_database_write_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert preflight["preflight_id"].startswith("pchome-retry-exception-controlled-apply-preflight-")
    assert preflight["ready_for_controlled_apply_executor"] is True
    assert preflight["ready_for_database_apply_now"] is False
    assert package["mutation_plan"]["executes_in_preflight"] is False
    assert package["mutation_plan"]["writes_database"] is False
    assert package["rollback_plan"]["writes_database"] is False
    assert package["post_apply_readback_plan"]["readback_check_count"] == 5
    assert package["executor_guard"]["all_passed"] is True
    assert package["executor_guard"]["allows_database_write_now"] is False
    assert {selector["momo_product_id"] for selector in package["target_selectors"]} == {
        "MOMO-RETRY-REVIEW",
        "MOMO-RETRY-REVIEW-2",
    }
    assert package["safety"]["executes_database_write_in_preflight"] is False
    assert package["safety"]["writes_database"] is False
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_exception_controlled_apply_executor_writes_matches(tmp_path):
    from sqlalchemy import create_engine, text

    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-REVIEW-2",
                    "name": "Direct mapping product 40ml 限量組",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    engine = create_engine(f"sqlite:///{tmp_path / 'executor.db'}")
    with engine.begin() as conn:
        conn.execute(text("""
            CREATE TABLE pchome_product_matches (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                momo_name TEXT NOT NULL,
                momo_icode VARCHAR(120) UNIQUE,
                momo_price DOUBLE PRECISION,
                pchome_id VARCHAR(120),
                pchome_name TEXT,
                pchome_url TEXT,
                pchome_price DOUBLE PRECISION,
                pchome_original DOUBLE PRECISION,
                pchome_in_stock BOOLEAN DEFAULT 1,
                similarity DOUBLE PRECISION,
                price_diff DOUBLE PRECISION,
                price_diff_pct DOUBLE PRECISION,
                advantage VARCHAR(20),
                last_checked TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """))

    package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_executor_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
        materialize_artifacts=True,
        artifact_root=tmp_path,
        execute_apply=True,
        engine=engine,
    )

    assert package["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_executor"
    )
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_EXECUTED"
    assert package["summary"]["controlled_apply_executor_ready_count"] == 1
    assert package["summary"]["execute_apply_requested_count"] == 1
    assert package["summary"]["target_selector_count"] == 2
    assert package["summary"]["prewrite_snapshot_count"] == 2
    assert package["summary"]["applied_record_count"] == 2
    assert package["summary"]["post_apply_readback_pass_count"] == 2
    assert package["summary"]["writes_database_count"] == 2
    assert package["summary"]["persists_candidate_count"] == 2
    assert package["summary"]["executor_receipt_ready_count"] == 1
    assert package["summary"]["executor_receipt_materialized_count"] == 1
    assert package["summary"]["executor_receipt_hash_match_count"] == 1
    assert package["controlled_apply_executor"]["target_table"] == "pchome_product_matches"
    assert package["controlled_apply_executor"]["write_attempted"] is True
    assert package["controlled_apply_executor"]["ready_for_apply"] is True
    assert all(readback["passed"] for readback in package["post_apply_readbacks"])
    assert package["rollback_plan"]["rollback_step_count"] == 2
    assert package["post_executor_receipt_verifier"]["passed"] is True
    assert package["post_executor_receipt_verifier"]["hash_match"] is True
    assert len(package["materialized_executor_artifacts"]) == 1
    receipt = package["materialized_executor_artifacts"][0]
    receipt_path = Path(receipt["absolute_path"])
    assert receipt_path.exists()
    assert hashlib.sha256(receipt_path.read_bytes()).hexdigest() == receipt["payload_sha256"]
    receipt_payload = json.loads(receipt_path.read_text(encoding="utf-8"))
    assert receipt_payload["executor_id"] == package["controlled_apply_executor"]["executor_id"]
    assert receipt_payload["summary"]["applied_record_count"] == 2
    assert receipt_payload["summary"]["post_apply_readback_pass_count"] == 2
    assert receipt_payload["safety"]["writes_database_count"] == 2
    assert package["safety"]["execute_apply"] is True
    assert package["safety"]["writes_database_count"] == 2
    assert package["safety"]["writes_artifact_count"] == 1
    with engine.connect() as conn:
        rows = conn.execute(text("""
            SELECT momo_icode, pchome_id, advantage
            FROM pchome_product_matches
            ORDER BY momo_icode
        """)).mappings().all()
    assert [row["momo_icode"] for row in rows] == ["MOMO-RETRY-REVIEW", "MOMO-RETRY-REVIEW-2"]
    assert {row["pchome_id"] for row in rows} == {"PCH-2"}
    assert {row["advantage"] for row in rows} == {"ai_match"}
    assert call_count["search"] == 2


def test_direct_mapping_retry_candidate_exception_controlled_apply_executor_blocks_zero_selector_apply():
    package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_executor_package(
        _payload(),
        batch_size=1,
        execute_apply=True,
    )

    assert package["result"] == "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_PREFLIGHT"
    assert package["summary"]["target_selector_count"] == 0
    assert package["summary"]["applied_record_count"] == 0
    assert package["summary"]["executor_receipt_ready_count"] == 0
    assert package["summary"]["executor_receipt_materialized_count"] == 0
    assert package["controlled_apply_executor"]["write_attempted"] is False
    assert "engine_required_for_execute_apply" in package["write_blockers"]
    assert "controlled_apply_preflight_not_ready" in package["write_blockers"]
    assert package["post_executor_receipt_verifier"]["passed"] is False
    assert package["safety"]["writes_database_count"] == 0


def test_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_materializes_readback(tmp_path):
    from sqlalchemy import create_engine, text

    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        if targets[0].get("source_artifact_id"):
            return True, "retry_found", [
                {
                    "product_id": "MOMO-RETRY-REVIEW",
                    "name": "Direct mapping product 40ml 多款任選",
                    "price": 499,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.74,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
                {
                    "product_id": "MOMO-RETRY-REVIEW-2",
                    "name": "Direct mapping product 40ml 限量組",
                    "price": 520,
                    "target_pchome_product_id": "PCH-2",
                    "target_pchome_name": "Direct mapping product 40ml x2",
                    "target_match_score": 0.91,
                    "auto_compare_type": "manual_review",
                    "target_hard_veto": False,
                },
            ]
        return True, "found", [
            {
                "product_id": "MOMO-UNIT",
                "name": "Direct mapping product 40ml",
                "price": 499,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.91,
                "auto_compare_type": "unit_price",
                "target_hard_veto": True,
            }
        ]

    artifact_package = build_pchome_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_package(
        _payload(),
        batch_size=1,
        execute_search=True,
        execute_retry_search=True,
        max_terms_per_product=6,
        search_func=fake_search,
        materialize_artifacts=True,
        artifact_root=tmp_path,
    )
    run_id = artifact_package["artifact_materialization_package"]["run_id"]
    engine = create_engine(f"sqlite:///{tmp_path / 'receipt-replay.db'}")
    with engine.begin() as conn:
        conn.execute(text("""
            CREATE TABLE pchome_product_matches (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                momo_name TEXT NOT NULL,
                momo_icode VARCHAR(120) UNIQUE,
                momo_price DOUBLE PRECISION,
                pchome_id VARCHAR(120),
                pchome_name TEXT,
                pchome_url TEXT,
                pchome_price DOUBLE PRECISION,
                pchome_original DOUBLE PRECISION,
                pchome_in_stock BOOLEAN DEFAULT 1,
                similarity DOUBLE PRECISION,
                price_diff DOUBLE PRECISION,
                price_diff_pct DOUBLE PRECISION,
                advantage VARCHAR(20),
                last_checked TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """))
        conn.execute(text("""
            INSERT INTO pchome_product_matches (momo_name, momo_icode, momo_price, pchome_id, pchome_name, advantage)
            VALUES
                ('Direct mapping product 40ml 多款任選', 'MOMO-RETRY-REVIEW', 499, 'PCH-2', 'Direct mapping product 40ml x2', 'ai_match'),
                ('Direct mapping product 40ml 限量組', 'MOMO-RETRY-REVIEW-2', 520, 'PCH-2', 'Direct mapping product 40ml x2', 'ai_match')
        """))

    package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
        artifact_root=tmp_path,
        run_id=run_id,
        materialize_artifacts=True,
        engine=engine,
    )

    assert package["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay"
    )
    assert package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_RECEIPT_REPLAYED"
    assert package["summary"]["target_selector_count"] == 2
    assert package["summary"]["post_apply_readback_pass_count"] == 2
    assert package["summary"]["executor_receipt_ready_count"] == 1
    assert package["summary"]["executor_receipt_materialized_count"] == 1
    assert package["summary"]["executor_receipt_hash_match_count"] == 1
    assert package["post_executor_receipt_verifier"]["passed"] is True
    assert package["post_executor_receipt_verifier"]["hash_match"] is True
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["writes_database_count"] == 0
    assert package["safety"]["writes_artifact_count"] == 1
    receipt = package["materialized_executor_artifacts"][0]
    receipt_path = Path(receipt["absolute_path"])
    assert receipt_path.exists()
    assert hashlib.sha256(receipt_path.read_bytes()).hexdigest() == receipt["payload_sha256"]
    receipt_payload = json.loads(receipt_path.read_text(encoding="utf-8"))
    assert receipt_payload["run_id"] == run_id
    assert receipt_payload["summary"]["post_apply_readback_pass_count"] == 2
    read_only_package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_receipt_replay_package(
        artifact_root=tmp_path,
        run_id=run_id,
        materialize_artifacts=False,
        engine=engine,
    )
    assert read_only_package["summary"]["executor_receipt_materialized_count"] == 1
    assert read_only_package["summary"]["executor_receipt_hash_match_count"] == 1
    assert read_only_package["post_executor_receipt_verifier"]["hash_match"] is True
    verifier = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=read_only_package,
        materialize_artifacts=True,
    )
    assert verifier["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_VERIFIED"
    assert verifier["summary"]["target_selector_count"] == 2
    assert verifier["summary"]["drift_count"] == 0
    assert verifier["summary"]["drift_verified_count"] == 1
    assert verifier["summary"]["drift_verifier_artifact_materialized_count"] == 1
    assert verifier["summary"]["drift_verifier_artifact_hash_match_count"] == 1
    assert verifier["post_drift_verifier_artifact_verifier"]["hash_match"] is True
    drift_receipt = verifier["materialized_drift_artifacts"][0]
    drift_receipt_path = Path(drift_receipt["absolute_path"])
    assert drift_receipt_path.exists()
    assert hashlib.sha256(drift_receipt_path.read_bytes()).hexdigest() == drift_receipt["payload_sha256"]
    assert verifier["safety"]["writes_database"] is False
    assert verifier["safety"]["writes_artifact_count"] == 1
    no_drift_recovery = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_recovery_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=read_only_package,
        source_drift_verifier=verifier,
        materialize_artifacts=True,
    )
    assert no_drift_recovery["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_NOT_REQUIRED"
    assert no_drift_recovery["summary"]["drift_recovery_action_count"] == 0
    assert no_drift_recovery["summary"]["recovery_artifact_materialized_count"] == 1
    assert no_drift_recovery["post_recovery_artifact_verifier"]["hash_match"] is True
    assert no_drift_recovery["safety"]["writes_database"] is False
    compact = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_compact_readback_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
        source_receipt_replay=read_only_package,
        source_drift_verifier=verifier,
        source_drift_recovery=no_drift_recovery,
        materialize_artifacts=True,
    )
    assert compact["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_VERIFIED"
    assert compact["summary"]["target_selector_count"] == 2
    assert compact["summary"]["post_apply_readback_pass_count"] == 2
    assert compact["summary"]["drift_count"] == 0
    assert compact["summary"]["compact_readback_artifact_materialized_count"] == 1
    assert compact["summary"]["compact_readback_artifact_hash_match_count"] == 1
    assert compact["compact_readback"]["status"] == "completed"
    assert compact["compact_readback"]["next_machine_action"] == "keep_monitoring_drift"
    assert compact["summary"]["apply_receipt_hash_match_count"] == 1
    assert compact["receipts"]["apply"]["hash_match"] is True
    assert compact["receipts"]["replay"]["hash_match"] is True
    assert compact["receipts"]["drift"]["hash_match"] is True
    assert compact["receipts"]["recovery"]["hash_match"] is True
    assert compact["post_compact_artifact_verifier"]["hash_match"] is True
    assert compact["safety"]["writes_database"] is False
    with engine.begin() as conn:
        conn.execute(text("""
            UPDATE pchome_product_matches
            SET pchome_id = 'PCH-DRIFT'
            WHERE momo_icode = 'MOMO-RETRY-REVIEW'
        """))
    drift_package = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_verifier_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
    )
    assert drift_package["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_DETECTED"
    assert drift_package["summary"]["drift_count"] == 1
    assert drift_package["drift_items"][0]["momo_icode"] == "MOMO-RETRY-REVIEW"
    assert drift_package["drift_items"][0]["actual_pchome_id"] == "PCH-DRIFT"
    recovery = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_drift_recovery_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
        source_drift_verifier=drift_package,
        materialize_artifacts=True,
    )
    assert recovery["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_RECOVERY_PACKAGE_READY"
    assert recovery["summary"]["drift_count"] == 1
    assert recovery["summary"]["drift_recovery_action_count"] == 1
    assert recovery["summary"]["drift_reapply_ready_count"] == 1
    assert recovery["summary"]["writes_database_count"] == 0
    assert recovery["dry_run_plan"]["ready"] is True
    assert recovery["dry_run_plan"]["executes_in_package"] is False
    assert recovery["rollback_plan"]["rollback_action_count"] == 1
    assert recovery["recovery_actions"][0]["action_type"] == "reapply_expected_match"
    assert recovery["recovery_actions"][0]["momo_icode"] == "MOMO-RETRY-REVIEW"
    assert recovery["recovery_actions"][0]["expected_pchome_id"] == "PCH-2"
    assert recovery["recovery_actions"][0]["actual_pchome_id"] == "PCH-DRIFT"
    assert "UPDATE pchome_product_matches" in recovery["recovery_actions"][0]["controlled_reapply_sql_shape"]
    assert recovery["recovery_actions"][0]["writes_database"] is False
    assert recovery["summary"]["recovery_artifact_materialized_count"] == 1
    assert recovery["summary"]["recovery_artifact_hash_match_count"] == 1
    assert recovery["post_recovery_artifact_verifier"]["hash_match"] is True
    assert recovery["safety"]["writes_database"] is False
    assert recovery["safety"]["writes_artifact_count"] == 1
    drift_compact = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_compact_readback_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
        source_drift_verifier=drift_package,
        source_drift_recovery=recovery,
        materialize_artifacts=True,
    )
    assert drift_compact["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_COMPACT_READBACK_DRIFT_REQUIRES_RECOVERY"
    assert drift_compact["summary"]["drift_count"] == 1
    assert drift_compact["summary"]["drift_recovery_action_count"] == 1
    assert drift_compact["compact_readback"]["status"] == "blocked"
    assert drift_compact["compact_readback"]["next_machine_action"] == "run_controlled_reapply_check_mode"
    assert drift_compact["summary"]["compact_readback_artifact_materialized_count"] == 1
    assert drift_compact["post_compact_artifact_verifier"]["hash_match"] is True
    assert drift_compact["safety"]["writes_database"] is False
    retention = build_pchome_direct_mapping_retry_candidate_exception_controlled_apply_artifact_retention_package(
        artifact_root=tmp_path,
        run_id=run_id,
        engine=engine,
        source_compact_readback=drift_compact,
        keep_latest_per_family=1,
        materialize_artifacts=True,
    )
    assert retention["result"] == "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_ARTIFACT_RETENTION_POLICY_READY"
    assert retention["summary"]["retention_family_count"] == 8
    assert retention["summary"]["artifact_count"] >= 8
    assert retention["summary"]["retained_artifact_count"] > 0
    assert retention["summary"]["prune_candidate_count"] >= 1
    assert retention["summary"]["artifact_count"] == (
        retention["summary"]["retained_artifact_count"]
        + retention["summary"]["prune_candidate_count"]
    )
    assert retention["summary"]["retention_prune_executes_count"] == 0
    assert retention["summary"]["retention_artifact_materialized_count"] == 1
    assert retention["summary"]["retention_artifact_hash_match_count"] == 1
    assert retention["post_retention_artifact_verifier"]["hash_match"] is True
    assert retention["safety"]["deletes_artifacts"] is False
    assert retention["safety"]["retention_prune_executes"] is False
    assert retention["safety"]["writes_database"] is False
    protected_paths = set(retention["protected_active_chain_paths"])
    assert drift_compact["compact_artifact"]["relative_path"] in protected_paths
    prune_candidates = [
        artifact
        for family in retention["family_reports"]
        for artifact in family["artifacts"]
        if artifact["retention_decision"] == "candidate_for_retention_prune"
    ]
    assert prune_candidates
    assert all(candidate["delete_in_package"] is False for candidate in prune_candidates)
    assert call_count["search"] == 2


def test_ai_automation_readiness_makes_automation_visible_without_manual_primary_flow():
    readiness = build_pchome_growth_ai_automation_readiness(_payload(), batch_size=1)

    lanes = {lane["key"]: lane for lane in readiness["automation_lanes"]}
    assert readiness["policy"] == "read_only_pchome_growth_ai_automation_readiness"
    assert readiness["result"] == "AI_AUTOMATION_ACTIVE_WAITING_FOR_CANDIDATES"
    assert readiness["summary"]["direct_mapping_count"] == 2
    assert readiness["summary"]["selected_search_target_count"] == 1
    assert readiness["summary"]["planned_search_term_count"] >= 1
    assert readiness["summary"]["waiting_candidate_count"] == 1
    assert readiness["summary"]["primary_human_gate_count"] == 0
    assert readiness["summary"]["ai_exception_count"] == 0
    assert readiness["summary"]["machine_review_exception_receipt_count"] == 0
    assert readiness["summary"]["manual_required_as_primary_flow_count"] == 0
    assert readiness["automation_policy"]["primary_flow"] == "ai_controlled"
    assert readiness["automation_policy"]["human_primary_flow"] is False
    assert readiness["ai_exception_auto_resolution"]["mode"] == "machine_verifiable_auto_resolution"
    assert readiness["ai_exception_auto_resolution"]["primary_human_gate_count"] == 0
    assert readiness["manual_policy"]["manual_review_mode"] == "exception_only"
    assert readiness["manual_policy"]["deprecated_product_surface"] is True
    assert readiness["manual_policy"]["manual_as_primary_flow"] is False
    assert lanes["same_item_search_package"]["status"] == "ready"
    assert lanes["candidate_decision_package"]["status"] == "waiting"
    assert lanes["candidate_decision_package"]["ai_exception_mode"] == "machine_verifiable_auto_resolution"
    assert lanes["controlled_apply"]["status"] == "blocked_until_verifier"
    assert readiness["safety"]["writes_database"] is False
    assert readiness["safety"]["llm_calls_in_preview"] is False


def test_ai_automation_readiness_surfaces_controlled_apply_receipt_replay_closeout():
    readiness = build_pchome_growth_ai_automation_readiness(
        _payload(),
        batch_size=1,
        controlled_apply_receipt_replay={
            "result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_RECEIPT_REPLAYED",
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 4,
                "executor_receipt_ready_count": 1,
                "executor_receipt_materialized_count": 1,
                "executor_receipt_hash_match_count": 1,
            },
            "safety": {
                "writes_database": False,
            },
        },
        controlled_apply_drift_verifier={
            "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,
                "receipt_hash_match_count": 1,
                "drift_verifier_artifact_materialized_count": 1,
                "drift_verifier_artifact_hash_match_count": 1,
            },
        },
    )

    lanes = {lane["key"]: lane for lane in readiness["automation_lanes"]}
    assert readiness["result"] == "AI_AUTOMATION_CONTROLLED_APPLY_CLOSEOUT_VERIFIED"
    assert readiness["summary"]["controlled_apply_replay_selector_count"] == 4
    assert readiness["summary"]["controlled_apply_replay_readback_pass_count"] == 4
    assert readiness["summary"]["controlled_apply_receipt_materialized_count"] == 1
    assert readiness["summary"]["controlled_apply_closeout_verified_count"] == 1
    assert readiness["summary"]["controlled_apply_drift_count"] == 0
    assert readiness["summary"]["controlled_apply_drift_verified_count"] == 1
    assert readiness["summary"]["controlled_apply_drift_artifact_count"] == 1
    assert readiness["summary"]["controlled_apply_drift_artifact_hash_match_count"] == 1
    assert readiness["automation_policy"]["controlled_apply_closeout"] == "receipt_replay_machine_verified"
    assert readiness["automation_policy"]["controlled_apply_drift"] == "drift_verified"
    assert lanes["controlled_apply"]["status"] == "completed"
    assert lanes["controlled_apply"]["value"] == 4
    assert lanes["controlled_apply_receipt_replay"]["status"] == "completed"
    assert lanes["controlled_apply_receipt_replay"]["value"] == 1
    assert lanes["controlled_apply_drift_verifier"]["status"] == "completed"
    assert lanes["controlled_apply_drift_verifier"]["value"] == 0
    assert readiness["safety"]["reads_database_for_receipt_replay"] is True
    assert readiness["safety"]["reads_database_for_drift_verifier"] is True
    assert readiness["safety"]["writes_database"] is False


def test_ai_automation_readiness_surfaces_controlled_apply_drift_detected():
    readiness = build_pchome_growth_ai_automation_readiness(
        _payload(),
        batch_size=1,
        controlled_apply_receipt_replay={
            "result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_RECEIPT_REPLAY_READBACK_MISMATCH",
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 3,
                "executor_receipt_ready_count": 0,
                "executor_receipt_materialized_count": 1,
                "executor_receipt_hash_match_count": 0,
            },
        },
        controlled_apply_drift_verifier={
            "result": "DIRECT_MAPPING_RETRY_EXCEPTION_CONTROLLED_APPLY_DRIFT_DETECTED",
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 3,
                "drift_count": 1,
                "drift_verified_count": 0,
                "receipt_hash_match_count": 0,
            },
        },
    )

    lanes = {lane["key"]: lane for lane in readiness["automation_lanes"]}
    assert readiness["result"] == "AI_AUTOMATION_CONTROLLED_APPLY_DRIFT_DETECTED"
    assert readiness["summary"]["controlled_apply_drift_count"] == 1
    assert readiness["automation_policy"]["controlled_apply_drift"] == "drift_detected"
    assert lanes["controlled_apply_drift_verifier"]["status"] == "blocked"
    assert lanes["controlled_apply_drift_verifier"]["value"] == 1
    assert readiness["safety"]["writes_database"] is False


def test_ai_automation_surface_summary_turns_readiness_into_golden_signals():
    readiness = build_pchome_growth_ai_automation_readiness(
        _payload(),
        batch_size=1,
        controlled_apply_receipt_replay={
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 4,
                "executor_receipt_ready_count": 1,
                "executor_receipt_materialized_count": 1,
                "executor_receipt_hash_match_count": 1,
            },
        },
        controlled_apply_drift_verifier={
            "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,
            },
        },
    )

    surface = build_pchome_growth_ai_automation_surface_summary(readiness)
    signals = {signal["key"]: signal for signal in surface["golden_signals"]}

    assert surface["policy"] == "read_only_pchome_growth_ai_automation_surface_summary"
    assert surface["summary"]["safe_lane_count"] >= 4
    assert surface["summary"]["ready_lane_count"] >= 1
    assert surface["summary"]["completed_lane_count"] >= 1
    assert surface["summary"]["controlled_apply_replay_readback_pass_count"] == 4
    assert surface["summary"]["controlled_apply_drift_count"] == 0
    assert surface["summary"]["primary_human_gate_count"] == 0
    assert surface["summary"]["manual_required_as_primary_flow_count"] == 0
    assert surface["summary"]["writes_database_count"] == 0
    assert set(signals) == {
        "automated-landing",
        "verified",
        "change-state",
        "next-machine-action",
    }
    assert signals["automated-landing"]["label"] == "已自動落地"
    assert signals["verified"]["label"] == "已驗證"
    assert signals["change-state"]["label"] == "異動狀態"
    assert signals["next-machine-action"]["label"] == "下一步"
    assert signals["automated-landing"]["value"] == "已完成回讀"
    assert "4/4" in signals["automated-landing"]["detail"]
    assert signals["verified"]["value"] == "4 筆已回讀"
    assert signals["change-state"]["value"] == "無漂移"
    assert surface["surface_contract"]["first_viewport_required"] is True
    assert surface["surface_contract"]["raw_evidence_hidden_from_first_viewport"] is True
    assert surface["safety"]["writes_database"] is False
    assert surface["safety"]["llm_calls_in_preview"] is False


def test_ai_automation_surface_summary_prioritizes_drift_recovery_action():
    readiness = build_pchome_growth_ai_automation_readiness(
        _payload(),
        batch_size=1,
        controlled_apply_receipt_replay={
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 3,
                "executor_receipt_ready_count": 0,
                "executor_receipt_materialized_count": 1,
                "executor_receipt_hash_match_count": 0,
            },
        },
        controlled_apply_drift_verifier={
            "summary": {
                "target_selector_count": 4,
                "post_apply_readback_pass_count": 3,
                "drift_count": 1,
                "drift_verified_count": 0,
            },
        },
    )

    surface = build_pchome_growth_ai_automation_surface_summary(readiness)
    signals = {signal["key"]: signal for signal in surface["golden_signals"]}

    assert surface["summary"]["controlled_apply_drift_count"] == 1
    assert surface["summary"]["next_machine_action"] == "執行漂移恢復、重新回讀與 rollback path 比對"
    assert signals["change-state"]["value"] == "1 筆漂移"
    assert signals["change-state"]["status"] == "bad"
    assert signals["next-machine-action"]["value"] == surface["summary"]["next_machine_action"]
    assert surface["safety"]["writes_database"] is False


def test_ai_automation_readiness_reports_candidate_decisions_after_controlled_search():
    call_count = {"search": 0}

    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        call_count["search"] += 1
        return True, "found", [
            {
                "product_id": "MOMO-1",
                "name": "Direct mapping product 40ml x2",
                "price": 999,
                "target_pchome_product_id": "PCH-2",
                "target_match_score": 0.92,
                "auto_compare_type": "total_price",
                "target_hard_veto": False,
            }
        ]

    readiness = build_pchome_growth_ai_automation_readiness(
        _payload(),
        batch_size=1,
        execute_search=True,
        search_func=fake_search,
    )

    lanes = {lane["key"]: lane for lane in readiness["automation_lanes"]}
    assert readiness["result"] == "AI_AUTOMATION_CANDIDATE_DECISIONS_READY"
    assert readiness["summary"]["candidate_decision_count"] == 1
    assert readiness["summary"]["waiting_candidate_count"] == 0
    assert readiness["summary"]["auto_compare_decision_count"] == 1
    assert readiness["summary"]["machine_review_decision_count"] == 0
    assert readiness["summary"]["machine_review_exception_receipt_count"] == 0
    assert readiness["summary"]["external_network_execute_count"] == 1
    assert lanes["candidate_decision_package"]["status"] == "ready"
    assert readiness["safety"]["executes_search"] is True
    assert readiness["safety"]["writes_database"] is False
    assert call_count["search"] == 1


def test_ai_automation_readiness_reports_exception_auto_resolution_ready():
    def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
        return True, "found", [
            {
                "product_id": "MOMO-VARIANT",
                "name": "Direct mapping product 40ml 多款任選",
                "price": 899,
                "target_pchome_product_id": "PCH-2",
                "target_pchome_name": "Direct mapping product 40ml x2",
                "target_match_score": 0.51,
                "auto_compare_type": "manual_review",
                "target_hard_veto": False,
            }
        ]

    readiness = build_pchome_growth_ai_automation_readiness(
        _payload(),
        batch_size=1,
        execute_search=True,
        search_func=fake_search,
    )

    lanes = {lane["key"]: lane for lane in readiness["automation_lanes"]}
    assert readiness["result"] == "AI_AUTOMATION_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
    assert readiness["summary"]["candidate_decision_count"] == 1
    assert readiness["summary"]["machine_review_exception_receipt_count"] == 1
    assert readiness["summary"]["exception_auto_resolution_artifact_count"] == 1
    assert readiness["summary"]["exception_resolution_closeout_receipt_count"] == 1
    assert readiness["summary"]["evidence_delta_closeout_count"] == 1
    assert readiness["summary"]["variant_bundle_discriminator_count"] == 1
    assert readiness["summary"]["named_candidate_evidence_delta_count"] == 1
    assert readiness["ai_exception_auto_resolution"]["exception_auto_resolution_artifact_count"] == 1
    assert readiness["ai_exception_auto_resolution"]["exception_resolution_closeout_receipt_count"] == 1
    assert lanes["candidate_exception_auto_resolution"]["status"] == "ready"
    assert lanes["candidate_exception_auto_resolution"]["value"] == 1
    assert lanes["candidate_exception_resolution_closeout"]["status"] == "ready"
    assert lanes["candidate_exception_resolution_closeout"]["value"] == 1
    assert readiness["summary"]["primary_human_gate_count"] == 0
    assert readiness["summary"]["writes_database_count"] == 0
    assert readiness["safety"]["writes_database"] is False


def test_unit_package_basis_parser_extracts_quantity_count_and_risk_signals():
    single = parse_unit_package_basis("雅詩蘭黛 粉持久完美持妝粉底 30ml")
    assert single["package_basis"] == "single_unit_quantity_candidate"
    assert single["quantities"][0] == {"value": 30, "unit": "ml", "raw": "30ml"}
    assert single["unit_pricing_measure"] == {"value": 30, "unit": "ml"}
    assert single["unit_pricing_base_measure"] == {"value": 100, "unit": "ml"}
    assert single["human_review_required"] is False
    assert single["ai_exception_required"] is False
    assert single["primary_human_gate_count"] == 0
    assert single["writes_database"] is False
    assert single["fetches_external_sites"] is False
    assert single["llm_calls"] is False

    bundle = parse_unit_package_basis("理膚寶水 B5 修復霜 40ml x2 超值組")
    assert bundle["package_basis"] == "variant_sensitive_quantity_candidate"
    assert bundle["multipliers"] == [2]
    assert bundle["estimated_total_quantity"] == 80
    assert "bundle_or_promo" in bundle["risk_signals"]
    assert bundle["human_review_required"] is False
    assert bundle["legacy_human_review_required"] is True
    assert bundle["ai_exception_required"] is True

    variant = parse_unit_package_basis("Dior 癮誘唇膏 3.2g 多款任選")
    assert variant["package_basis"] == "variant_sensitive_quantity_candidate"
    assert variant["unit_label"] == "g"
    assert "variant_selection" in variant["risk_signals"]
    assert variant["human_review_required"] is False
    assert variant["legacy_human_review_required"] is True
    assert variant["ai_exception_required"] is True

    count_only = parse_unit_package_basis("濕紙巾 42張")
    assert count_only["package_basis"] == "count_package_candidate"
    assert count_only["unit_pricing_measure"] == {"value": 42, "unit": "ct"}


def test_evidence_enrichment_preview_builds_missing_field_tasks():
    preview = build_pchome_evidence_enrichment_preview(_payload(), batch_size=1)

    assert preview["policy"] == "read_only_pchome_growth_evidence_enrichment_preview"
    assert preview["result"] == "NEEDS_EVIDENCE_ENRICHMENT"
    assert preview["summary"]["task_count"] == 2
    assert preview["summary"]["tasks_with_blockers"] == 2
    assert preview["summary"]["missing_field_counts"]["image"] == 2
    assert preview["summary"]["missing_field_counts"]["availability"] == 2
    assert preview["summary"]["missing_field_counts"]["unit_price_or_package_basis"] == 1
    assert preview["evidence_tasks"][0]["lane"] == "direct_mapping"
    assert preview["evidence_tasks"][0]["product_url"] == "https://24h.pchome.com.tw/prod/PCH-2"
    assert "unit_price_or_package_basis" not in preview["evidence_tasks"][0]["missing_fields"]
    assert preview["evidence_tasks"][0]["unit_package_basis"]["estimated_total_quantity"] == 80
    assert "image" in preview["evidence_tasks"][0]["blocking_missing_fields"]
    assert preview["evidence_tasks"][0]["enrichment_steps"][0]["sources"][0]["writes_database"] is False
    assert preview["ai_automation_plan"]["policy"] == "ollama_first_read_only_evidence_assist"
    assert preview["ai_automation_plan"]["llm_calls_in_preview"] is False
    assert preview["safety"]["fetches_external_sites"] is False
    assert preview["safety"]["writes_database"] is False


def test_review_candidate_pchome_price_counts_as_price_evidence():
    payload = json.loads(json.dumps(_payload()))
    payload["opportunities"][2]["review_candidate"]["pchome_price"] = 880

    preview = build_pchome_evidence_enrichment_preview(payload, batch_size=1)
    review_task = next(task for task in preview["evidence_tasks"] if task["pchome_product_id"] == "PCH-3")

    assert "price" not in review_task["missing_fields"]
    assert "price" in review_task["present_fields"]


def test_evidence_source_preview_plans_read_only_fetch_gates_without_fetching():
    preview = build_pchome_evidence_source_preview(_payload(), batch_size=1)

    assert preview["policy"] == "read_only_pchome_growth_evidence_source_preview"
    assert preview["result"] == "NEEDS_SOURCE_WIRING"
    assert preview["source_policy"] == "read_only_pchome_growth_evidence_enrichment_preview"
    assert preview["summary"]["field_counts"]["image"]["missing_count"] == 2
    assert preview["summary"]["field_counts"]["availability"]["missing_count"] == 2
    assert preview["summary"]["field_counts"]["price"]["missing_count"] == 1
    assert preview["source_plans"]["image"]["future_read_only_fetch_gate"]["method"] == "GET"
    assert (
        preview["source_plans"]["image"]["future_read_only_fetch_gate"]["check_mode_parser"]
        == "read_only_pchome_product_page_evidence_parser"
    )
    assert preview["source_plans"]["image"]["future_read_only_fetch_gate"]["fetches_external_sites_in_preview"] is False
    assert preview["source_plans"]["availability"]["future_read_only_fetch_gate"]["writes_database"] is False
    assert preview["source_plans"]["price"]["payload_mapping_probe"]["writes_database"] is False
    assert preview["fetch_gate_candidates"][0]["product_url"] == "https://24h.pchome.com.tw/prod/PCH-2"
    assert preview["fetch_gate_candidates"][0]["executes_fetch_in_preview"] is False
    assert preview["ai_automation_plan"]["llm_calls_in_preview"] is False
    assert preview["ai_automation_plan"]["gemini_allowed"] is False
    assert preview["safety"]["fetches_external_sites"] is False
    assert preview["safety"]["writes_database"] is False


def test_product_page_evidence_parser_reads_jsonld_without_fetching():
    html = """
    <html><head>
      <script type="application/ld+json">
        {
          "@context": "https://schema.org",
          "@type": "Product",
          "name": "Example product",
          "image": ["https://cdn.example.test/product.jpg"],
          "offers": {
            "@type": "Offer",
            "price": "1200",
            "availability": "https://schema.org/InStock"
          }
        }
      </script>
    </head></html>
    """

    parsed = parse_pchome_product_page_evidence_html(html, product_url="https://24h.pchome.com.tw/prod/PCH-2")

    assert parsed["policy"] == "read_only_pchome_product_page_evidence_parser"
    assert parsed["source"] == "html_fixture"
    assert parsed["image_url"] == "https://cdn.example.test/product.jpg"
    assert parsed["availability"] == "in_stock"
    assert parsed["jsonld_product_found"] is True
    assert parsed["jsonld_offer_found"] is True
    assert parsed["safety"]["fetches_external_sites"] is False
    assert parsed["safety"]["writes_database"] is False
    assert parsed["safety"]["llm_calls"] is False


def test_product_page_evidence_parser_uses_meta_fallbacks_and_skips_invalid_jsonld():
    html = """
    <html><head>
      <script type="application/ld+json">{not json}</script>
      <meta property="og:image" content="https://cdn.example.test/fallback.jpg">
      <meta property="product:availability" content="out of stock">
    </head></html>
    """

    parsed = parse_pchome_product_page_evidence_html(html)

    assert parsed["image_url"] == "https://cdn.example.test/fallback.jpg"
    assert parsed["availability"] == "out_of_stock"
    assert parsed["fallbacks_used"] == ["og:image", "product:availability"]
    assert parsed["parser_warnings"] == ["invalid_jsonld_skipped"]


def test_evidence_fetch_gate_defaults_to_planned_no_fetch_receipts():
    preview = build_pchome_evidence_fetch_gate(_payload(), batch_size=1)

    assert preview["policy"] == "controlled_read_only_pchome_product_page_evidence_fetch_gate"
    assert preview["result"] == "FETCH_GATE_PLANNED"
    assert preview["summary"]["candidate_count"] == 1
    assert preview["summary"]["executed_fetch_count"] == 0
    assert preview["fetch_config"]["execute_fetch"] is False
    assert preview["fetch_receipts"][0]["status"] == "PLANNED"
    assert preview["fetch_receipts"][0]["executed_fetch"] is False
    assert preview["fetch_receipts"][0]["writes_database"] is False
    assert preview["safety"]["read_only_fetch_gate"] is True
    assert preview["safety"]["writes_database"] is False


def test_evidence_fetch_gate_executes_fake_get_and_parses_receipt():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/pchome.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    calls = []

    def fake_get(url, timeout, headers):
        calls.append({"url": url, "timeout": timeout, "headers": headers})
        return FakeResponse()

    preview = build_pchome_evidence_fetch_gate(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        timeout_seconds=2,
        http_get=fake_get,
    )

    receipt = preview["fetch_receipts"][0]
    assert preview["result"] == "FETCH_GATE_EXECUTED_WITH_EVIDENCE"
    assert preview["summary"]["executed_fetch_count"] == 1
    assert preview["summary"]["parsed_image_count"] == 1
    assert preview["summary"]["parsed_availability_count"] == 1
    assert receipt["status"] == "FETCHED_WITH_EVIDENCE"
    assert receipt["executed_fetch"] is True
    assert receipt["parsed_evidence"]["image_url"] == "https://cdn.example.test/pchome.jpg"
    assert receipt["parsed_evidence"]["availability"] == "in_stock"
    assert receipt["writes_database"] is False
    assert calls[0]["url"] == "https://24h.pchome.com.tw/prod/PCH-2"
    assert calls[0]["timeout"] == 2


def test_evidence_fetch_gate_blocks_non_allowlisted_product_url():
    payload = _payload()
    payload["opportunities"][1]["product_url"] = "https://example.test/prod/PCH-2"

    preview = build_pchome_evidence_fetch_gate(payload, batch_size=1, execute_fetch=True)

    assert preview["result"] == "FETCH_GATE_EXECUTED_WITH_BLOCKERS"
    assert preview["summary"]["blocked_count"] == 1
    assert preview["fetch_receipts"][0]["status"] == "BLOCKED_BY_ALLOWLIST"
    assert preview["fetch_receipts"][0]["executed_fetch"] is False


def test_evidence_merge_preview_requires_fetch_before_merge_by_default():
    preview = build_pchome_evidence_merge_preview(_payload(), batch_size=1)

    assert preview["policy"] == "read_only_pchome_growth_evidence_merge_preview"
    assert preview["result"] == "FETCH_REQUIRED_FOR_MERGE_PREVIEW"
    assert preview["summary"]["executed_fetch_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert preview["summary"]["manual_review_required_count"] == 0
    assert preview["summary"]["manual_review_mode"] == "exception_only"
    assert preview["merge_items"][0]["merge_status"] == "FETCH_GATE_PLANNED"
    assert preview["merge_items"][0]["automation_decision"] == "AUTO_RUN_FETCH_GATE"
    assert preview["merge_items"][0]["manual_review_required"] is False
    assert preview["merge_items"][0]["writes_database"] is False
    assert preview["safety"]["writes_database"] is False
    assert preview["safety"]["updates_mapping"] is False
    assert preview["safety"]["requires_operator_review_before_write"] is False


def test_evidence_merge_preview_merges_fake_fetch_receipt_without_writing():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/merged.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_evidence_merge_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    item = preview["merge_items"][0]
    assert preview["result"] == "MERGE_PREVIEW_READY"
    assert preview["summary"]["merge_ready_count"] == 1
    assert preview["summary"]["auto_merge_ready_count"] == 1
    assert preview["summary"]["manual_review_required_count"] == 0
    assert item["merge_status"] == "MERGE_PREVIEW_READY"
    assert item["automation_decision"] == "AUTO_ACCEPT_EVIDENCE_MERGE"
    assert item["automation_allowed"] is True
    assert item["manual_review_required"] is False
    assert item["evidence_delta"] == {
        "image_url": "https://cdn.example.test/merged.jpg",
        "availability": "in_stock",
    }
    assert "image" in item["merged_present_fields"]
    assert "availability" in item["merged_present_fields"]
    assert "image" not in item["remaining_missing_fields"]
    assert "availability" not in item["remaining_missing_fields"]
    assert item["writes_database"] is False
    assert preview["safety"]["writes_database"] is False
    assert preview["safety"]["manual_review_mode"] == "exception_only"


def test_auto_policy_receipt_gate_builds_planned_receipts_without_persisting():
    gate = build_pchome_auto_policy_receipt_gate(_payload(), batch_size=1)

    receipt = gate["auto_policy_receipts"][0]
    assert gate["policy"] == "read_only_pchome_growth_auto_policy_receipt_gate"
    assert gate["result"] == "AUTO_POLICY_RECEIPTS_PLANNED"
    assert gate["summary"]["receipt_count"] == 2
    assert gate["summary"]["ready_for_auto_fetch_count"] == 1
    assert gate["summary"]["manual_review_required_count"] == 0
    assert gate["summary"]["writes_database_count"] == 0
    assert gate["summary"]["persists_receipt_count"] == 0
    assert receipt["receipt_id"].startswith("pchome-evidence-")
    assert receipt["receipt_status"] == "READY_FOR_AUTO_FETCH"
    assert receipt["automation_decision"] == "AUTO_RUN_FETCH_GATE"
    assert receipt["manual_review_required"] is False
    assert receipt["writes_database"] is False
    assert receipt["persists_receipt"] is False
    assert gate["persistence_gate"]["mode"] == "no_write_receipt_preview"
    assert gate["safety"]["writes_database"] is False
    assert gate["safety"]["persists_receipt"] is False


def test_auto_policy_receipt_gate_prepares_auto_persistence_receipt_after_fake_fetch():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/receipt.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    gate = build_pchome_auto_policy_receipt_gate(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    receipt = gate["auto_policy_receipts"][0]
    assert gate["result"] == "AUTO_POLICY_RECEIPTS_READY"
    assert gate["summary"]["ready_for_auto_persistence_count"] == 1
    assert gate["summary"]["receipt_status_counts"]["READY_FOR_AUTO_PERSISTENCE"] == 1
    assert receipt["receipt_status"] == "READY_FOR_AUTO_PERSISTENCE"
    assert receipt["automation_decision"] == "AUTO_ACCEPT_EVIDENCE_MERGE"
    assert receipt["evidence_delta"] == {
        "image_url": "https://cdn.example.test/receipt.jpg",
        "availability": "in_stock",
    }
    assert receipt["persists_receipt"] is False
    assert receipt["writes_database"] is False


def test_auto_policy_persistence_gate_builds_no_write_dry_run_contract_without_fetch():
    gate = build_pchome_auto_policy_persistence_gate(_payload(), batch_size=1)

    item = gate["persistence_items"][0]
    assert gate["policy"] == "read_only_pchome_growth_auto_policy_persistence_gate"
    assert gate["result"] == "PERSISTENCE_WAITING_FOR_RECEIPTS"
    assert gate["summary"]["persistence_item_count"] == 2
    assert gate["summary"]["dry_run_ready_count"] == 0
    assert gate["summary"]["waiting_for_receipt_count"] == 2
    assert gate["summary"]["writes_database_count"] == 0
    assert gate["summary"]["persists_receipt_count"] == 0
    assert gate["schema_contract"]["requires_schema_migration_before_apply"] is True
    assert gate["apply_gate"]["mode"] == "dry_run_only"
    assert item["persistence_status"] == "WAITING_FOR_READY_RECEIPT"
    assert item["planned_operation"] == "NOOP"
    assert item["writes_database"] is False
    assert item["persists_receipt"] is False
    assert gate["safety"]["writes_database"] is False
    assert gate["safety"]["persists_receipt"] is False


def test_auto_policy_persistence_gate_prepares_idempotent_transaction_preview_after_fake_fetch():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/persist.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    gate = build_pchome_auto_policy_persistence_gate(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    item = gate["persistence_items"][0]
    assert gate["result"] == "PERSISTENCE_DRY_RUN_READY"
    assert gate["summary"]["dry_run_ready_count"] == 1
    assert item["persistence_status"] == "DRY_RUN_READY"
    assert item["planned_operation"] == "UPSERT_EVIDENCE_RECEIPT_AND_PATCH_EXTERNAL_OFFER_EVIDENCE"
    assert item["idempotency_key"].startswith("pchome-evidence-")
    assert item["payload_hash"]
    assert item["transaction_preview"]["commit"] == "future_apply_gate_only"
    assert item["parameter_preview"]["image_url_present"] is True
    assert item["parameter_preview"]["availability"] == "in_stock"
    assert item["target_tables"] == ["external_offer_evidence_receipts", "external_offers"]
    assert item["writes_database"] is False
    assert item["persists_receipt"] is False
    assert gate["apply_gate"]["writes_database"] is False
    assert gate["safety"]["writes_database"] is False


def test_auto_policy_schema_migration_preview_stays_no_write_without_fetch():
    preview = build_pchome_auto_policy_schema_migration_preview(_payload(), batch_size=1)

    ddl_preview = "\n".join(preview["schema_migration_preview"]["ddl_preview"])
    assert preview["policy"] == "read_only_pchome_growth_auto_policy_schema_migration_preview"
    assert preview["result"] == "SCHEMA_MIGRATION_PREVIEW_READY"
    assert preview["future_apply_gate"]["status"] == "WAITING_FOR_DRY_RUN_READY_ITEMS"
    assert preview["summary"]["dry_run_ready_count"] == 0
    assert preview["summary"]["executes_migration_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert "CREATE TABLE IF NOT EXISTS external_offer_evidence_receipts" in ddl_preview
    assert "JSONB" in ddl_preview
    assert preview["schema_migration_preview"]["executes_sql"] is False
    assert preview["prewrite_snapshot_contract"]["executes_sql"] is False
    assert preview["future_apply_verifier"]["executes_in_preview"] is False
    assert preview["future_apply_gate"]["current_preview_apply_allowed"] is False
    assert preview["safety"]["executes_migration"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_schema_migration_preview_builds_future_apply_verifier_after_fake_fetch():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/schema.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_auto_policy_schema_migration_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    assert preview["future_apply_gate"]["status"] == "APPLY_CONTRACT_READY"
    assert preview["summary"]["dry_run_ready_count"] == 1
    assert preview["summary"]["future_verifier_count"] == 5
    assert preview["prewrite_snapshot_contract"]["target_receipt_ids"][0].startswith("pchome-evidence-")
    assert preview["prewrite_snapshot_contract"]["target_pchome_product_ids"] == ["PCH-2"]
    assert preview["future_apply_verifier"]["manual_review_mode"] == "exception_only"
    assert preview["future_apply_verifier"]["checks"][0]["routes_failure_to"] == "exception_review"
    assert preview["future_apply_gate"]["requires_prewrite_snapshot"] is True
    assert preview["future_apply_gate"]["requires_post_write_readback"] is True
    assert preview["future_apply_gate"]["writes_database"] is False
    assert preview["safety"]["persists_receipt"] is False


def test_auto_policy_migration_file_preview_stays_no_write_without_fetch():
    preview = build_pchome_auto_policy_migration_file_preview(_payload(), batch_size=1)

    migration = preview["migration_file_preview"]
    endpoint = preview["future_apply_endpoint_verifier"]
    forward_sql = "\n".join(migration["forward_sql_preview"])
    assert preview["policy"] == "read_only_pchome_growth_auto_policy_migration_file_preview"
    assert preview["result"] == "MIGRATION_FILE_PREVIEW_READY"
    assert preview["summary"]["apply_endpoint_contract_ready_count"] == 0
    assert preview["summary"]["writes_file_count"] == 0
    assert preview["summary"]["executes_endpoint_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert migration["migration_filename"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert migration["file_write_mode"] == "preview_only"
    assert migration["forbidden_forward_tokens_absent"] is True
    assert "Migration 045: PChome auto-policy evidence receipts" in forward_sql
    assert "CREATE TABLE IF NOT EXISTS external_offer_evidence_receipts" in forward_sql
    assert "GRANT ALL PRIVILEGES ON external_offer_evidence_receipts TO momo" in forward_sql
    assert migration["writes_file"] is False
    assert migration["executes_sql"] is False
    assert endpoint["contract_status"] == "WAITING_FOR_APPLY_INPUTS"
    assert endpoint["executes_endpoint"] is False
    assert endpoint["writes_database"] is False
    assert preview["safety"]["writes_file"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_migration_file_preview_builds_apply_endpoint_contract_after_fake_fetch():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/file.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_auto_policy_migration_file_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    endpoint = preview["future_apply_endpoint_verifier"]
    assert preview["summary"]["dry_run_ready_count"] == 1
    assert preview["summary"]["apply_endpoint_contract_ready_count"] == 1
    assert preview["migration_file_preview"]["forward_sql_hash"]
    assert endpoint["contract_status"] == "APPLY_ENDPOINT_CONTRACT_READY"
    assert endpoint["request_contract"]["receipt_count"] == 1
    assert endpoint["request_contract"]["product_count"] == 1
    assert endpoint["request_contract"]["expected_migration_filename"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert endpoint["request_contract"]["expected_migration_hash"] == (
        preview["migration_file_preview"]["forward_sql_hash"]
    )
    assert endpoint["rollback_contract"]["uses_prewrite_snapshot"] is True
    assert endpoint["post_write_verifier_contract"]["verifier_count"] == 5
    assert endpoint["manual_review_mode"] == "exception_only"
    assert endpoint["executes_endpoint"] is False
    assert endpoint["executes_sql"] is False


def test_auto_policy_apply_readiness_closeout_waits_for_ready_receipts_without_fetch():
    closeout = build_pchome_auto_policy_apply_readiness_closeout(_payload(), batch_size=1)

    waiting_keys = {check["key"] for check in closeout["closeout"]["waiting_checks"]}
    assert closeout["policy"] == "read_only_pchome_growth_auto_policy_apply_readiness_closeout"
    assert closeout["result"] == "APPLY_READINESS_WAITING_FOR_READY_RECEIPTS"
    assert closeout["summary"]["readiness_check_count"] == 9
    assert closeout["summary"]["current_preview_ready_count"] == 0
    assert closeout["summary"]["future_apply_blocker_count"] == 4
    assert "ready_receipts_present" in waiting_keys
    assert "future_apply_endpoint_contract_ready" in waiting_keys
    assert closeout["closeout"]["ready_for_migration_file_generation_request"] is False
    assert closeout["closeout"]["ready_for_database_apply"] is False
    assert closeout["summary"]["writes_file_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["safety"]["writes_file"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_apply_readiness_closeout_ready_after_fake_fetch_but_not_db_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_apply_readiness_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    assert closeout["result"] == "APPLY_READINESS_CLOSEOUT_READY"
    assert closeout["summary"]["readiness_pass_count"] == 9
    assert closeout["summary"]["readiness_waiting_count"] == 0
    assert closeout["summary"]["current_preview_ready_count"] == 1
    assert closeout["summary"]["future_apply_blocker_count"] == 4
    assert closeout["closeout"]["status"] == "READY_FOR_MIGRATION_FILE_GENERATION_REQUEST"
    assert closeout["closeout"]["ready_for_migration_file_generation_request"] is True
    assert closeout["closeout"]["ready_for_database_apply"] is False
    assert closeout["migration_file_preview_summary"]["migration_filename"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert closeout["future_apply_endpoint_summary"]["contract_status"] == "APPLY_ENDPOINT_CONTRACT_READY"
    assert closeout["future_apply_endpoint_summary"]["receipt_count"] == 1
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_migration_file_generation_request_waits_for_closeout_without_fetch():
    request_package = build_pchome_auto_policy_migration_file_generation_request(_payload(), batch_size=1)

    request = request_package["file_generation_request"]
    assert request_package["policy"] == "read_only_pchome_growth_auto_policy_migration_file_generation_request"
    assert request_package["result"] == "WAITING_FOR_APPLY_READINESS_CLOSEOUT"
    assert request_package["summary"]["request_ready_count"] == 0
    assert request_package["summary"]["required_artifact_count"] == 4
    assert request_package["summary"]["file_generation_step_count"] == 3
    assert request["ready_to_generate_file"] is False
    assert request["ready_for_database_apply"] is False
    assert request["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert request["writes_file_in_preview"] is False
    assert request_package["summary"]["writes_file_count"] == 0
    assert request_package["summary"]["executes_endpoint_count"] == 0
    assert request_package["summary"]["writes_database_count"] == 0
    assert request_package["safety"]["writes_file"] is False
    assert request_package["safety"]["writes_database"] is False


def test_auto_policy_migration_file_generation_request_ready_after_fake_fetch_without_writing_file():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/request.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    request_package = build_pchome_auto_policy_migration_file_generation_request(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    request = request_package["file_generation_request"]
    assert request_package["result"] == "FILE_GENERATION_REQUEST_READY"
    assert request_package["summary"]["request_ready_count"] == 1
    assert request["request_id"].startswith("pchome-migration-file-request-")
    assert request["ready_to_generate_file"] is True
    assert request["ready_for_database_apply"] is False
    assert request["expected_sha256"]
    assert request["expected_line_count"] == 31
    assert request["file_generation_steps"][0]["content_source"] == "migration_file_preview.forward_sql_preview"
    assert request_package["future_apply_endpoint_summary"]["contract_status"] == "APPLY_ENDPOINT_CONTRACT_READY"
    assert request_package["future_apply_blockers"][0]["key"] == "migration_file_not_written"
    assert request_package["safety"]["writes_file"] is False
    assert request_package["safety"]["executes_sql"] is False


def test_generated_auto_policy_migration_file_matches_generation_request_hash():
    request_package = build_pchome_auto_policy_migration_file_generation_request(_payload(), batch_size=1)
    request = request_package["file_generation_request"]
    migration_path = ROOT / request["target_file"]

    assert migration_path.exists()
    migration_text = migration_path.read_text(encoding="utf-8")
    assert request["expected_sha256"] == hashlib.sha256(migration_text.encode("utf-8")).hexdigest()
    assert migration_text.endswith("\n")
    assert request_package["safety"]["writes_database"] is False


def test_auto_policy_migration_apply_gate_preview_reads_generated_file_without_db_apply():
    preview = build_pchome_auto_policy_migration_apply_gate_preview(_payload(), batch_size=1)

    assert preview["policy"] == "read_only_pchome_growth_auto_policy_migration_apply_gate_preview"
    assert preview["result"] == "MIGRATION_APPLY_GATE_WAITING"
    assert preview["summary"]["generated_file_exists_count"] == 1
    assert preview["summary"]["generated_file_hash_matches_count"] == 1
    assert preview["apply_gate"]["ready_for_database_apply_now"] is False
    assert preview["generated_migration_file"]["exists"] is True
    assert preview["generated_migration_file"]["target_file"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert preview["generated_migration_file"]["sha256"] == preview["apply_gate"]["expected_sha256"]
    assert preview["safety"]["executes_migration"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_migration_apply_gate_preview_ready_after_fake_fetch_but_still_no_db_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/apply-gate.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_auto_policy_migration_apply_gate_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    assert preview["result"] == "MIGRATION_APPLY_GATE_PREVIEW_READY"
    assert preview["summary"]["apply_gate_pass_count"] == 9
    assert preview["summary"]["apply_gate_waiting_count"] == 0
    assert preview["summary"]["apply_preview_ready_count"] == 1
    assert preview["summary"]["future_apply_blocker_count"] == 3
    assert preview["apply_gate"]["status"] == "READY_FOR_EXPLICIT_DB_APPLY_REQUEST"
    assert preview["apply_gate"]["ready_for_explicit_db_apply_request"] is True
    assert preview["apply_gate"]["ready_for_database_apply_now"] is False
    assert preview["apply_gate"]["hash_matches"] is True
    assert preview["future_apply_endpoint_summary"]["contract_status"] == "APPLY_ENDPOINT_CONTRACT_READY"
    assert preview["future_apply_endpoint_summary"]["receipt_count"] == 1
    assert preview["safety"]["executes_sql"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_request_gate_preview_waits_without_ready_receipts():
    preview = build_pchome_auto_policy_db_apply_request_gate_preview(_payload(), batch_size=1)

    gate = preview["db_apply_request_gate"]
    assert preview["policy"] == "read_only_pchome_growth_auto_policy_db_apply_request_gate_preview"
    assert preview["result"] == "WAITING_FOR_MIGRATION_APPLY_GATE_PREVIEW"
    assert preview["summary"]["request_ready_count"] == 0
    assert preview["summary"]["required_artifact_count"] == 5
    assert preview["summary"]["apply_sequence_step_count"] == 5
    assert gate["ready_for_explicit_db_apply_request"] is False
    assert gate["ready_for_database_apply_now"] is False
    assert gate["command_preview"]["executes_in_preview"] is False
    assert gate["command_preview"]["reads_secret_in_preview"] is False
    assert gate["command_preview"]["writes_database"] is False
    assert preview["rollback_gate_preview"]["writes_database"] is False
    assert preview["safety"]["reads_secret_in_preview"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_request_gate_preview_ready_after_fake_fetch_but_still_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-request.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_auto_policy_db_apply_request_gate_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    gate = preview["db_apply_request_gate"]
    assert preview["result"] == "DB_APPLY_REQUEST_GATE_READY"
    assert preview["summary"]["request_ready_count"] == 1
    assert preview["summary"]["generated_file_hash_matches_count"] == 1
    assert gate["request_id"].startswith("pchome-db-apply-request-")
    assert gate["ready_for_explicit_db_apply_request"] is True
    assert gate["ready_for_database_apply_now"] is False
    assert gate["hash_matches"] is True
    assert gate["command_preview"]["command"].startswith('psql "$DATABASE_URL"')
    assert gate["command_preview"]["uses_secret_placeholder"] is True
    assert gate["apply_sequence_preview"][3]["name"] == "execute_migration"
    assert preview["required_runtime_readback"] == [
        "fresh production /health",
        "schema catalog readback for external_offer_evidence_receipts",
        "index catalog readback",
        "privilege readback",
        "mapping backlog read-only smoke",
    ]
    assert preview["safety"]["executes_migration"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_execution_preflight_waits_without_ready_request_gate():
    preflight = build_pchome_auto_policy_db_apply_execution_preflight(_payload(), batch_size=1)

    execution = preflight["execution_preflight"]
    assert preflight["policy"] == "read_only_pchome_growth_auto_policy_db_apply_execution_preflight"
    assert preflight["result"] == "WAITING_FOR_DB_APPLY_REQUEST_GATE"
    assert preflight["summary"]["preflight_ready_count"] == 0
    assert preflight["summary"]["request_ready_count"] == 0
    assert preflight["summary"]["required_artifact_count"] == 6
    assert preflight["summary"]["snapshot_plan_count"] == 5
    assert preflight["summary"]["readback_plan_count"] == 6
    assert preflight["summary"]["rollback_artifact_count"] == 1
    assert preflight["summary"]["abort_condition_count"] == 8
    assert preflight["summary"]["reads_secret_count"] == 0
    assert execution["ready_for_preflight_artifact_generation"] is False
    assert execution["ready_for_database_apply_now"] is False
    assert execution["reads_secret_in_preview"] is False
    assert preflight["prewrite_snapshot_plan"]["required"] is True
    assert preflight["prewrite_snapshot_plan"]["executes_sql_in_preview"] is False
    assert preflight["post_apply_readback_plan"]["readback_check_count"] == 6
    assert preflight["rollback_artifact_plan"]["uses_prewrite_snapshot"] is True
    assert preflight["rollback_artifact_plan"]["writes_database"] is False
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_execution_preflight_ready_after_fake_fetch_but_still_no_db_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-preflight.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_execution_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    execution = preflight["execution_preflight"]
    readback_keys = [check["key"] for check in preflight["post_apply_readback_plan"]["readback_checks"]]
    snapshot_keys = [step["key"] for step in preflight["prewrite_snapshot_plan"]["snapshot_steps"]]
    assert preflight["result"] == "DB_APPLY_EXECUTION_PREFLIGHT_READY"
    assert preflight["summary"]["preflight_ready_count"] == 1
    assert preflight["summary"]["request_ready_count"] == 1
    assert preflight["summary"]["generated_file_hash_matches_count"] == 1
    assert preflight["summary"]["executes_migration_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert execution["preflight_id"].startswith("pchome-db-apply-preflight-")
    assert execution["source_request_id"].startswith("pchome-db-apply-request-")
    assert execution["ready_for_preflight_artifact_generation"] is True
    assert execution["ready_for_database_apply_now"] is False
    assert execution["hash_matches"] is True
    assert execution["operator_secret_boundary"] == "future_shell_only"
    assert "schema_catalog_prewrite_snapshot" in snapshot_keys
    assert "receipt_table_exists" in readback_keys
    assert "mapping_backlog_read_only_smoke" in readback_keys
    assert preflight["rollback_artifact_plan"]["artifacts"][0]["rollback_sql_preview"] == [
        "DROP TABLE IF EXISTS external_offer_evidence_receipts;"
    ]
    assert preflight["rollback_artifact_plan"]["artifacts"][0]["executes_sql_in_preview"] is False
    assert preflight["safety"]["writes_artifact_in_preview"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_package_waits_without_ready_preflight():
    package = build_pchome_auto_policy_db_apply_authorization_package(_payload(), batch_size=1)

    authorization = package["authorization_package"]
    assert package["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_package"
    assert package["result"] == "WAITING_FOR_DB_APPLY_EXECUTION_PREFLIGHT"
    assert package["summary"]["authorization_check_count"] == 11
    assert package["summary"]["authorization_package_ready_count"] == 0
    assert package["summary"]["freshness_requirement_count"] == 5
    assert package["summary"]["manifest_step_count"] == 6
    assert package["summary"]["verifier_bundle_count"] == 3
    assert package["summary"]["reads_secret_count"] == 0
    assert package["summary"]["executes_sql_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert authorization["ready_for_explicit_apply_authorization_request"] is False
    assert authorization["ready_for_database_apply_now"] is False
    assert authorization["reads_secret_in_preview"] is False
    assert package["machine_apply_manifest"]["executes_in_preview"] is False
    assert package["machine_apply_manifest"]["writes_database"] is False
    assert package["verifier_bundle"]["executes_in_preview"] is False
    assert package["verifier_bundle"]["writes_database"] is False
    assert package["safety"]["executes_sql"] is False
    assert package["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_package_ready_after_fake_fetch_but_still_no_db_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    package = build_pchome_auto_policy_db_apply_authorization_package(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    authorization = package["authorization_package"]
    assert package["result"] == "DB_APPLY_AUTHORIZATION_PACKAGE_READY"
    assert package["summary"]["authorization_check_count"] == 11
    assert package["summary"]["authorization_pass_count"] == 11
    assert package["summary"]["authorization_waiting_count"] == 0
    assert package["summary"]["authorization_package_ready_count"] == 1
    assert package["summary"]["required_artifact_count"] == 6
    assert package["summary"]["snapshot_plan_count"] == 5
    assert package["summary"]["readback_plan_count"] == 6
    assert package["summary"]["rollback_artifact_count"] == 1
    assert package["summary"]["executes_migration_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert authorization["package_id"].startswith("pchome-db-apply-authorization-")
    assert authorization["source_preflight_id"].startswith("pchome-db-apply-preflight-")
    assert authorization["source_request_id"].startswith("pchome-db-apply-request-")
    assert authorization["ready_for_explicit_apply_authorization_request"] is True
    assert authorization["ready_for_database_apply_now"] is False
    assert authorization["freshness_window_seconds"] == 300
    assert authorization["operator_secret_boundary"] == "future_shell_only"
    assert authorization["reads_secret_in_preview"] is False
    assert authorization["executes_sql_in_preview"] is False
    assert authorization["writes_database_in_preview"] is False
    assert package["freshness_requirements"][0]["key"] == "production_truth_fresh_within_300_seconds"
    assert package["machine_apply_manifest"]["manifest_step_count"] == 6
    assert package["machine_apply_manifest"]["manifest_steps"][3]["executes_in_preview"] is False
    assert "receipt_table_exists" in package["verifier_bundle"]["post_apply_verifiers"]
    assert package["safety"]["reads_secret_in_preview"] is False
    assert package["safety"]["executes_sql"] is False
    assert package["safety"]["writes_database"] is False


def test_auto_policy_db_apply_verifier_artifact_preview_waits_without_ready_authorization_package():
    preview = build_pchome_auto_policy_db_apply_verifier_artifact_preview(_payload(), batch_size=1)

    artifact_preview = preview["artifact_preview"]
    assert preview["policy"] == "read_only_pchome_growth_auto_policy_db_apply_verifier_artifact_preview"
    assert preview["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_PACKAGE"
    assert preview["summary"]["artifact_preview_ready_count"] == 0
    assert preview["summary"]["artifact_schema_count"] == 3
    assert preview["summary"]["artifact_generation_step_count"] == 5
    assert preview["summary"]["verifier_check_count"] == 15
    assert preview["summary"]["writes_artifact_count"] == 0
    assert preview["summary"]["executes_sql_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert artifact_preview["ready_for_future_artifact_generation"] is False
    assert artifact_preview["ready_to_write_artifacts_now"] is False
    assert artifact_preview["ready_for_database_apply_now"] is False
    assert artifact_preview["writes_artifact_in_preview"] is False
    assert preview["artifact_generation_plan"]["writes_artifact_in_preview"] is False
    assert preview["verifier_manifest"]["executes_in_preview"] is False
    assert preview["verifier_manifest"]["writes_database"] is False
    assert preview["safety"]["writes_artifact_in_preview"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_verifier_artifact_preview_ready_after_fake_fetch_but_no_artifact_write():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-artifacts.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_auto_policy_db_apply_verifier_artifact_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    artifact_preview = preview["artifact_preview"]
    artifact_keys = [schema["key"] for schema in preview["artifact_schemas"]]
    assert preview["result"] == "DB_APPLY_VERIFIER_ARTIFACT_PREVIEW_READY"
    assert preview["summary"]["artifact_preview_ready_count"] == 1
    assert preview["summary"]["authorization_package_ready_count"] == 1
    assert preview["summary"]["artifact_schema_count"] == 3
    assert preview["summary"]["artifact_generation_step_count"] == 5
    assert preview["summary"]["verifier_check_count"] == 15
    assert preview["summary"]["writes_artifact_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert artifact_preview["preview_id"].startswith("pchome-db-apply-artifacts-")
    assert artifact_preview["source_authorization_package_id"].startswith("pchome-db-apply-authorization-")
    assert artifact_preview["ready_for_future_artifact_generation"] is True
    assert artifact_preview["ready_to_write_artifacts_now"] is False
    assert artifact_preview["ready_for_database_apply_now"] is False
    assert artifact_preview["writes_artifact_in_preview"] is False
    assert artifact_preview["executes_sql_in_preview"] is False
    assert "prewrite_snapshot_artifact" in artifact_keys
    assert "post_apply_readback_artifact" in artifact_keys
    assert "rollback_artifact" in artifact_keys
    assert preview["artifact_schemas"][2]["rollback_sql_preview"] == [
        "DROP TABLE IF EXISTS external_offer_evidence_receipts;"
    ]
    assert "receipt_table_exists" in preview["verifier_manifest"]["post_apply_checks"]
    assert preview["artifact_generation_plan"]["generation_step_count"] == 5
    assert preview["safety"]["writes_artifact_in_preview"] is False
    assert preview["safety"]["executes_sql"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_final_handoff_package_waits_without_ready_artifact_preview():
    package = build_pchome_auto_policy_db_apply_final_handoff_package(_payload(), batch_size=1)

    handoff = package["final_handoff_package"]
    assert package["policy"] == "read_only_pchome_growth_auto_policy_db_apply_final_handoff_package"
    assert package["result"] == "WAITING_FOR_DB_APPLY_VERIFIER_ARTIFACT_PREVIEW"
    assert package["summary"]["final_handoff_ready_count"] == 0
    assert package["summary"]["handoff_section_count"] == 6
    assert package["summary"]["final_runbook_step_count"] == 7
    assert package["summary"]["command_preview_count"] == 3
    assert package["summary"]["abort_gate_count"] == 10
    assert package["summary"]["source_endpoint_count"] == 4
    assert package["summary"]["writes_artifact_count"] == 0
    assert package["summary"]["executes_sql_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert handoff["ready_for_explicit_db_apply_handoff"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["reads_secret_in_preview"] is False
    assert handoff["writes_artifact_in_preview"] is False
    assert package["final_runbook_manifest"]["executes_in_preview"] is False
    assert package["final_runbook_manifest"]["writes_database"] is False
    assert package["command_previews"][1]["reads_secret_in_preview"] is False
    assert package["safety"]["executes_sql"] is False
    assert package["safety"]["writes_database"] is False


def test_auto_policy_db_apply_final_handoff_package_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-final-handoff.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    package = build_pchome_auto_policy_db_apply_final_handoff_package(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    handoff = package["final_handoff_package"]
    assert package["result"] == "DB_APPLY_FINAL_HANDOFF_PACKAGE_READY"
    assert package["summary"]["final_handoff_ready_count"] == 1
    assert package["summary"]["artifact_preview_ready_count"] == 1
    assert package["summary"]["handoff_section_count"] == 6
    assert package["summary"]["final_runbook_step_count"] == 7
    assert package["summary"]["command_preview_count"] == 3
    assert package["summary"]["abort_gate_count"] == 10
    assert package["summary"]["source_endpoint_count"] == 4
    assert package["summary"]["artifact_schema_count"] == 3
    assert package["summary"]["verifier_check_count"] == 15
    assert package["summary"]["writes_artifact_count"] == 0
    assert package["summary"]["executes_sql_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert handoff["package_id"].startswith("pchome-db-apply-final-handoff-")
    assert handoff["source_artifact_preview_id"].startswith("pchome-db-apply-artifacts-")
    assert handoff["source_authorization_package_id"].startswith("pchome-db-apply-authorization-")
    assert handoff["ready_for_explicit_db_apply_handoff"] is True
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["requires_separate_explicit_db_apply_authorization"] is True
    assert handoff["operator_secret_boundary"] == "future_shell_only"
    assert handoff["reads_secret_in_preview"] is False
    assert handoff["executes_sql_in_preview"] is False
    assert handoff["writes_database_in_preview"] is False
    assert package["source_proof_manifest"]["source_endpoint_chain"][-1].endswith(
        "auto-policy-db-apply-verifier-artifact-preview"
    )
    assert package["command_previews"][1]["command"].startswith('psql "$DATABASE_URL"')
    assert package["command_previews"][1]["executes_in_preview"] is False
    assert package["final_runbook_manifest"]["step_count"] == 7
    assert package["safety"]["reads_secret_in_preview"] is False
    assert package["safety"]["executes_sql"] is False
    assert package["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_shell_preview_waits_without_ready_final_handoff():
    preview = build_pchome_auto_policy_db_apply_controlled_dry_run_shell_preview(_payload(), batch_size=1)

    shell = preview["controlled_dry_run_shell_preview"]
    assert preview["policy"] == "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_shell_preview"
    assert preview["result"] == "WAITING_FOR_DB_APPLY_FINAL_HANDOFF_PACKAGE"
    assert preview["summary"]["dry_run_shell_preview_ready_count"] == 0
    assert preview["summary"]["shell_phase_count"] == 9
    assert preview["summary"]["shell_script_line_count"] == 10
    assert preview["summary"]["check_mode_required_check_count"] == 6
    assert preview["summary"]["rollback_hook_count"] == 3
    assert preview["summary"]["writes_script_count"] == 0
    assert preview["summary"]["executes_script_count"] == 0
    assert preview["summary"]["executes_sql_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert shell["ready_for_future_shell_script_generation"] is False
    assert shell["ready_to_write_script_now"] is False
    assert shell["ready_to_execute_shell_now"] is False
    assert shell["ready_for_database_apply_now"] is False
    assert shell["reads_secret_in_preview"] is False
    assert preview["shell_script_preview"]["writes_file_in_preview"] is False
    assert preview["shell_script_preview"]["executes_script_in_preview"] is False
    assert preview["check_mode_contract"]["dry_run_only"] is True
    assert preview["rollback_hook_preview"]["writes_database"] is False
    assert preview["safety"]["executes_script"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_shell_preview_ready_after_fake_fetch_but_no_shell_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-dry-run-shell.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preview = build_pchome_auto_policy_db_apply_controlled_dry_run_shell_preview(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    shell = preview["controlled_dry_run_shell_preview"]
    phase_names = [phase["name"] for phase in preview["shell_phases"]]
    assert preview["result"] == "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_PREVIEW_READY"
    assert preview["summary"]["dry_run_shell_preview_ready_count"] == 1
    assert preview["summary"]["final_handoff_ready_count"] == 1
    assert preview["summary"]["shell_phase_count"] == 9
    assert preview["summary"]["shell_script_line_count"] == 10
    assert preview["summary"]["check_mode_required_check_count"] == 6
    assert preview["summary"]["rollback_hook_count"] == 3
    assert preview["summary"]["writes_script_count"] == 0
    assert preview["summary"]["executes_script_count"] == 0
    assert preview["summary"]["writes_database_count"] == 0
    assert shell["preview_id"].startswith("pchome-db-apply-dry-run-shell-")
    assert shell["source_final_handoff_package_id"].startswith("pchome-db-apply-final-handoff-")
    assert shell["ready_for_future_shell_script_generation"] is True
    assert shell["ready_to_write_script_now"] is False
    assert shell["ready_to_execute_shell_now"] is False
    assert shell["ready_for_database_apply_now"] is False
    assert shell["dry_run_only"] is True
    assert shell["reads_secret_in_preview"] is False
    assert shell["executes_sql_in_preview"] is False
    assert shell["writes_database_in_preview"] is False
    assert "render_database_apply_command_preview" in phase_names
    assert preview["shell_script_preview"]["line_count"] == 10
    assert preview["shell_script_preview"]["executes_script_in_preview"] is False
    assert any('psql "$DATABASE_URL"' in line for line in preview["shell_script_preview"]["lines"])
    assert preview["check_mode_contract"]["required_check_count"] == 6
    assert preview["rollback_hook_preview"]["hook_count"] == 3
    assert preview["safety"]["writes_script_in_preview"] is False
    assert preview["safety"]["executes_script"] is False
    assert preview["safety"]["executes_sql"] is False
    assert preview["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_shell_closeout_waits_without_ready_preview():
    closeout = build_pchome_auto_policy_db_apply_controlled_dry_run_shell_closeout(_payload(), batch_size=1)

    boundary = closeout["explicit_authorization_boundary"]
    assert closeout["policy"] == "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_shell_closeout"
    assert closeout["result"] == "WAITING_FOR_CONTROLLED_DRY_RUN_SHELL_PREVIEW"
    assert closeout["summary"]["closeout_ready_count"] == 0
    assert closeout["summary"]["closeout_check_count"] == 13
    assert closeout["summary"]["closeout_waiting_count"] > 0
    assert closeout["summary"]["future_apply_boundary_count"] == 6
    assert closeout["summary"]["writes_script_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert boundary["ready_for_explicit_apply_authorization_boundary"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["requires_new_explicit_db_apply_authorization"] is True
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert closeout["controlled_dry_run_shell_closeout"]["ready_for_database_apply_now"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_shell_closeout_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-dry-run-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_controlled_dry_run_shell_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    boundary = closeout["explicit_authorization_boundary"]
    check_keys = [check["key"] for check in closeout["closeout_checks"]]
    future_boundary_keys = [item["key"] for item in closeout["future_apply_boundaries"]]
    assert closeout["result"] == "DB_APPLY_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT_READY"
    assert closeout["summary"]["closeout_ready_count"] == 1
    assert closeout["summary"]["closeout_check_count"] == 13
    assert closeout["summary"]["closeout_pass_count"] == 13
    assert closeout["summary"]["closeout_waiting_count"] == 0
    assert closeout["summary"]["dry_run_shell_preview_ready_count"] == 1
    assert closeout["summary"]["future_apply_boundary_count"] == 6
    assert closeout["summary"]["writes_script_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert boundary["boundary_id"].startswith("pchome-db-apply-dry-run-closeout-")
    assert boundary["source_dry_run_shell_preview_id"].startswith("pchome-db-apply-dry-run-shell-")
    assert boundary["ready_for_explicit_apply_authorization_boundary"] is True
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["requires_new_explicit_db_apply_authorization"] is True
    assert boundary["operator_secret_boundary"] == "future_shell_only"
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert "preview_executes_no_shell" in check_keys
    assert "database_url_from_future_shell_only" in future_boundary_keys
    assert closeout["controlled_dry_run_shell_closeout"]["waiting_checks"] == []
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_request_intake_waits_without_ready_closeout():
    intake = build_pchome_auto_policy_db_apply_authorization_request_intake(_payload(), batch_size=1)

    request_intake = intake["authorization_request_intake"]
    envelope = intake["authorization_envelope"]
    assert intake["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_request_intake"
    assert intake["result"] == "WAITING_FOR_CONTROLLED_DRY_RUN_SHELL_CLOSEOUT"
    assert intake["summary"]["authorization_request_intake_ready_count"] == 0
    assert intake["summary"]["required_request_evidence_count"] == 7
    assert intake["summary"]["request_payload_required_field_count"] == 10
    assert intake["summary"]["authorization_acceptance_gate_count"] == 11
    assert intake["summary"]["rejection_reason_count"] == 10
    assert intake["summary"]["writes_script_count"] == 0
    assert intake["summary"]["reads_secret_count"] == 0
    assert intake["summary"]["executes_script_count"] == 0
    assert intake["summary"]["executes_sql_count"] == 0
    assert intake["summary"]["writes_database_count"] == 0
    assert request_intake["ready_for_authorization_request_intake"] is False
    assert request_intake["ready_for_database_apply_now"] is False
    assert request_intake["requires_new_explicit_db_apply_authorization"] is True
    assert request_intake["reads_secret_in_preview"] is False
    assert request_intake["executes_shell_in_preview"] is False
    assert request_intake["executes_sql_in_preview"] is False
    assert envelope["accepts_authorization_request"] is False
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert "operator_acknowledges_secret_boundary" in intake["request_payload_schema"]["required_fields"]
    assert intake["request_payload_schema"]["accepts_database_url"] is False
    assert intake["safety"]["executes_script"] is False
    assert intake["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_request_intake_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-intake.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    intake = build_pchome_auto_policy_db_apply_authorization_request_intake(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    request_intake = intake["authorization_request_intake"]
    envelope = intake["authorization_envelope"]
    evidence_keys = [item["key"] for item in intake["required_request_evidence"]]
    gate_keys = [item["key"] for item in intake["authorization_acceptance_gates"]]
    assert intake["result"] == "DB_APPLY_AUTHORIZATION_REQUEST_INTAKE_READY"
    assert intake["summary"]["authorization_request_intake_ready_count"] == 1
    assert intake["summary"]["required_request_evidence_count"] == 7
    assert intake["summary"]["request_payload_required_field_count"] == 10
    assert intake["summary"]["authorization_acceptance_gate_count"] == 11
    assert intake["summary"]["authorization_acceptance_pass_count"] == 11
    assert intake["summary"]["authorization_acceptance_waiting_count"] == 0
    assert intake["summary"]["rejection_reason_count"] == 10
    assert intake["summary"]["closeout_ready_count"] == 1
    assert intake["summary"]["future_apply_boundary_count"] == 6
    assert intake["summary"]["writes_script_count"] == 0
    assert intake["summary"]["reads_secret_count"] == 0
    assert intake["summary"]["executes_script_count"] == 0
    assert intake["summary"]["executes_sql_count"] == 0
    assert intake["summary"]["writes_database_count"] == 0
    assert request_intake["intake_id"].startswith("pchome-db-apply-authorization-intake-")
    assert request_intake["source_closeout_boundary_id"].startswith("pchome-db-apply-dry-run-closeout-")
    assert request_intake["source_dry_run_shell_preview_id"].startswith("pchome-db-apply-dry-run-shell-")
    assert request_intake["ready_for_authorization_request_intake"] is True
    assert request_intake["ready_for_database_apply_now"] is False
    assert request_intake["request_scope"] == "future_explicit_db_apply_authorization_only"
    assert request_intake["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert request_intake["hash_matches"] is True
    assert request_intake["operator_secret_boundary"] == "future_shell_only"
    assert request_intake["reads_secret_in_preview"] is False
    assert request_intake["executes_shell_in_preview"] is False
    assert request_intake["executes_sql_in_preview"] is False
    assert request_intake["writes_database_in_preview"] is False
    assert envelope["accepts_authorization_request"] is True
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["rejects_direct_database_apply"] is True
    assert "migration_file_hash" in evidence_keys
    assert "preview_has_no_side_effects" in gate_keys
    assert "direct_database_apply_requested_from_intake" in intake["rejection_reasons"]
    assert intake["request_payload_schema"]["accepts_database_url"] is False
    assert intake["request_payload_schema"]["accepts_authorization_header"] is False
    assert intake["safety"]["reads_secret_in_preview"] is False
    assert intake["safety"]["executes_script"] is False
    assert intake["safety"]["executes_sql"] is False
    assert intake["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_request_closeout_waits_without_ready_intake():
    closeout = build_pchome_auto_policy_db_apply_authorization_request_closeout(_payload(), batch_size=1)

    package = closeout["final_exact_request_package"]
    assert closeout["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_request_closeout"
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_REQUEST_INTAKE"
    assert closeout["summary"]["authorization_request_closeout_ready_count"] == 0
    assert closeout["summary"]["closeout_check_count"] == 12
    assert closeout["summary"]["closeout_waiting_count"] > 0
    assert closeout["summary"]["exact_request_payload_field_count"] == 10
    assert closeout["summary"]["machine_request_manifest_step_count"] == 6
    assert closeout["summary"]["required_request_evidence_count"] == 7
    assert closeout["summary"]["authorization_acceptance_gate_count"] == 11
    assert closeout["summary"]["rejection_reason_count"] == 10
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert package["ready_for_exact_authorization_request_package"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert closeout["machine_request_manifest"]["issues_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_request_closeout_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_request_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    package = closeout["final_exact_request_package"]
    manifest = closeout["machine_request_manifest"]
    check_keys = [check["key"] for check in closeout["closeout_checks"]]
    template = package["exact_request_payload_template"]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_request_closeout_ready_count"] == 1
    assert closeout["summary"]["closeout_check_count"] == 12
    assert closeout["summary"]["closeout_pass_count"] == 12
    assert closeout["summary"]["closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_request_intake_ready_count"] == 1
    assert closeout["summary"]["exact_request_payload_field_count"] == 10
    assert closeout["summary"]["machine_request_manifest_step_count"] == 6
    assert closeout["summary"]["required_request_evidence_count"] == 7
    assert closeout["summary"]["authorization_acceptance_gate_count"] == 11
    assert closeout["summary"]["rejection_reason_count"] == 10
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert package["package_id"].startswith("pchome-db-apply-authorization-closeout-")
    assert package["source_intake_id"].startswith("pchome-db-apply-authorization-intake-")
    assert package["ready_for_exact_authorization_request_package"] is True
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["request_scope"] == "future_explicit_db_apply_authorization_only"
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["payload_template_field_count"] == 10
    assert template["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert template["operator_acknowledges_secret_boundary"] is True
    assert template["fresh_production_truth"]["same_run_only"] is True
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert manifest["manifest_step_count"] == 6
    assert manifest["issues_database_apply_authorization"] is False
    assert manifest["writes_database"] is False
    assert "direct_apply_rejected" in check_keys
    assert "preview_has_no_shell_sql_or_db_side_effect" in check_keys
    assert closeout["authorization_request_closeout"]["waiting_checks"] == []
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_lane_guard_waits_without_ready_closeout():
    guard = build_pchome_auto_policy_db_apply_authorization_lane_guard(_payload(), batch_size=1)

    lane = guard["future_authorization_lane_guard"]
    contract = guard["lane_transfer_contract"]
    assert guard["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_lane_guard"
    assert guard["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_REQUEST_CLOSEOUT"
    assert guard["summary"]["authorization_lane_guard_ready_count"] == 0
    assert guard["summary"]["lane_guard_check_count"] == 12
    assert guard["summary"]["lane_guard_waiting_count"] > 0
    assert guard["summary"]["lane_entry_requirement_count"] == 6
    assert guard["summary"]["exact_request_payload_field_count"] == 10
    assert guard["summary"]["machine_request_manifest_step_count"] == 6
    assert guard["summary"]["reads_secret_count"] == 0
    assert guard["summary"]["executes_script_count"] == 0
    assert guard["summary"]["executes_sql_count"] == 0
    assert guard["summary"]["writes_database_count"] == 0
    assert lane["ready_for_future_authorization_lane_entry"] is False
    assert lane["ready_for_database_apply_now"] is False
    assert lane["issues_database_apply_authorization"] is False
    assert lane["reads_secret_in_preview"] is False
    assert lane["executes_shell_in_preview"] is False
    assert lane["executes_sql_in_preview"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert guard["safety"]["executes_sql"] is False
    assert guard["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_lane_guard_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-lane.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    guard = build_pchome_auto_policy_db_apply_authorization_lane_guard(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    lane = guard["future_authorization_lane_guard"]
    contract = guard["lane_transfer_contract"]
    check_keys = [check["key"] for check in guard["lane_guard_checks"]]
    requirement_keys = [item["key"] for item in guard["lane_entry_requirements"]]
    assert guard["result"] == "DB_APPLY_AUTHORIZATION_LANE_GUARD_READY"
    assert guard["summary"]["authorization_lane_guard_ready_count"] == 1
    assert guard["summary"]["lane_guard_check_count"] == 12
    assert guard["summary"]["lane_guard_pass_count"] == 12
    assert guard["summary"]["lane_guard_waiting_count"] == 0
    assert guard["summary"]["authorization_request_closeout_ready_count"] == 1
    assert guard["summary"]["exact_request_payload_field_count"] == 10
    assert guard["summary"]["machine_request_manifest_step_count"] == 6
    assert guard["summary"]["lane_entry_requirement_count"] == 6
    assert guard["summary"]["required_request_evidence_count"] == 7
    assert guard["summary"]["authorization_acceptance_gate_count"] == 11
    assert guard["summary"]["rejection_reason_count"] == 10
    assert guard["summary"]["reads_secret_count"] == 0
    assert guard["summary"]["executes_script_count"] == 0
    assert guard["summary"]["executes_sql_count"] == 0
    assert guard["summary"]["writes_database_count"] == 0
    assert lane["guard_id"].startswith("pchome-db-apply-authorization-lane-")
    assert lane["source_closeout_package_id"].startswith("pchome-db-apply-authorization-closeout-")
    assert lane["ready_for_future_authorization_lane_entry"] is True
    assert lane["ready_for_database_apply_now"] is False
    assert lane["issues_database_apply_authorization"] is False
    assert lane["request_scope"] == "future_explicit_db_apply_authorization_only"
    assert lane["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert lane["hash_matches"] is True
    assert lane["requires_fresh_production_truth_in_same_run"] is True
    assert lane["operator_secret_boundary"] == "future_shell_only"
    assert lane["reads_secret_in_preview"] is False
    assert lane["executes_shell_in_preview"] is False
    assert lane["executes_sql_in_preview"] is False
    assert lane["writes_database_in_preview"] is False
    assert contract["machine_verifiable"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "fresh_production_truth_same_run_required" in check_keys
    assert "secret_rejection_step_present" in check_keys
    assert "rollback_acknowledgement_present" in check_keys
    assert "production_truth_refreshed_in_same_run" in requirement_keys
    assert "direct_apply_rejected_until_next_lane" in requirement_keys
    assert guard["safety"]["reads_secret_in_preview"] is False
    assert guard["safety"]["executes_script"] is False
    assert guard["safety"]["executes_sql"] is False
    assert guard["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_decision_preflight_waits_without_ready_lane_guard():
    preflight = build_pchome_auto_policy_db_apply_authorization_decision_preflight(_payload(), batch_size=1)

    decision = preflight["future_authorization_decision_preflight"]
    envelope = preflight["decision_preflight_envelope"]
    assert preflight["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_preflight"
    assert preflight["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_LANE_GUARD"
    assert preflight["summary"]["authorization_decision_preflight_ready_count"] == 0
    assert preflight["summary"]["decision_preflight_check_count"] == 12
    assert preflight["summary"]["decision_preflight_waiting_count"] > 0
    assert preflight["summary"]["decision_input_requirement_count"] == 8
    assert preflight["summary"]["decision_rejection_reason_count"] == 10
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert decision["ready_for_future_authorization_decision"] is False
    assert decision["can_enter_authorization_decision_lane"] is False
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert decision["reads_secret_in_preview"] is False
    assert decision["executes_shell_in_preview"] is False
    assert decision["executes_sql_in_preview"] is False
    assert envelope["allows_authorization_decision_in_future_lane"] is False
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["requires_post_apply_verifier"] is True
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_decision_preflight_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-decision.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_authorization_decision_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    decision = preflight["future_authorization_decision_preflight"]
    envelope = preflight["decision_preflight_envelope"]
    check_keys = [check["key"] for check in preflight["decision_preflight_checks"]]
    input_keys = [item["key"] for item in preflight["decision_input_requirements"]]
    assert preflight["result"] == "DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT_READY"
    assert preflight["summary"]["authorization_decision_preflight_ready_count"] == 1
    assert preflight["summary"]["decision_preflight_check_count"] == 12
    assert preflight["summary"]["decision_preflight_pass_count"] == 12
    assert preflight["summary"]["decision_preflight_waiting_count"] == 0
    assert preflight["summary"]["authorization_lane_guard_ready_count"] == 1
    assert preflight["summary"]["decision_input_requirement_count"] == 8
    assert preflight["summary"]["decision_rejection_reason_count"] == 10
    assert preflight["summary"]["lane_entry_requirement_count"] == 6
    assert preflight["summary"]["exact_request_payload_field_count"] == 10
    assert preflight["summary"]["machine_request_manifest_step_count"] == 6
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert decision["preflight_id"].startswith("pchome-db-apply-authorization-decision-")
    assert decision["source_lane_guard_id"].startswith("pchome-db-apply-authorization-lane-")
    assert decision["ready_for_future_authorization_decision"] is True
    assert decision["can_enter_authorization_decision_lane"] is True
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert decision["request_scope"] == "future_explicit_db_apply_authorization_only"
    assert decision["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert decision["hash_matches"] is True
    assert decision["requires_fresh_production_truth_in_same_run"] is True
    assert decision["operator_secret_boundary"] == "future_shell_only"
    assert decision["reads_secret_in_preview"] is False
    assert decision["executes_shell_in_preview"] is False
    assert decision["executes_sql_in_preview"] is False
    assert decision["writes_database_in_preview"] is False
    assert envelope["allows_authorization_decision_in_future_lane"] is True
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["rejects_direct_database_apply"] is True
    assert envelope["requires_post_apply_verifier"] is True
    assert "same_run_production_truth_required" in check_keys
    assert "secret_boundary_rejects_secret_material" in check_keys
    assert "post_apply_verifier_reference" in input_keys
    assert "direct_database_apply_requested_from_decision_preflight" in preflight["decision_rejection_policy"]
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["executes_script"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_decision_closeout_waits_without_ready_preflight():
    closeout = build_pchome_auto_policy_db_apply_authorization_decision_closeout(
        _payload(),
        batch_size=1,
    )

    decision = closeout["future_authorization_decision_closeout"]
    package = closeout["future_authorization_decision_package"]
    contract = closeout["decision_closeout_contract"]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_closeout"
    )
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_DECISION_PREFLIGHT"
    assert closeout["summary"]["authorization_decision_closeout_ready_count"] == 0
    assert closeout["summary"]["decision_closeout_check_count"] == 12
    assert closeout["summary"]["decision_closeout_waiting_count"] > 0
    assert closeout["summary"]["authorization_decision_preflight_ready_count"] == 0
    assert closeout["summary"]["decision_input_requirement_count"] == 8
    assert closeout["summary"]["decision_rejection_reason_count"] == 10
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert decision["ready_for_future_authorization_decision_closeout"] is False
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert package["ready_for_future_authorization_decision_package"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["requires_post_apply_verifier"] is True
    assert package["reads_secret_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert contract["permits_future_authorization_decision_lane"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_decision_closeout_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-decision-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_decision_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    decision = closeout["future_authorization_decision_closeout"]
    package = closeout["future_authorization_decision_package"]
    contract = closeout["decision_closeout_contract"]
    check_keys = [check["key"] for check in closeout["decision_closeout_checks"]]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_decision_closeout_ready_count"] == 1
    assert closeout["summary"]["decision_closeout_check_count"] == 12
    assert closeout["summary"]["decision_closeout_pass_count"] == 12
    assert closeout["summary"]["decision_closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_decision_preflight_ready_count"] == 1
    assert closeout["summary"]["decision_input_requirement_count"] == 8
    assert closeout["summary"]["decision_rejection_reason_count"] == 10
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert decision["closeout_id"].startswith("pchome-db-apply-authorization-decision-closeout-")
    assert decision["source_preflight_id"].startswith("pchome-db-apply-authorization-decision-")
    assert decision["source_lane_guard_id"].startswith("pchome-db-apply-authorization-lane-")
    assert decision["source_closeout_package_id"].startswith("pchome-db-apply-authorization-closeout-")
    assert decision["ready_for_future_authorization_decision_closeout"] is True
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert package["package_id"].startswith("pchome-db-apply-authorization-decision-closeout-")
    assert package["ready_for_future_authorization_decision_package"] is True
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["requires_fresh_production_truth_in_same_run"] is True
    assert package["requires_post_apply_verifier"] is True
    assert package["operator_secret_boundary"] == "future_shell_only"
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert contract["permits_future_authorization_decision_lane"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "post_apply_verifier_required" in check_keys
    assert "direct_apply_still_rejected" in check_keys
    assert "manual_review_regression_absent" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_issuer_gate_waits_without_ready_closeout():
    gate = build_pchome_auto_policy_db_apply_authorization_issuer_gate(
        _payload(),
        batch_size=1,
    )

    issuer = gate["future_authorization_issuer_gate"]
    envelope = gate["final_nonsecret_authorization_envelope"]
    contract = gate["issuer_gate_contract"]
    assert gate["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_issuer_gate"
    assert gate["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_DECISION_CLOSEOUT"
    assert gate["summary"]["authorization_issuer_gate_ready_count"] == 0
    assert gate["summary"]["issuer_gate_check_count"] == 12
    assert gate["summary"]["issuer_gate_waiting_count"] > 0
    assert gate["summary"]["authorization_decision_closeout_ready_count"] == 0
    assert gate["summary"]["decision_closeout_check_count"] == 12
    assert gate["summary"]["required_issuer_evidence_count"] == 9
    assert gate["summary"]["nonsecret_authorization_claim_count"] == 8
    assert gate["summary"]["post_apply_verifier_required_count"] == 1
    assert gate["summary"]["same_run_truth_required_count"] == 1
    assert gate["summary"]["reads_secret_count"] == 0
    assert gate["summary"]["executes_script_count"] == 0
    assert gate["summary"]["executes_sql_count"] == 0
    assert gate["summary"]["writes_database_count"] == 0
    assert issuer["ready_for_future_authorization_issuer_lane"] is False
    assert issuer["ready_for_database_apply_now"] is False
    assert issuer["issues_database_apply_authorization"] is False
    assert issuer["signs_database_apply_authorization"] is False
    assert envelope["authorization_material_type"] == "nonsecret_request_envelope"
    assert envelope["ready_for_future_authorization_issuer_lane"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["signs_database_apply_authorization"] is False
    assert envelope["secret_material_included"] is False
    assert envelope["reads_secret_in_preview"] is False
    assert envelope["writes_database_in_preview"] is False
    assert contract["permits_future_authorization_issuer_lane"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert gate["safety"]["executes_sql"] is False
    assert gate["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_issuer_gate_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-issuer-gate.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    gate = build_pchome_auto_policy_db_apply_authorization_issuer_gate(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    issuer = gate["future_authorization_issuer_gate"]
    envelope = gate["final_nonsecret_authorization_envelope"]
    contract = gate["issuer_gate_contract"]
    check_keys = [check["key"] for check in gate["issuer_gate_checks"]]
    evidence_keys = [item["key"] for item in envelope["required_issuer_evidence"]]
    claim_keys = [item["key"] for item in envelope["nonsecret_authorization_claims"]]
    assert gate["result"] == "DB_APPLY_AUTHORIZATION_ISSUER_GATE_READY"
    assert gate["summary"]["authorization_issuer_gate_ready_count"] == 1
    assert gate["summary"]["issuer_gate_check_count"] == 12
    assert gate["summary"]["issuer_gate_pass_count"] == 12
    assert gate["summary"]["issuer_gate_waiting_count"] == 0
    assert gate["summary"]["authorization_decision_closeout_ready_count"] == 1
    assert gate["summary"]["decision_closeout_check_count"] == 12
    assert gate["summary"]["required_issuer_evidence_count"] == 9
    assert gate["summary"]["nonsecret_authorization_claim_count"] == 8
    assert gate["summary"]["post_apply_verifier_required_count"] == 1
    assert gate["summary"]["same_run_truth_required_count"] == 1
    assert gate["summary"]["decision_rejection_reason_count"] == 10
    assert gate["summary"]["reads_secret_count"] == 0
    assert gate["summary"]["executes_script_count"] == 0
    assert gate["summary"]["executes_sql_count"] == 0
    assert gate["summary"]["writes_database_count"] == 0
    assert issuer["gate_id"].startswith("pchome-db-apply-authorization-issuer-gate-")
    assert issuer["source_decision_closeout_id"].startswith(
        "pchome-db-apply-authorization-decision-closeout-"
    )
    assert issuer["source_decision_preflight_id"].startswith("pchome-db-apply-authorization-decision-")
    assert issuer["source_lane_guard_id"].startswith("pchome-db-apply-authorization-lane-")
    assert issuer["ready_for_future_authorization_issuer_lane"] is True
    assert issuer["ready_for_database_apply_now"] is False
    assert issuer["issues_database_apply_authorization"] is False
    assert issuer["signs_database_apply_authorization"] is False
    assert envelope["envelope_id"].startswith("pchome-db-apply-authorization-issuer-gate-")
    assert envelope["authorization_material_type"] == "nonsecret_request_envelope"
    assert envelope["decision_scope"] == "future_explicit_db_apply_authorization_issuer_lane_only"
    assert envelope["ready_for_future_authorization_issuer_lane"] is True
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["signs_database_apply_authorization"] is False
    assert envelope["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert envelope["hash_matches"] is True
    assert envelope["requires_fresh_production_truth_in_same_run"] is True
    assert envelope["requires_post_apply_verifier"] is True
    assert envelope["operator_secret_boundary"] == "future_shell_only"
    assert envelope["secret_material_included"] is False
    assert envelope["reads_secret_in_preview"] is False
    assert envelope["executes_shell_in_preview"] is False
    assert envelope["executes_sql_in_preview"] is False
    assert envelope["writes_database_in_preview"] is False
    assert contract["permits_future_authorization_issuer_lane"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "issuer_policy_requires_future_explicit_authorization" in check_keys
    assert "direct_apply_still_rejected" in check_keys
    assert "secret_boundary_rejection" in evidence_keys
    assert "no_database_apply_authorization_issued" in claim_keys
    assert gate["safety"]["reads_secret_in_preview"] is False
    assert gate["safety"]["executes_script"] is False
    assert gate["safety"]["executes_sql"] is False
    assert gate["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_decision_preflight_waits_without_ready_issuer_gate():
    preflight = build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight(
        _payload(),
        batch_size=1,
    )

    decision = preflight["future_authorization_signing_decision_preflight"]
    envelope = preflight["signing_decision_preflight_envelope"]
    assert preflight["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_decision_preflight"
    )
    assert preflight["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_ISSUER_GATE"
    assert preflight["summary"]["authorization_signing_decision_preflight_ready_count"] == 0
    assert preflight["summary"]["signing_decision_preflight_check_count"] == 12
    assert preflight["summary"]["signing_decision_preflight_waiting_count"] > 0
    assert preflight["summary"]["authorization_issuer_gate_ready_count"] == 0
    assert preflight["summary"]["issuer_gate_check_count"] == 12
    assert preflight["summary"]["required_issuer_evidence_count"] == 9
    assert preflight["summary"]["nonsecret_authorization_claim_count"] == 8
    assert preflight["summary"]["signing_decision_input_requirement_count"] == 10
    assert preflight["summary"]["signing_decision_rejection_reason_count"] == 11
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert decision["ready_for_future_signing_decision_preflight"] is False
    assert decision["can_enter_authorization_signing_decision_lane"] is False
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert decision["signs_database_apply_authorization"] is False
    assert envelope["allows_future_authorization_signing_decision_lane"] is False
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["signs_database_apply_authorization"] is False
    assert envelope["secret_material_required_in_preview"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_decision_preflight_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signing-preflight.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_authorization_signing_decision_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    decision = preflight["future_authorization_signing_decision_preflight"]
    envelope = preflight["signing_decision_preflight_envelope"]
    source_envelope = preflight["source_nonsecret_authorization_envelope"]
    check_keys = [check["key"] for check in preflight["signing_decision_preflight_checks"]]
    input_keys = [item["key"] for item in preflight["signing_decision_input_requirements"]]
    assert preflight["result"] == "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT_READY"
    assert preflight["summary"]["authorization_signing_decision_preflight_ready_count"] == 1
    assert preflight["summary"]["signing_decision_preflight_check_count"] == 12
    assert preflight["summary"]["signing_decision_preflight_pass_count"] == 12
    assert preflight["summary"]["signing_decision_preflight_waiting_count"] == 0
    assert preflight["summary"]["authorization_issuer_gate_ready_count"] == 1
    assert preflight["summary"]["issuer_gate_check_count"] == 12
    assert preflight["summary"]["required_issuer_evidence_count"] == 9
    assert preflight["summary"]["nonsecret_authorization_claim_count"] == 8
    assert preflight["summary"]["signing_decision_input_requirement_count"] == 10
    assert preflight["summary"]["signing_decision_rejection_reason_count"] == 11
    assert preflight["summary"]["post_apply_verifier_required_count"] == 1
    assert preflight["summary"]["same_run_truth_required_count"] == 1
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert decision["preflight_id"].startswith("pchome-db-apply-authorization-signing-preflight-")
    assert decision["source_issuer_gate_id"].startswith("pchome-db-apply-authorization-issuer-gate-")
    assert decision["source_decision_closeout_id"].startswith(
        "pchome-db-apply-authorization-decision-closeout-"
    )
    assert decision["ready_for_future_signing_decision_preflight"] is True
    assert decision["can_enter_authorization_signing_decision_lane"] is True
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert decision["signs_database_apply_authorization"] is False
    assert envelope["allows_future_authorization_signing_decision_lane"] is True
    assert envelope["issues_database_apply_authorization"] is False
    assert envelope["ready_for_database_apply_now"] is False
    assert envelope["signs_database_apply_authorization"] is False
    assert envelope["rejects_direct_database_apply"] is True
    assert envelope["requires_post_apply_verifier"] is True
    assert envelope["secret_material_required_in_preview"] is False
    assert source_envelope["authorization_material_type"] == "nonsecret_request_envelope"
    assert source_envelope["secret_material_included"] is False
    assert source_envelope["signs_database_apply_authorization"] is False
    assert "nonsecret_envelope_complete" in check_keys
    assert "signing_and_direct_apply_still_rejected" in check_keys
    assert "no_signing_without_future_explicit_authorization" in input_keys
    assert "authorization_signing_requested_from_preflight" in preflight["signing_decision_rejection_policy"]
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_script"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_decision_closeout_waits_without_ready_preflight():
    closeout = build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout(
        _payload(),
        batch_size=1,
    )

    decision = closeout["future_authorization_signing_decision_closeout"]
    package = closeout["unsigned_signing_decision_package"]
    contract = closeout["signing_decision_closeout_contract"]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_decision_closeout"
    )
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_PREFLIGHT"
    assert closeout["summary"]["authorization_signing_decision_closeout_ready_count"] == 0
    assert closeout["summary"]["signing_decision_closeout_check_count"] == 12
    assert closeout["summary"]["signing_decision_closeout_waiting_count"] > 0
    assert closeout["summary"]["authorization_signing_decision_preflight_ready_count"] == 0
    assert closeout["summary"]["signing_decision_preflight_check_count"] == 12
    assert closeout["summary"]["signing_decision_input_requirement_count"] == 10
    assert closeout["summary"]["signing_decision_rejection_reason_count"] == 11
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert decision["ready_for_future_signing_decision_closeout"] is False
    assert decision["can_enter_unsigned_signing_decision_package_lane"] is False
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert decision["signs_database_apply_authorization"] is False
    assert package["authorization_material_type"] == "unsigned_signing_decision_package"
    assert package["ready_for_future_unsigned_signing_decision_package"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["secret_material_included"] is False
    assert package["secret_material_required_in_preview"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert contract["permits_future_unsigned_signing_decision_package_lane"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_decision_closeout_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signing-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_signing_decision_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    decision = closeout["future_authorization_signing_decision_closeout"]
    package = closeout["unsigned_signing_decision_package"]
    contract = closeout["signing_decision_closeout_contract"]
    check_keys = [check["key"] for check in closeout["signing_decision_closeout_checks"]]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_signing_decision_closeout_ready_count"] == 1
    assert closeout["summary"]["signing_decision_closeout_check_count"] == 12
    assert closeout["summary"]["signing_decision_closeout_pass_count"] == 12
    assert closeout["summary"]["signing_decision_closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_signing_decision_preflight_ready_count"] == 1
    assert closeout["summary"]["signing_decision_preflight_check_count"] == 12
    assert closeout["summary"]["signing_decision_input_requirement_count"] == 10
    assert closeout["summary"]["signing_decision_rejection_reason_count"] == 11
    assert closeout["summary"]["required_issuer_evidence_count"] == 9
    assert closeout["summary"]["nonsecret_authorization_claim_count"] == 8
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert decision["closeout_id"].startswith("pchome-db-apply-authorization-signing-closeout-")
    assert decision["source_signing_decision_preflight_id"].startswith(
        "pchome-db-apply-authorization-signing-preflight-"
    )
    assert decision["source_issuer_gate_id"].startswith("pchome-db-apply-authorization-issuer-gate-")
    assert decision["ready_for_future_signing_decision_closeout"] is True
    assert decision["can_enter_unsigned_signing_decision_package_lane"] is True
    assert decision["ready_for_database_apply_now"] is False
    assert decision["issues_database_apply_authorization"] is False
    assert decision["signs_database_apply_authorization"] is False
    assert package["package_id"].startswith("pchome-db-apply-authorization-signing-closeout-")
    assert package["authorization_material_type"] == "unsigned_signing_decision_package"
    assert package["ready_for_future_unsigned_signing_decision_package"] is True
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["requires_fresh_production_truth_in_same_run"] is True
    assert package["requires_post_apply_verifier"] is True
    assert package["operator_secret_boundary"] == "future_shell_only"
    assert package["secret_material_included"] is False
    assert package["secret_material_required_in_preview"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert contract["permits_future_unsigned_signing_decision_package_lane"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "unsigned_package_source_envelope_complete" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert "manual_review_regression_absent" in check_keys
    assert "authorization_signing_requested_from_preflight" in package[
        "signing_decision_rejection_policy"
    ]
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_issuer_guard_waits_without_ready_closeout():
    guard = build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard(
        _payload(),
        batch_size=1,
    )

    issuer_guard = guard["future_authorization_signing_issuer_guard"]
    boundary = guard["signable_request_boundary"]
    contract = guard["signing_issuer_guard_contract"]
    assert guard["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_issuer_guard"
    )
    assert guard["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_DECISION_CLOSEOUT"
    assert guard["summary"]["authorization_signing_issuer_guard_ready_count"] == 0
    assert guard["summary"]["signing_issuer_guard_check_count"] == 12
    assert guard["summary"]["signing_issuer_guard_waiting_count"] > 0
    assert guard["summary"]["authorization_signing_decision_closeout_ready_count"] == 0
    assert guard["summary"]["signing_decision_closeout_check_count"] == 12
    assert guard["summary"]["signing_decision_input_requirement_count"] == 10
    assert guard["summary"]["signing_decision_rejection_reason_count"] == 11
    assert guard["summary"]["signs_database_apply_authorization_count"] == 0
    assert guard["summary"]["reads_secret_count"] == 0
    assert guard["summary"]["executes_script_count"] == 0
    assert guard["summary"]["executes_sql_count"] == 0
    assert guard["summary"]["writes_database_count"] == 0
    assert issuer_guard["ready_for_future_signing_issuer_guard"] is False
    assert issuer_guard["can_enter_future_authorization_signing_issuer_lane"] is False
    assert issuer_guard["ready_for_database_apply_now"] is False
    assert issuer_guard["issues_database_apply_authorization"] is False
    assert issuer_guard["signs_database_apply_authorization"] is False
    assert boundary["request_boundary_type"] == "future_signable_request_boundary"
    assert boundary["ready_for_future_signable_request_boundary"] is False
    assert boundary["can_enter_future_authorization_signing_issuer_lane"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["issues_database_apply_authorization"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert contract["permits_future_authorization_signing_issuer_lane"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert guard["safety"]["signs_database_apply_authorization"] is False
    assert guard["safety"]["executes_sql"] is False
    assert guard["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_issuer_guard_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signing-issuer.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    guard = build_pchome_auto_policy_db_apply_authorization_signing_issuer_guard(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    issuer_guard = guard["future_authorization_signing_issuer_guard"]
    boundary = guard["signable_request_boundary"]
    contract = guard["signing_issuer_guard_contract"]
    check_keys = [check["key"] for check in guard["signing_issuer_guard_checks"]]
    assert guard["result"] == "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD_READY"
    assert guard["summary"]["authorization_signing_issuer_guard_ready_count"] == 1
    assert guard["summary"]["signing_issuer_guard_check_count"] == 12
    assert guard["summary"]["signing_issuer_guard_pass_count"] == 12
    assert guard["summary"]["signing_issuer_guard_waiting_count"] == 0
    assert guard["summary"]["authorization_signing_decision_closeout_ready_count"] == 1
    assert guard["summary"]["signing_decision_closeout_check_count"] == 12
    assert guard["summary"]["signing_decision_input_requirement_count"] == 10
    assert guard["summary"]["signing_decision_rejection_reason_count"] == 11
    assert guard["summary"]["required_issuer_evidence_count"] == 9
    assert guard["summary"]["nonsecret_authorization_claim_count"] == 8
    assert guard["summary"]["post_apply_verifier_required_count"] == 1
    assert guard["summary"]["same_run_truth_required_count"] == 1
    assert guard["summary"]["signs_database_apply_authorization_count"] == 0
    assert guard["summary"]["reads_secret_count"] == 0
    assert guard["summary"]["executes_script_count"] == 0
    assert guard["summary"]["executes_sql_count"] == 0
    assert guard["summary"]["writes_database_count"] == 0
    assert issuer_guard["guard_id"].startswith("pchome-db-apply-authorization-signing-issuer-")
    assert issuer_guard["source_signing_decision_closeout_id"].startswith(
        "pchome-db-apply-authorization-signing-closeout-"
    )
    assert issuer_guard["source_signing_decision_preflight_id"].startswith(
        "pchome-db-apply-authorization-signing-preflight-"
    )
    assert issuer_guard["ready_for_future_signing_issuer_guard"] is True
    assert issuer_guard["can_enter_future_authorization_signing_issuer_lane"] is True
    assert issuer_guard["ready_for_database_apply_now"] is False
    assert issuer_guard["issues_database_apply_authorization"] is False
    assert issuer_guard["signs_database_apply_authorization"] is False
    assert boundary["boundary_id"].startswith("pchome-db-apply-authorization-signing-issuer-")
    assert boundary["request_boundary_type"] == "future_signable_request_boundary"
    assert boundary["ready_for_future_signable_request_boundary"] is True
    assert boundary["can_enter_future_authorization_signing_issuer_lane"] is True
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["issues_database_apply_authorization"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert boundary["hash_matches"] is True
    assert boundary["requires_fresh_production_truth_in_same_run"] is True
    assert boundary["requires_post_apply_verifier"] is True
    assert boundary["operator_secret_boundary"] == "future_shell_only"
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert contract["permits_future_authorization_signing_issuer_lane"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "signable_boundary_is_future_only" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert guard["safety"]["reads_secret_in_preview"] is False
    assert guard["safety"]["signs_database_apply_authorization"] is False
    assert guard["safety"]["executes_script"] is False
    assert guard["safety"]["executes_sql"] is False
    assert guard["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_issuer_closeout_waits_without_ready_guard():
    closeout = build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout(
        _payload(),
        batch_size=1,
    )

    issuer_closeout = closeout["future_authorization_signing_issuer_closeout"]
    final_package = closeout["final_signable_request_package"]
    contract = closeout["signing_issuer_closeout_contract"]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_issuer_closeout"
    )
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_GUARD"
    assert closeout["summary"]["authorization_signing_issuer_closeout_ready_count"] == 0
    assert closeout["summary"]["signing_issuer_closeout_check_count"] == 12
    assert closeout["summary"]["signing_issuer_closeout_waiting_count"] > 0
    assert closeout["summary"]["authorization_signing_issuer_guard_ready_count"] == 0
    assert closeout["summary"]["signing_issuer_guard_check_count"] == 12
    assert closeout["summary"]["signing_decision_input_requirement_count"] == 10
    assert closeout["summary"]["signing_decision_rejection_reason_count"] == 11
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert issuer_closeout["ready_for_future_signing_issuer_closeout"] is False
    assert issuer_closeout["can_enter_future_final_signable_request_package_lane"] is False
    assert issuer_closeout["ready_for_database_apply_now"] is False
    assert issuer_closeout["issues_database_apply_authorization"] is False
    assert issuer_closeout["signs_database_apply_authorization"] is False
    assert final_package["authorization_material_type"] == "final_signable_request_package"
    assert final_package["ready_for_future_final_signable_request_package"] is False
    assert final_package["ready_for_database_apply_now"] is False
    assert final_package["issues_database_apply_authorization"] is False
    assert final_package["signs_database_apply_authorization"] is False
    assert final_package["secret_material_included"] is False
    assert final_package["secret_material_required_in_preview"] is False
    assert final_package["reads_secret_in_preview"] is False
    assert contract["permits_future_final_signable_request_package_lane"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_issuer_closeout_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signing-issuer-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_signing_issuer_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    issuer_closeout = closeout["future_authorization_signing_issuer_closeout"]
    final_package = closeout["final_signable_request_package"]
    contract = closeout["signing_issuer_closeout_contract"]
    check_keys = [check["key"] for check in closeout["signing_issuer_closeout_checks"]]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_signing_issuer_closeout_ready_count"] == 1
    assert closeout["summary"]["signing_issuer_closeout_check_count"] == 12
    assert closeout["summary"]["signing_issuer_closeout_pass_count"] == 12
    assert closeout["summary"]["signing_issuer_closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_signing_issuer_guard_ready_count"] == 1
    assert closeout["summary"]["signing_issuer_guard_check_count"] == 12
    assert closeout["summary"]["signing_decision_input_requirement_count"] == 10
    assert closeout["summary"]["signing_decision_rejection_reason_count"] == 11
    assert closeout["summary"]["required_issuer_evidence_count"] == 9
    assert closeout["summary"]["nonsecret_authorization_claim_count"] == 8
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert issuer_closeout["closeout_id"].startswith(
        "pchome-db-apply-authorization-signing-issuer-closeout-"
    )
    assert issuer_closeout["source_signing_issuer_guard_id"].startswith(
        "pchome-db-apply-authorization-signing-issuer-"
    )
    assert issuer_closeout["ready_for_future_signing_issuer_closeout"] is True
    assert issuer_closeout["can_enter_future_final_signable_request_package_lane"] is True
    assert issuer_closeout["ready_for_database_apply_now"] is False
    assert issuer_closeout["issues_database_apply_authorization"] is False
    assert issuer_closeout["signs_database_apply_authorization"] is False
    assert final_package["package_id"].startswith(
        "pchome-db-apply-authorization-signing-issuer-closeout-"
    )
    assert final_package["authorization_material_type"] == "final_signable_request_package"
    assert final_package["ready_for_future_final_signable_request_package"] is True
    assert final_package["ready_for_database_apply_now"] is False
    assert final_package["issues_database_apply_authorization"] is False
    assert final_package["signs_database_apply_authorization"] is False
    assert final_package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert final_package["hash_matches"] is True
    assert final_package["requires_fresh_production_truth_in_same_run"] is True
    assert final_package["requires_post_apply_verifier"] is True
    assert final_package["operator_secret_boundary"] == "future_shell_only"
    assert final_package["secret_material_included"] is False
    assert final_package["secret_material_required_in_preview"] is False
    assert final_package["reads_secret_in_preview"] is False
    assert final_package["executes_shell_in_preview"] is False
    assert final_package["executes_sql_in_preview"] is False
    assert final_package["writes_database_in_preview"] is False
    assert contract["permits_future_final_signable_request_package_lane"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "final_package_does_not_authorize_sign_or_apply" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_execution_preflight_waits_without_ready_closeout():
    preflight = build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight(
        _payload(),
        batch_size=1,
    )

    future_preflight = preflight["future_authorization_signing_execution_preflight"]
    package = preflight["signing_execution_preflight_package"]
    boundary = preflight["operator_held_secret_boundary_contract"]
    contract = preflight["signing_execution_preflight_contract"]
    assert preflight["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_execution_preflight"
    )
    assert preflight["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_ISSUER_CLOSEOUT"
    assert preflight["summary"]["authorization_signing_execution_preflight_ready_count"] == 0
    assert preflight["summary"]["signing_execution_preflight_check_count"] == 12
    assert preflight["summary"]["signing_execution_preflight_waiting_count"] > 0
    assert preflight["summary"]["authorization_signing_issuer_closeout_ready_count"] == 0
    assert preflight["summary"]["signing_issuer_closeout_check_count"] == 12
    assert preflight["summary"]["final_signable_request_package_ready_count"] == 0
    assert preflight["summary"]["operator_held_secret_boundary_count"] == 1
    assert preflight["summary"]["signing_execution_input_requirement_count"] == 10
    assert preflight["summary"]["signing_execution_abort_condition_count"] == 8
    assert preflight["summary"]["rollback_boundary_count"] == 4
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert future_preflight["ready_for_future_signing_execution_preflight"] is False
    assert future_preflight["can_enter_future_authorization_signing_execution_lane"] is False
    assert future_preflight["ready_for_database_apply_now"] is False
    assert future_preflight["issues_database_apply_authorization"] is False
    assert future_preflight["signs_database_apply_authorization"] is False
    assert future_preflight["secret_material_included"] is False
    assert future_preflight["secret_material_required_in_preview"] is False
    assert future_preflight["reads_secret_in_preview"] is False
    assert package["authorization_material_type"] == "signing_execution_preflight_package"
    assert package["required_nonsecret_input_count"] == 10
    assert package["ready_for_database_apply_now"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["secret_material_included"] is False
    assert package["secret_material_required_in_preview"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert boundary["secret_reference_mode"] == "external_runtime_reference_only"
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["accepts_plaintext_secret"] is False
    assert boundary["permits_secret_value_logging"] is False
    assert contract["permits_future_explicit_authorization_signing_execution_lane"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_execution_preflight_ready_after_fake_fetch_but_no_signing():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signing-execution-preflight.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_authorization_signing_execution_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_preflight = preflight["future_authorization_signing_execution_preflight"]
    package = preflight["signing_execution_preflight_package"]
    boundary = preflight["operator_held_secret_boundary_contract"]
    contract = preflight["signing_execution_preflight_contract"]
    check_keys = [check["key"] for check in preflight["signing_execution_preflight_checks"]]
    assert preflight["result"] == "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT_READY"
    assert preflight["summary"]["authorization_signing_execution_preflight_ready_count"] == 1
    assert preflight["summary"]["signing_execution_preflight_check_count"] == 12
    assert preflight["summary"]["signing_execution_preflight_pass_count"] == 12
    assert preflight["summary"]["signing_execution_preflight_waiting_count"] == 0
    assert preflight["summary"]["authorization_signing_issuer_closeout_ready_count"] == 1
    assert preflight["summary"]["signing_issuer_closeout_check_count"] == 12
    assert preflight["summary"]["final_signable_request_package_ready_count"] == 1
    assert preflight["summary"]["operator_held_secret_boundary_count"] == 1
    assert preflight["summary"]["signing_execution_input_requirement_count"] == 10
    assert preflight["summary"]["signing_execution_abort_condition_count"] == 8
    assert preflight["summary"]["rollback_boundary_count"] == 4
    assert preflight["summary"]["post_apply_verifier_required_count"] == 1
    assert preflight["summary"]["same_run_truth_required_count"] == 1
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert future_preflight["preflight_id"].startswith(
        "pchome-db-apply-authorization-signing-execution-preflight-"
    )
    assert future_preflight["source_final_signable_request_package_id"].startswith(
        "pchome-db-apply-authorization-signing-issuer-closeout-"
    )
    assert future_preflight["ready_for_future_signing_execution_preflight"] is True
    assert future_preflight["can_enter_future_authorization_signing_execution_lane"] is True
    assert future_preflight["ready_for_database_apply_now"] is False
    assert future_preflight["issues_database_apply_authorization"] is False
    assert future_preflight["signs_database_apply_authorization"] is False
    assert package["package_id"].startswith(
        "pchome-db-apply-authorization-signing-execution-preflight-"
    )
    assert package["authorization_material_type"] == "signing_execution_preflight_package"
    assert package["ready_for_future_signing_execution_preflight"] is True
    assert package["required_nonsecret_input_count"] == 10
    assert all(item["secret"] is False for item in package["required_nonsecret_inputs"])
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["requires_fresh_production_truth_in_same_run"] is True
    assert package["requires_post_apply_verifier"] is True
    assert package["secret_material_included"] is False
    assert package["secret_material_required_in_preview"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["command_preview"]["redacts_secret_values"] is True
    assert package["command_preview"]["executes_in_preview"] is False
    assert package["command_preview"]["signs_database_apply_authorization"] is False
    assert boundary["secret_reference_mode"] == "external_runtime_reference_only"
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["accepts_plaintext_secret"] is False
    assert boundary["permits_secret_value_logging"] is False
    assert contract["permits_future_explicit_authorization_signing_execution_lane"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "operator_held_secret_boundary_is_externalized" in check_keys
    assert "future_command_preview_is_non_executing_and_redacted" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_script"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_execution_closeout_waits_without_ready_preflight():
    closeout = build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout(
        _payload(),
        batch_size=1,
    )

    future_closeout = closeout["future_authorization_signing_execution_closeout"]
    boundary = closeout["unsigned_signed_authorization_receipt_boundary"]
    contract = closeout["signing_execution_closeout_contract"]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_execution_closeout"
    )
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_PREFLIGHT"
    assert closeout["summary"]["authorization_signing_execution_closeout_ready_count"] == 0
    assert closeout["summary"]["signing_execution_closeout_check_count"] == 12
    assert closeout["summary"]["signing_execution_closeout_waiting_count"] > 0
    assert closeout["summary"]["authorization_signing_execution_preflight_ready_count"] == 0
    assert closeout["summary"]["signing_execution_preflight_check_count"] == 12
    assert closeout["summary"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert closeout["summary"]["operator_held_secret_boundary_count"] == 1
    assert closeout["summary"]["signing_execution_input_requirement_count"] == 10
    assert closeout["summary"]["signing_execution_abort_condition_count"] == 8
    assert closeout["summary"]["rollback_boundary_count"] == 4
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future_closeout["ready_for_future_signing_execution_closeout"] is False
    assert (
        future_closeout["can_enter_future_unsigned_signed_authorization_receipt_boundary"]
        is False
    )
    assert future_closeout["ready_for_database_apply_now"] is False
    assert future_closeout["issues_database_apply_authorization"] is False
    assert future_closeout["signs_database_apply_authorization"] is False
    assert future_closeout["secret_material_included"] is False
    assert future_closeout["secret_material_required_in_preview"] is False
    assert future_closeout["reads_secret_in_preview"] is False
    assert boundary["authorization_material_type"] == (
        "unsigned_signed_authorization_receipt_boundary"
    )
    assert boundary["ready_for_future_unsigned_signed_authorization_receipt_boundary"] is False
    assert boundary["ready_for_future_signed_authorization_receipt_lane"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["issues_database_apply_authorization"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert contract["permits_future_unsigned_signed_authorization_receipt_boundary"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_execution_closeout_ready_after_fake_fetch_but_no_signing():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signing-execution-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_signing_execution_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_closeout = closeout["future_authorization_signing_execution_closeout"]
    boundary = closeout["unsigned_signed_authorization_receipt_boundary"]
    contract = closeout["signing_execution_closeout_contract"]
    check_keys = [check["key"] for check in closeout["signing_execution_closeout_checks"]]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_signing_execution_closeout_ready_count"] == 1
    assert closeout["summary"]["signing_execution_closeout_check_count"] == 12
    assert closeout["summary"]["signing_execution_closeout_pass_count"] == 12
    assert closeout["summary"]["signing_execution_closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_signing_execution_preflight_ready_count"] == 1
    assert closeout["summary"]["signing_execution_preflight_check_count"] == 12
    assert closeout["summary"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert closeout["summary"]["operator_held_secret_boundary_count"] == 1
    assert closeout["summary"]["signing_execution_input_requirement_count"] == 10
    assert closeout["summary"]["signing_execution_abort_condition_count"] == 8
    assert closeout["summary"]["rollback_boundary_count"] == 4
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future_closeout["closeout_id"].startswith(
        "pchome-db-apply-authorization-signing-execution-closeout-"
    )
    assert future_closeout["source_signing_execution_preflight_id"].startswith(
        "pchome-db-apply-authorization-signing-execution-preflight-"
    )
    assert future_closeout["source_final_signable_request_package_id"].startswith(
        "pchome-db-apply-authorization-signing-issuer-closeout-"
    )
    assert future_closeout["ready_for_future_signing_execution_closeout"] is True
    assert (
        future_closeout["can_enter_future_unsigned_signed_authorization_receipt_boundary"]
        is True
    )
    assert future_closeout["ready_for_database_apply_now"] is False
    assert future_closeout["issues_database_apply_authorization"] is False
    assert future_closeout["signs_database_apply_authorization"] is False
    assert boundary["boundary_id"].startswith(
        "pchome-db-apply-authorization-signing-execution-closeout-"
    )
    assert boundary["authorization_material_type"] == (
        "unsigned_signed_authorization_receipt_boundary"
    )
    assert boundary["ready_for_future_unsigned_signed_authorization_receipt_boundary"] is True
    assert boundary["ready_for_future_signed_authorization_receipt_lane"] is True
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["issues_database_apply_authorization"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["operator_held_secret_boundary_contract"]["secret_reference_mode"] == (
        "external_runtime_reference_only"
    )
    assert boundary["command_preview"]["redacts_secret_values"] is True
    assert boundary["command_preview"]["executes_in_preview"] is False
    assert boundary["command_preview"]["signs_database_apply_authorization"] is False
    assert boundary["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert boundary["hash_matches"] is True
    assert boundary["requires_fresh_production_truth_in_same_run"] is True
    assert boundary["requires_post_apply_verifier"] is True
    assert contract["permits_future_unsigned_signed_authorization_receipt_boundary"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "operator_held_secret_boundary_carried_forward" in check_keys
    assert "closeout_does_not_authorize_sign_or_apply" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_preflight_waits_without_ready_closeout():
    preflight = build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight(
        _payload(),
        batch_size=1,
    )

    future_preflight = preflight["future_authorization_signed_receipt_preflight"]
    boundary = preflight["external_signing_receipt_evidence_boundary"]
    contract = preflight["signed_receipt_preflight_contract"]
    assert preflight["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_preflight"
    )
    assert preflight["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNING_EXECUTION_CLOSEOUT"
    assert preflight["summary"]["authorization_signed_receipt_preflight_ready_count"] == 0
    assert preflight["summary"]["signed_receipt_preflight_check_count"] == 12
    assert preflight["summary"]["signed_receipt_preflight_waiting_count"] > 0
    assert preflight["summary"]["authorization_signing_execution_closeout_ready_count"] == 0
    assert preflight["summary"]["signing_execution_closeout_check_count"] == 12
    assert preflight["summary"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert preflight["summary"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert preflight["summary"]["required_external_receipt_evidence_count"] == 10
    assert preflight["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert preflight["summary"]["operator_held_secret_boundary_count"] == 1
    assert preflight["summary"]["signing_execution_input_requirement_count"] == 10
    assert preflight["summary"]["signing_execution_abort_condition_count"] == 8
    assert preflight["summary"]["rollback_boundary_count"] == 4
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert future_preflight["ready_for_future_signed_authorization_receipt_preflight"] is False
    assert (
        future_preflight["can_enter_future_external_signing_receipt_evidence_boundary"]
        is False
    )
    assert future_preflight["ready_for_database_apply_now"] is False
    assert future_preflight["issues_database_apply_authorization"] is False
    assert future_preflight["signs_database_apply_authorization"] is False
    assert future_preflight["signed_authorization_receipt_included"] is False
    assert future_preflight["signature_material_included"] is False
    assert future_preflight["secret_material_included"] is False
    assert future_preflight["reads_secret_in_preview"] is False
    assert boundary["authorization_material_type"] == "external_signing_receipt_evidence_boundary"
    assert boundary["ready_for_future_external_signing_receipt_evidence_boundary"] is False
    assert boundary["ready_for_future_signed_authorization_receipt_lane"] is False
    assert boundary["required_external_receipt_evidence_count"] == 10
    assert boundary["external_receipt_acceptance_gate_count"] == 8
    assert boundary["external_signed_authorization_receipt_required_in_future"] is True
    assert boundary["external_signed_authorization_receipt_included"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert contract["permits_future_external_signing_receipt_evidence_boundary"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_preflight_ready_after_fake_fetch_but_no_signed_receipt():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signed-receipt-preflight.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_authorization_signed_receipt_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_preflight = preflight["future_authorization_signed_receipt_preflight"]
    boundary = preflight["external_signing_receipt_evidence_boundary"]
    contract = preflight["signed_receipt_preflight_contract"]
    check_keys = [check["key"] for check in preflight["signed_receipt_preflight_checks"]]
    assert preflight["result"] == "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT_READY"
    assert preflight["summary"]["authorization_signed_receipt_preflight_ready_count"] == 1
    assert preflight["summary"]["signed_receipt_preflight_check_count"] == 12
    assert preflight["summary"]["signed_receipt_preflight_pass_count"] == 12
    assert preflight["summary"]["signed_receipt_preflight_waiting_count"] == 0
    assert preflight["summary"]["authorization_signing_execution_closeout_ready_count"] == 1
    assert preflight["summary"]["signing_execution_closeout_check_count"] == 12
    assert preflight["summary"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert preflight["summary"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert preflight["summary"]["required_external_receipt_evidence_count"] == 10
    assert preflight["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert preflight["summary"]["operator_held_secret_boundary_count"] == 1
    assert preflight["summary"]["signing_execution_input_requirement_count"] == 10
    assert preflight["summary"]["signing_execution_abort_condition_count"] == 8
    assert preflight["summary"]["rollback_boundary_count"] == 4
    assert preflight["summary"]["post_apply_verifier_required_count"] == 1
    assert preflight["summary"]["same_run_truth_required_count"] == 1
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert future_preflight["preflight_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-preflight-"
    )
    assert future_preflight["source_signing_execution_closeout_id"].startswith(
        "pchome-db-apply-authorization-signing-execution-closeout-"
    )
    assert future_preflight["ready_for_future_signed_authorization_receipt_preflight"] is True
    assert (
        future_preflight["can_enter_future_external_signing_receipt_evidence_boundary"]
        is True
    )
    assert future_preflight["ready_for_database_apply_now"] is False
    assert future_preflight["issues_database_apply_authorization"] is False
    assert future_preflight["signs_database_apply_authorization"] is False
    assert future_preflight["signed_authorization_receipt_included"] is False
    assert future_preflight["signature_material_included"] is False
    assert boundary["boundary_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-preflight-"
    )
    assert boundary["authorization_material_type"] == "external_signing_receipt_evidence_boundary"
    assert boundary["ready_for_future_external_signing_receipt_evidence_boundary"] is True
    assert boundary["ready_for_future_signed_authorization_receipt_lane"] is True
    assert boundary["required_external_receipt_evidence_count"] == 10
    assert boundary["external_receipt_acceptance_gate_count"] == 8
    assert "detached_signature_verification_status" in boundary["required_external_receipt_evidence"]
    assert boundary["external_signed_authorization_receipt_required_in_future"] is True
    assert boundary["external_signed_authorization_receipt_included"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert boundary["hash_matches"] is True
    assert boundary["requires_fresh_production_truth_in_same_run"] is True
    assert boundary["requires_post_apply_verifier"] is True
    assert contract["permits_future_external_signing_receipt_evidence_boundary"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "external_receipt_evidence_contract_complete" in check_keys
    assert "preflight_has_no_signed_receipt_signature_or_authorization" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_script"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_closeout_waits_without_ready_preflight():
    closeout = build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout(
        _payload(),
        batch_size=1,
    )

    future_closeout = closeout["future_authorization_signed_receipt_closeout"]
    boundary = closeout["detached_receipt_verification_boundary"]
    contract = closeout["signed_receipt_closeout_contract"]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_closeout"
    )
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_PREFLIGHT"
    assert closeout["summary"]["authorization_signed_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["signed_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["signed_receipt_closeout_waiting_count"] > 0
    assert closeout["summary"]["authorization_signed_receipt_preflight_ready_count"] == 0
    assert closeout["summary"]["signed_receipt_preflight_check_count"] == 12
    assert closeout["summary"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert closeout["summary"]["detached_receipt_verification_boundary_count"] == 1
    assert closeout["summary"]["required_external_receipt_evidence_count"] == 10
    assert closeout["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert closeout["summary"]["detached_receipt_verification_check_count"] == 10
    assert closeout["summary"]["operator_held_secret_boundary_count"] == 1
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future_closeout["ready_for_future_signed_authorization_receipt_closeout"] is False
    assert future_closeout["can_enter_future_detached_receipt_verification_boundary"] is False
    assert future_closeout["ready_for_database_apply_now"] is False
    assert future_closeout["issues_database_apply_authorization"] is False
    assert future_closeout["signs_database_apply_authorization"] is False
    assert future_closeout["external_signed_authorization_receipt_included"] is False
    assert future_closeout["signed_authorization_receipt_included"] is False
    assert future_closeout["signature_material_included"] is False
    assert future_closeout["secret_material_included"] is False
    assert boundary["authorization_material_type"] == "detached_receipt_verification_boundary"
    assert boundary["ready_for_future_detached_receipt_verification_boundary"] is False
    assert boundary["ready_for_future_signed_authorization_receipt_verification_lane"] is False
    assert boundary["detached_receipt_verification_check_count"] == 10
    assert boundary["requires_detached_signature_verification"] is True
    assert boundary["detached_signature_verification_performed"] is False
    assert boundary["external_signed_authorization_receipt_included"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert contract["permits_future_detached_receipt_verification_boundary"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_closeout_ready_after_fake_fetch_but_no_signed_receipt():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signed-receipt-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_signed_receipt_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_closeout = closeout["future_authorization_signed_receipt_closeout"]
    boundary = closeout["detached_receipt_verification_boundary"]
    contract = closeout["signed_receipt_closeout_contract"]
    check_keys = [check["key"] for check in closeout["signed_receipt_closeout_checks"]]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_signed_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["signed_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["signed_receipt_closeout_pass_count"] == 12
    assert closeout["summary"]["signed_receipt_closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_signed_receipt_preflight_ready_count"] == 1
    assert closeout["summary"]["signed_receipt_preflight_check_count"] == 12
    assert closeout["summary"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert closeout["summary"]["detached_receipt_verification_boundary_count"] == 1
    assert closeout["summary"]["required_external_receipt_evidence_count"] == 10
    assert closeout["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert closeout["summary"]["detached_receipt_verification_check_count"] == 10
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future_closeout["closeout_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-closeout-"
    )
    assert future_closeout["source_signed_receipt_preflight_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-preflight-"
    )
    assert future_closeout["ready_for_future_signed_authorization_receipt_closeout"] is True
    assert future_closeout["can_enter_future_detached_receipt_verification_boundary"] is True
    assert future_closeout["ready_for_database_apply_now"] is False
    assert future_closeout["issues_database_apply_authorization"] is False
    assert future_closeout["signs_database_apply_authorization"] is False
    assert future_closeout["external_signed_authorization_receipt_included"] is False
    assert future_closeout["signed_authorization_receipt_included"] is False
    assert future_closeout["signature_material_included"] is False
    assert boundary["boundary_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-closeout-"
    )
    assert boundary["authorization_material_type"] == "detached_receipt_verification_boundary"
    assert boundary["ready_for_future_detached_receipt_verification_boundary"] is True
    assert boundary["ready_for_future_signed_authorization_receipt_verification_lane"] is True
    assert boundary["required_external_receipt_evidence_count"] == 10
    assert boundary["external_receipt_acceptance_gate_count"] == 8
    assert boundary["detached_receipt_verification_check_count"] == 10
    assert "detached_signature_verification_status_passed" in (
        boundary["detached_receipt_verification_checks"]
    )
    assert boundary["requires_detached_signature_verification"] is True
    assert boundary["detached_signature_verification_performed"] is False
    assert boundary["external_signed_authorization_receipt_included"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["secret_material_required_in_preview"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert boundary["hash_matches"] is True
    assert boundary["requires_fresh_production_truth_in_same_run"] is True
    assert boundary["requires_post_apply_verifier"] is True
    assert contract["permits_future_detached_receipt_verification_boundary"] is True
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "detached_receipt_verification_boundary_contract_complete" in check_keys
    assert "closeout_has_no_signed_receipt_signature_or_authorization" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_evidence_intake_waits_without_ready_closeout():
    intake = build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake(
        _payload(),
        batch_size=1,
    )

    future_intake = intake["future_signed_authorization_receipt_evidence_intake"]
    schema = intake["detached_verification_evidence_schema"]
    contract = intake["signed_receipt_evidence_intake_contract"]
    assert intake["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_evidence_intake"
    )
    assert intake["result"] == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_CLOSEOUT"
    assert intake["summary"]["authorization_signed_receipt_evidence_intake_ready_count"] == 0
    assert intake["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert intake["summary"]["signed_receipt_evidence_intake_waiting_count"] > 0
    assert intake["summary"]["authorization_signed_receipt_closeout_ready_count"] == 0
    assert intake["summary"]["signed_receipt_closeout_check_count"] == 12
    assert intake["summary"]["detached_receipt_verification_boundary_count"] == 1
    assert intake["summary"]["detached_verification_evidence_schema_count"] == 1
    assert intake["summary"]["detached_verification_evidence_field_count"] == 12
    assert intake["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert intake["summary"]["signs_database_apply_authorization_count"] == 0
    assert intake["summary"]["reads_secret_count"] == 0
    assert intake["summary"]["executes_script_count"] == 0
    assert intake["summary"]["executes_sql_count"] == 0
    assert intake["summary"]["writes_database_count"] == 0
    assert (
        future_intake["ready_for_future_signed_authorization_receipt_evidence_intake"]
        is False
    )
    assert future_intake["can_enter_future_detached_verification_evidence_validation"] is False
    assert future_intake["external_signed_authorization_receipt_evidence_schema_ready"] is False
    assert future_intake["ready_for_database_apply_now"] is False
    assert future_intake["issues_database_apply_authorization"] is False
    assert future_intake["signs_database_apply_authorization"] is False
    assert future_intake["detached_signature_verification_performed"] is False
    assert future_intake["external_signed_authorization_receipt_included"] is False
    assert future_intake["signed_authorization_receipt_included"] is False
    assert future_intake["signature_material_included"] is False
    assert future_intake["secret_material_included"] is False
    assert schema["authorization_material_type"] == "detached_verification_evidence_schema"
    assert schema["ready_for_future_detached_verification_evidence_schema"] is False
    assert schema["detached_verification_evidence_field_count"] == 12
    assert schema["detached_verification_acceptance_gate_count"] == 10
    assert schema["requires_detached_signature_verification"] is True
    assert schema["detached_signature_verification_performed"] is False
    assert schema["external_signed_authorization_receipt_required_in_future"] is True
    assert schema["external_signed_authorization_receipt_included"] is False
    assert schema["signed_authorization_receipt_included"] is False
    assert schema["signature_material_included"] is False
    assert schema["secret_material_included"] is False
    assert schema["accepts_plaintext_secret"] is False
    assert schema["reads_secret_in_preview"] is False
    assert schema["executes_shell_in_preview"] is False
    assert schema["executes_sql_in_preview"] is False
    assert schema["writes_database_in_preview"] is False
    assert schema["ready_for_database_apply_now"] is False
    assert schema["signs_database_apply_authorization"] is False
    assert contract["permits_future_detached_verification_evidence_validation"] is False
    assert contract["accepts_plaintext_secret"] is False
    assert contract["detached_signature_verification_performed"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert intake["safety"]["reads_secret_in_preview"] is False
    assert intake["safety"]["performs_detached_signature_verification"] is False
    assert intake["safety"]["signs_database_apply_authorization"] is False
    assert intake["safety"]["executes_sql"] is False
    assert intake["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_evidence_intake_ready_after_fake_fetch_but_no_signed_receipt():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-signed-receipt-evidence-intake.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    intake = build_pchome_auto_policy_db_apply_authorization_signed_receipt_evidence_intake(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_intake = intake["future_signed_authorization_receipt_evidence_intake"]
    schema = intake["detached_verification_evidence_schema"]
    contract = intake["signed_receipt_evidence_intake_contract"]
    check_keys = [check["key"] for check in intake["signed_receipt_evidence_intake_checks"]]
    assert intake["result"] == "DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE_READY"
    assert intake["summary"]["authorization_signed_receipt_evidence_intake_ready_count"] == 1
    assert intake["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert intake["summary"]["signed_receipt_evidence_intake_pass_count"] == 12
    assert intake["summary"]["signed_receipt_evidence_intake_waiting_count"] == 0
    assert intake["summary"]["authorization_signed_receipt_closeout_ready_count"] == 1
    assert intake["summary"]["signed_receipt_closeout_check_count"] == 12
    assert intake["summary"]["detached_receipt_verification_boundary_count"] == 1
    assert intake["summary"]["detached_verification_evidence_schema_count"] == 1
    assert intake["summary"]["required_external_receipt_evidence_count"] == 10
    assert intake["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert intake["summary"]["detached_receipt_verification_check_count"] == 10
    assert intake["summary"]["detached_verification_evidence_field_count"] == 12
    assert intake["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert intake["summary"]["post_apply_verifier_required_count"] == 1
    assert intake["summary"]["same_run_truth_required_count"] == 1
    assert intake["summary"]["signs_database_apply_authorization_count"] == 0
    assert intake["summary"]["reads_secret_count"] == 0
    assert intake["summary"]["executes_script_count"] == 0
    assert intake["summary"]["executes_sql_count"] == 0
    assert intake["summary"]["writes_database_count"] == 0
    assert future_intake["intake_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-evidence-intake-"
    )
    assert future_intake["source_signed_receipt_closeout_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-closeout-"
    )
    assert (
        future_intake["ready_for_future_signed_authorization_receipt_evidence_intake"]
        is True
    )
    assert future_intake["can_enter_future_detached_verification_evidence_validation"] is True
    assert future_intake["external_signed_authorization_receipt_evidence_schema_ready"] is True
    assert future_intake["ready_for_database_apply_now"] is False
    assert future_intake["issues_database_apply_authorization"] is False
    assert future_intake["signs_database_apply_authorization"] is False
    assert future_intake["detached_signature_verification_performed"] is False
    assert future_intake["external_signed_authorization_receipt_included"] is False
    assert future_intake["signed_authorization_receipt_included"] is False
    assert future_intake["signature_material_included"] is False
    assert future_intake["secret_material_included"] is False
    assert schema["schema_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-evidence-intake-"
    )
    assert schema["authorization_material_type"] == "detached_verification_evidence_schema"
    assert schema["ready_for_future_detached_verification_evidence_schema"] is True
    assert schema["required_external_receipt_evidence_count"] == 10
    assert schema["external_receipt_acceptance_gate_count"] == 8
    assert schema["detached_receipt_verification_check_count"] == 10
    assert schema["detached_verification_evidence_field_count"] == 12
    assert schema["detached_verification_acceptance_gate_count"] == 10
    assert "verifier_receipt_sha256" in schema["detached_verification_evidence_fields"]
    assert "detached_signature_verification_status_is_passed" in (
        schema["detached_verification_acceptance_gates"]
    )
    assert schema["requires_detached_signature_verification"] is True
    assert schema["detached_signature_verification_performed"] is False
    assert schema["external_signed_authorization_receipt_required_in_future"] is True
    assert schema["external_signed_authorization_receipt_included"] is False
    assert schema["signed_authorization_receipt_included"] is False
    assert schema["signature_material_included"] is False
    assert schema["secret_material_included"] is False
    assert schema["accepts_plaintext_secret"] is False
    assert schema["reads_secret_in_preview"] is False
    assert schema["executes_shell_in_preview"] is False
    assert schema["executes_sql_in_preview"] is False
    assert schema["writes_database_in_preview"] is False
    assert schema["ready_for_database_apply_now"] is False
    assert schema["signs_database_apply_authorization"] is False
    assert schema["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert schema["hash_matches"] is True
    assert schema["requires_fresh_production_truth_in_same_run"] is True
    assert schema["requires_post_apply_verifier"] is True
    assert contract["permits_future_detached_verification_evidence_validation"] is True
    assert contract["accepts_plaintext_secret"] is False
    assert contract["detached_signature_verification_performed"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "detached_verification_evidence_schema_complete" in check_keys
    assert "no_signed_receipt_signature_secret_or_verification_execution" in check_keys
    assert "preview_has_no_side_effects_and_no_signing" in check_keys
    assert intake["safety"]["reads_secret_in_preview"] is False
    assert intake["safety"]["performs_detached_signature_verification"] is False
    assert intake["safety"]["signs_database_apply_authorization"] is False
    assert intake["safety"]["executes_script"] is False
    assert intake["safety"]["executes_sql"] is False
    assert intake["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_detached_verification_evidence_validation_waits_without_ready_intake():
    validation = (
        build_pchome_auto_policy_db_apply_authorization_detached_verification_evidence_validation(
            _payload(),
            batch_size=1,
        )
    )

    future_validation = validation["future_detached_verification_evidence_validation"]
    boundary = validation["verifier_receipt_closeout_boundary"]
    contract = validation["detached_verification_evidence_validation_contract"]
    assert validation["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_detached_verification_evidence_validation"
    )
    assert (
        validation["result"]
        == "WAITING_FOR_DB_APPLY_AUTHORIZATION_SIGNED_RECEIPT_EVIDENCE_INTAKE"
    )
    assert (
        validation["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 0
    )
    assert validation["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert validation["summary"]["detached_verification_evidence_validation_waiting_count"] > 0
    assert validation["summary"]["authorization_signed_receipt_evidence_intake_ready_count"] == 0
    assert validation["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert validation["summary"]["detached_verification_evidence_schema_count"] == 1
    assert validation["summary"]["verifier_receipt_closeout_boundary_count"] == 1
    assert validation["summary"]["detached_verification_evidence_field_count"] == 12
    assert validation["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert validation["summary"]["verifier_receipt_field_count"] == 12
    assert validation["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert validation["summary"]["signs_database_apply_authorization_count"] == 0
    assert validation["summary"]["reads_secret_count"] == 0
    assert validation["summary"]["executes_script_count"] == 0
    assert validation["summary"]["executes_sql_count"] == 0
    assert validation["summary"]["writes_database_count"] == 0
    assert (
        future_validation["ready_for_future_detached_verification_evidence_validation"]
        is False
    )
    assert future_validation["can_enter_future_verifier_receipt_closeout"] is False
    assert future_validation["verifier_receipt_closeout_boundary_ready"] is False
    assert future_validation["ready_for_database_apply_now"] is False
    assert future_validation["issues_database_apply_authorization"] is False
    assert future_validation["signs_database_apply_authorization"] is False
    assert future_validation["detached_signature_verification_performed"] is False
    assert future_validation["verifier_receipt_persisted"] is False
    assert future_validation["external_signed_authorization_receipt_included"] is False
    assert future_validation["signed_authorization_receipt_included"] is False
    assert future_validation["signature_material_included"] is False
    assert future_validation["secret_material_included"] is False
    assert boundary["authorization_material_type"] == "verifier_receipt_closeout_boundary"
    assert boundary["ready_for_future_verifier_receipt_closeout_boundary"] is False
    assert boundary["verifier_receipt_field_count"] == 12
    assert boundary["verifier_receipt_acceptance_gate_count"] == 10
    assert boundary["requires_detached_signature_verification"] is True
    assert boundary["detached_signature_verification_performed"] is False
    assert boundary["verifier_receipt_persisted"] is False
    assert boundary["external_signed_authorization_receipt_included"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["accepts_plaintext_secret"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert contract["permits_future_verifier_receipt_closeout"] is False
    assert contract["accepts_plaintext_secret"] is False
    assert contract["performs_detached_signature_verification"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert validation["safety"]["reads_secret_in_preview"] is False
    assert validation["safety"]["performs_detached_signature_verification"] is False
    assert validation["safety"]["persists_verifier_receipt"] is False
    assert validation["safety"]["signs_database_apply_authorization"] is False
    assert validation["safety"]["executes_sql"] is False
    assert validation["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_detached_verification_evidence_validation_ready_after_fake_fetch_but_no_verification():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-detached-verification-validation.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    validation = (
        build_pchome_auto_policy_db_apply_authorization_detached_verification_evidence_validation(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future_validation = validation["future_detached_verification_evidence_validation"]
    boundary = validation["verifier_receipt_closeout_boundary"]
    contract = validation["detached_verification_evidence_validation_contract"]
    check_keys = [
        check["key"]
        for check in validation["detached_verification_evidence_validation_checks"]
    ]
    assert (
        validation["result"]
        == "DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION_READY"
    )
    assert (
        validation["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 1
    )
    assert validation["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert validation["summary"]["detached_verification_evidence_validation_pass_count"] == 12
    assert validation["summary"]["detached_verification_evidence_validation_waiting_count"] == 0
    assert validation["summary"]["authorization_signed_receipt_evidence_intake_ready_count"] == 1
    assert validation["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert validation["summary"]["detached_verification_evidence_schema_count"] == 1
    assert validation["summary"]["verifier_receipt_closeout_boundary_count"] == 1
    assert validation["summary"]["required_external_receipt_evidence_count"] == 10
    assert validation["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert validation["summary"]["detached_receipt_verification_check_count"] == 10
    assert validation["summary"]["detached_verification_evidence_field_count"] == 12
    assert validation["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert validation["summary"]["verifier_receipt_field_count"] == 12
    assert validation["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert validation["summary"]["post_apply_verifier_required_count"] == 1
    assert validation["summary"]["same_run_truth_required_count"] == 1
    assert validation["summary"]["signs_database_apply_authorization_count"] == 0
    assert validation["summary"]["reads_secret_count"] == 0
    assert validation["summary"]["executes_script_count"] == 0
    assert validation["summary"]["executes_sql_count"] == 0
    assert validation["summary"]["writes_database_count"] == 0
    assert future_validation["validation_id"].startswith(
        "pchome-db-apply-authorization-detached-verification-evidence-validation-"
    )
    assert future_validation["source_signed_receipt_evidence_intake_id"].startswith(
        "pchome-db-apply-authorization-signed-receipt-evidence-intake-"
    )
    assert (
        future_validation["ready_for_future_detached_verification_evidence_validation"]
        is True
    )
    assert future_validation["can_enter_future_verifier_receipt_closeout"] is True
    assert future_validation["verifier_receipt_closeout_boundary_ready"] is True
    assert future_validation["ready_for_database_apply_now"] is False
    assert future_validation["issues_database_apply_authorization"] is False
    assert future_validation["signs_database_apply_authorization"] is False
    assert future_validation["detached_signature_verification_performed"] is False
    assert future_validation["verifier_receipt_persisted"] is False
    assert future_validation["external_signed_authorization_receipt_included"] is False
    assert future_validation["signed_authorization_receipt_included"] is False
    assert future_validation["signature_material_included"] is False
    assert future_validation["secret_material_included"] is False
    assert boundary["boundary_id"].startswith(
        "pchome-db-apply-authorization-detached-verification-evidence-validation-"
    )
    assert boundary["authorization_material_type"] == "verifier_receipt_closeout_boundary"
    assert boundary["ready_for_future_verifier_receipt_closeout_boundary"] is True
    assert boundary["required_external_receipt_evidence_count"] == 10
    assert boundary["external_receipt_acceptance_gate_count"] == 8
    assert boundary["detached_receipt_verification_check_count"] == 10
    assert boundary["detached_verification_evidence_field_count"] == 12
    assert boundary["detached_verification_acceptance_gate_count"] == 10
    assert boundary["verifier_receipt_field_count"] == 12
    assert boundary["verifier_receipt_acceptance_gate_count"] == 10
    assert "verifier_receipt_sha256" in boundary["verifier_receipt_fields"]
    assert "detached_signature_verification_status_passed" in (
        boundary["verifier_receipt_acceptance_gates"]
    )
    assert boundary["requires_detached_signature_verification"] is True
    assert boundary["detached_signature_verification_performed"] is False
    assert boundary["verifier_receipt_persisted"] is False
    assert boundary["external_signed_authorization_receipt_required_in_future"] is True
    assert boundary["external_signed_authorization_receipt_included"] is False
    assert boundary["signed_authorization_receipt_included"] is False
    assert boundary["signature_material_included"] is False
    assert boundary["secret_material_included"] is False
    assert boundary["accepts_plaintext_secret"] is False
    assert boundary["reads_secret_in_preview"] is False
    assert boundary["executes_shell_in_preview"] is False
    assert boundary["executes_sql_in_preview"] is False
    assert boundary["writes_database_in_preview"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert boundary["hash_matches"] is True
    assert boundary["requires_fresh_production_truth_in_same_run"] is True
    assert boundary["requires_post_apply_verifier"] is True
    assert contract["permits_future_verifier_receipt_closeout"] is True
    assert contract["accepts_plaintext_secret"] is False
    assert contract["performs_detached_signature_verification"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "verifier_receipt_closeout_boundary_contract_complete" in check_keys
    assert "secret_and_signed_material_boundary_enforced" in check_keys
    assert "preview_has_no_side_effects_no_verification_no_signing" in check_keys
    assert validation["safety"]["reads_secret_in_preview"] is False
    assert validation["safety"]["performs_detached_signature_verification"] is False
    assert validation["safety"]["persists_verifier_receipt"] is False
    assert validation["safety"]["signs_database_apply_authorization"] is False
    assert validation["safety"]["executes_script"] is False
    assert validation["safety"]["executes_sql"] is False
    assert validation["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_verifier_receipt_closeout_waits_without_ready_validation():
    closeout = build_pchome_auto_policy_db_apply_authorization_verifier_receipt_closeout(
        _payload(),
        batch_size=1,
    )

    future_closeout = closeout["future_verifier_receipt_closeout"]
    handoff = closeout["verifier_receipt_evidence_handoff"]
    contract = closeout["verifier_receipt_closeout_contract"]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_verifier_receipt_closeout"
    )
    assert (
        closeout["result"]
        == "WAITING_FOR_DB_APPLY_AUTHORIZATION_DETACHED_VERIFICATION_EVIDENCE_VALIDATION"
    )
    assert closeout["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["verifier_receipt_closeout_waiting_count"] > 0
    assert (
        closeout["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 0
    )
    assert closeout["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert closeout["summary"]["verifier_receipt_closeout_boundary_count"] == 1
    assert closeout["summary"]["verifier_receipt_evidence_handoff_count"] == 1
    assert closeout["summary"]["verifier_receipt_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future_closeout["ready_for_future_verifier_receipt_closeout"] is False
    assert (
        future_closeout[
            "can_enter_future_database_apply_authorization_verifier_handoff"
        ]
        is False
    )
    assert future_closeout["verifier_receipt_evidence_handoff_ready"] is False
    assert future_closeout["ready_for_database_apply_now"] is False
    assert future_closeout["issues_database_apply_authorization"] is False
    assert future_closeout["signs_database_apply_authorization"] is False
    assert future_closeout["detached_signature_verification_performed"] is False
    assert future_closeout["verifier_receipt_persisted"] is False
    assert future_closeout["external_signed_authorization_receipt_included"] is False
    assert future_closeout["signed_authorization_receipt_included"] is False
    assert future_closeout["signature_material_included"] is False
    assert future_closeout["secret_material_included"] is False
    assert handoff["authorization_material_type"] == "verifier_receipt_evidence_handoff"
    assert handoff["ready_for_future_verifier_receipt_evidence_handoff"] is False
    assert handoff["verifier_receipt_field_count"] == 12
    assert handoff["verifier_receipt_acceptance_gate_count"] == 10
    assert handoff["verifier_receipt_evidence_handoff_field_count"] == 12
    assert handoff["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert handoff["requires_detached_signature_verification"] is True
    assert handoff["detached_signature_verification_performed"] is False
    assert handoff["verifier_receipt_persisted"] is False
    assert handoff["external_signed_authorization_receipt_included"] is False
    assert handoff["signed_authorization_receipt_included"] is False
    assert handoff["signature_material_included"] is False
    assert handoff["secret_material_included"] is False
    assert handoff["accepts_plaintext_secret"] is False
    assert handoff["reads_secret_in_preview"] is False
    assert handoff["executes_shell_in_preview"] is False
    assert handoff["executes_sql_in_preview"] is False
    assert handoff["writes_database_in_preview"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["signs_database_apply_authorization"] is False
    assert contract["permits_future_database_apply_authorization_verifier_handoff"] is False
    assert contract["accepts_plaintext_secret"] is False
    assert contract["performs_detached_signature_verification"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["performs_detached_signature_verification"] is False
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_verifier_receipt_closeout_ready_after_fake_fetch_but_no_receipt_persist():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-verifier-receipt-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_verifier_receipt_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_closeout = closeout["future_verifier_receipt_closeout"]
    handoff = closeout["verifier_receipt_evidence_handoff"]
    contract = closeout["verifier_receipt_closeout_contract"]
    check_keys = [check["key"] for check in closeout["verifier_receipt_closeout_checks"]]
    assert closeout["result"] == "DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT_READY"
    assert closeout["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["verifier_receipt_closeout_pass_count"] == 12
    assert closeout["summary"]["verifier_receipt_closeout_waiting_count"] == 0
    assert (
        closeout["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 1
    )
    assert closeout["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert closeout["summary"]["authorization_signed_receipt_evidence_intake_ready_count"] == 1
    assert closeout["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert closeout["summary"]["verifier_receipt_closeout_boundary_count"] == 1
    assert closeout["summary"]["verifier_receipt_evidence_handoff_count"] == 1
    assert closeout["summary"]["required_external_receipt_evidence_count"] == 10
    assert closeout["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert closeout["summary"]["verifier_receipt_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert closeout["summary"]["detached_verification_evidence_field_count"] == 12
    assert closeout["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future_closeout["closeout_id"].startswith(
        "pchome-db-apply-authorization-verifier-receipt-closeout-"
    )
    assert future_closeout["source_detached_verification_evidence_validation_id"].startswith(
        "pchome-db-apply-authorization-detached-verification-evidence-validation-"
    )
    assert future_closeout["ready_for_future_verifier_receipt_closeout"] is True
    assert (
        future_closeout[
            "can_enter_future_database_apply_authorization_verifier_handoff"
        ]
        is True
    )
    assert future_closeout["verifier_receipt_evidence_handoff_ready"] is True
    assert future_closeout["ready_for_database_apply_now"] is False
    assert future_closeout["issues_database_apply_authorization"] is False
    assert future_closeout["signs_database_apply_authorization"] is False
    assert future_closeout["detached_signature_verification_performed"] is False
    assert future_closeout["verifier_receipt_persisted"] is False
    assert future_closeout["external_signed_authorization_receipt_included"] is False
    assert future_closeout["signed_authorization_receipt_included"] is False
    assert future_closeout["signature_material_included"] is False
    assert future_closeout["secret_material_included"] is False
    assert handoff["handoff_id"].startswith(
        "pchome-db-apply-authorization-verifier-receipt-closeout-"
    )
    assert handoff["authorization_material_type"] == "verifier_receipt_evidence_handoff"
    assert handoff["ready_for_future_verifier_receipt_evidence_handoff"] is True
    assert handoff["required_external_receipt_evidence_count"] == 10
    assert handoff["external_receipt_acceptance_gate_count"] == 8
    assert handoff["verifier_receipt_field_count"] == 12
    assert handoff["verifier_receipt_acceptance_gate_count"] == 10
    assert handoff["verifier_receipt_evidence_handoff_field_count"] == 12
    assert handoff["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert "verifier_receipt_sha256" in handoff["verifier_receipt_evidence_handoff_fields"]
    assert "verifier_receipt_not_persisted_by_preview" in (
        handoff["verifier_receipt_handoff_acceptance_gates"]
    )
    assert handoff["requires_detached_signature_verification"] is True
    assert handoff["detached_signature_verification_performed"] is False
    assert handoff["verifier_receipt_persisted"] is False
    assert handoff["external_signed_authorization_receipt_required_in_future"] is True
    assert handoff["external_signed_authorization_receipt_included"] is False
    assert handoff["signed_authorization_receipt_included"] is False
    assert handoff["signature_material_included"] is False
    assert handoff["secret_material_included"] is False
    assert handoff["accepts_plaintext_secret"] is False
    assert handoff["reads_secret_in_preview"] is False
    assert handoff["executes_shell_in_preview"] is False
    assert handoff["executes_sql_in_preview"] is False
    assert handoff["writes_database_in_preview"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["signs_database_apply_authorization"] is False
    assert handoff["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert handoff["hash_matches"] is True
    assert handoff["requires_fresh_production_truth_in_same_run"] is True
    assert handoff["requires_post_apply_verifier"] is True
    assert contract["permits_future_database_apply_authorization_verifier_handoff"] is True
    assert contract["accepts_plaintext_secret"] is False
    assert contract["performs_detached_signature_verification"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["issues_database_apply_authorization"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "verifier_receipt_evidence_handoff_contract_complete" in check_keys
    assert "secret_signed_material_and_receipt_persistence_boundary_enforced" in check_keys
    assert "preview_has_no_side_effects_no_verification_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["performs_detached_signature_verification"] is False
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_script"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_evidence_execution_preflight_waits_without_ready_closeout():
    preflight = build_pchome_auto_policy_db_apply_authorization_evidence_execution_preflight(
        _payload(),
        batch_size=1,
    )

    handoff = preflight["future_database_apply_authorization_verifier_handoff"]
    package = preflight["authorization_evidence_execution_preflight"]
    contract = preflight["authorization_evidence_execution_preflight_contract"]
    check_keys = [
        check["key"]
        for check in preflight["authorization_evidence_execution_preflight_checks"]
    ]
    assert preflight["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_evidence_execution_preflight"
    )
    assert (
        preflight["result"]
        == "WAITING_FOR_DB_APPLY_AUTHORIZATION_VERIFIER_RECEIPT_CLOSEOUT"
    )
    assert preflight["summary"]["authorization_evidence_execution_preflight_ready_count"] == 0
    assert preflight["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_preflight_waiting_count"] > 0
    assert preflight["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 0
    assert preflight["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert (
        preflight["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 0
    )
    assert preflight["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert preflight["summary"]["verifier_receipt_evidence_handoff_count"] == 1
    assert preflight["summary"]["authorization_evidence_execution_preflight_count"] == 1
    assert preflight["summary"]["authorization_evidence_execution_field_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert preflight["summary"]["verifier_receipt_field_count"] == 12
    assert preflight["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert preflight["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert preflight["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_migration_count"] == 0
    assert preflight["summary"]["executes_endpoint_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert handoff["preflight_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-preflight-"
    )
    assert (
        handoff["ready_for_future_database_apply_authorization_verifier_handoff"]
        is False
    )
    assert (
        handoff["can_enter_future_authorization_evidence_execution_closeout"]
        is False
    )
    assert handoff["authorization_evidence_execution_preflight_ready"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["issues_database_apply_authorization"] is False
    assert handoff["signs_database_apply_authorization"] is False
    assert handoff["executes_authorization_evidence"] is False
    assert handoff["detached_signature_verification_performed"] is False
    assert handoff["verifier_receipt_persisted"] is False
    assert handoff["external_signed_authorization_receipt_included"] is False
    assert handoff["signed_authorization_receipt_included"] is False
    assert handoff["signature_material_included"] is False
    assert handoff["secret_material_included"] is False
    assert package["authorization_material_type"] == (
        "authorization_evidence_execution_preflight"
    )
    assert package["ready_for_future_authorization_evidence_execution_preflight"] is False
    assert package["authorization_evidence_execution_field_count"] == 12
    assert package["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert package["verifier_receipt_field_count"] == 12
    assert package["verifier_receipt_acceptance_gate_count"] == 10
    assert package["verifier_receipt_evidence_handoff_field_count"] == 12
    assert package["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert package["requires_detached_signature_verification"] is True
    assert package["detached_signature_verification_performed"] is False
    assert package["verifier_receipt_persisted"] is False
    assert package["external_signed_authorization_receipt_included"] is False
    assert package["signed_authorization_receipt_included"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["signs_database_apply_authorization"] is False
    assert contract["permits_future_authorization_evidence_execution_closeout"] is False
    assert contract["accepts_plaintext_secret"] is False
    assert contract["performs_detached_signature_verification"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["executes_authorization_evidence"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "verifier_receipt_closeout_ready" in check_keys
    assert "authorization_evidence_execution_preflight_contract_complete" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["performs_detached_signature_verification"] is False
    assert preflight["safety"]["persists_verifier_receipt"] is False
    assert preflight["safety"]["executes_authorization_evidence"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_evidence_execution_preflight_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-evidence-execution-preflight.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_authorization_evidence_execution_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    handoff = preflight["future_database_apply_authorization_verifier_handoff"]
    package = preflight["authorization_evidence_execution_preflight"]
    contract = preflight["authorization_evidence_execution_preflight_contract"]
    check_keys = [
        check["key"]
        for check in preflight["authorization_evidence_execution_preflight_checks"]
    ]
    assert (
        preflight["result"]
        == "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT_READY"
    )
    assert preflight["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert preflight["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_preflight_pass_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_preflight_waiting_count"] == 0
    assert preflight["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert preflight["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert (
        preflight["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 1
    )
    assert preflight["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_preflight_count"] == 1
    assert preflight["summary"]["authorization_evidence_execution_field_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert preflight["summary"]["verifier_receipt_field_count"] == 12
    assert preflight["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert preflight["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert preflight["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert preflight["summary"]["required_external_receipt_evidence_count"] == 10
    assert preflight["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert preflight["summary"]["post_apply_verifier_required_count"] == 1
    assert preflight["summary"]["same_run_truth_required_count"] == 1
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_migration_count"] == 0
    assert preflight["summary"]["executes_endpoint_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert handoff["preflight_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-preflight-"
    )
    assert handoff["source_verifier_receipt_closeout_id"].startswith(
        "pchome-db-apply-authorization-verifier-receipt-closeout-"
    )
    assert (
        handoff["source_verifier_receipt_evidence_handoff_id"].startswith(
            "pchome-db-apply-authorization-verifier-receipt-closeout-"
        )
    )
    assert (
        handoff["ready_for_future_database_apply_authorization_verifier_handoff"]
        is True
    )
    assert (
        handoff["can_enter_future_authorization_evidence_execution_closeout"]
        is True
    )
    assert handoff["authorization_evidence_execution_preflight_ready"] is True
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["issues_database_apply_authorization"] is False
    assert handoff["signs_database_apply_authorization"] is False
    assert handoff["executes_authorization_evidence"] is False
    assert handoff["detached_signature_verification_performed"] is False
    assert handoff["verifier_receipt_persisted"] is False
    assert handoff["external_signed_authorization_receipt_included"] is False
    assert handoff["signed_authorization_receipt_included"] is False
    assert handoff["signature_material_included"] is False
    assert handoff["secret_material_included"] is False
    assert package["preflight_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-preflight-"
    )
    assert package["authorization_material_type"] == (
        "authorization_evidence_execution_preflight"
    )
    assert package["ready_for_future_authorization_evidence_execution_preflight"] is True
    assert package["authorization_evidence_execution_field_count"] == 12
    assert package["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert package["verifier_receipt_field_count"] == 12
    assert package["verifier_receipt_acceptance_gate_count"] == 10
    assert package["verifier_receipt_evidence_handoff_field_count"] == 12
    assert package["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert "verifier_receipt_sha256" in package["authorization_evidence_execution_fields"]
    assert "no_secret_signature_or_database_write_in_preflight" in (
        package["authorization_evidence_execution_acceptance_gates"]
    )
    assert package["requires_detached_signature_verification"] is True
    assert package["detached_signature_verification_performed"] is False
    assert package["verifier_receipt_persisted"] is False
    assert package["external_signed_authorization_receipt_included"] is False
    assert package["signed_authorization_receipt_included"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_shell_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["requires_fresh_production_truth_in_same_run"] is True
    assert package["requires_post_apply_verifier"] is True
    assert contract["permits_future_authorization_evidence_execution_closeout"] is True
    assert contract["accepts_plaintext_secret"] is False
    assert contract["performs_detached_signature_verification"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["executes_authorization_evidence"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "verifier_receipt_closeout_ready" in check_keys
    assert "source_chain_ids_present" in check_keys
    assert "closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["performs_detached_signature_verification"] is False
    assert preflight["safety"]["persists_verifier_receipt"] is False
    assert preflight["safety"]["executes_authorization_evidence"] is False
    assert preflight["safety"]["signs_database_apply_authorization"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_evidence_execution_closeout_waits_without_ready_preflight():
    closeout = build_pchome_auto_policy_db_apply_authorization_evidence_execution_closeout(
        _payload(),
        batch_size=1,
    )

    final_gate = closeout["future_database_apply_authorization_final_verifier_gate"]
    package = closeout["authorization_evidence_execution_closeout"]
    contract = closeout["authorization_evidence_execution_closeout_contract"]
    check_keys = [
        check["key"]
        for check in closeout["authorization_evidence_execution_closeout_checks"]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_evidence_execution_closeout"
    )
    assert (
        closeout["result"]
        == "WAITING_FOR_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_PREFLIGHT"
    )
    assert closeout["summary"]["authorization_evidence_execution_closeout_ready_count"] == 0
    assert closeout["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_waiting_count"] > 0
    assert closeout["summary"]["authorization_evidence_execution_preflight_ready_count"] == 0
    assert closeout["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["authorization_evidence_execution_closeout_count"] == 1
    assert closeout["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert closeout["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 0
    assert closeout["summary"]["authorization_evidence_execution_closeout_field_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["authorization_evidence_execution_field_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_migration_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert final_gate["final_verifier_gate_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-closeout-"
    )
    assert (
        final_gate["ready_for_future_database_apply_authorization_final_verifier_gate"]
        is False
    )
    assert (
        final_gate["can_enter_future_database_apply_controlled_apply_final_preflight"]
        is False
    )
    assert final_gate["authorization_evidence_execution_closeout_ready"] is False
    assert final_gate["final_verifier_gate_ready"] is False
    assert final_gate["final_verifier_gate_executed"] is False
    assert final_gate["ready_for_database_apply_now"] is False
    assert final_gate["database_apply_authorized"] is False
    assert final_gate["issues_database_apply_authorization"] is False
    assert final_gate["signs_database_apply_authorization"] is False
    assert final_gate["executes_authorization_evidence"] is False
    assert final_gate["executes_database_apply"] is False
    assert final_gate["detached_signature_verification_performed"] is False
    assert final_gate["verifier_receipt_persisted"] is False
    assert final_gate["external_signed_authorization_receipt_included"] is False
    assert final_gate["signed_authorization_receipt_included"] is False
    assert final_gate["signature_material_included"] is False
    assert final_gate["secret_material_included"] is False
    assert package["authorization_material_type"] == (
        "authorization_evidence_execution_closeout"
    )
    assert package["ready_for_future_authorization_evidence_execution_closeout"] is False
    assert package["authorization_evidence_execution_closeout_field_count"] == 12
    assert package["authorization_evidence_execution_closeout_acceptance_gate_count"] == 10
    assert package["authorization_evidence_execution_field_count"] == 12
    assert package["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert "final_verifier_gate_endpoint" in package[
        "authorization_evidence_execution_closeout_fields"
    ]
    assert "no_database_apply_authorized_by_closeout" in package[
        "authorization_evidence_execution_closeout_acceptance_gates"
    ]
    assert package["requires_detached_signature_verification"] is True
    assert package["detached_signature_verification_performed"] is False
    assert package["verifier_receipt_persisted"] is False
    assert package["external_signed_authorization_receipt_included"] is False
    assert package["signed_authorization_receipt_included"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_endpoint_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["executes_database_apply"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert package["signs_database_apply_authorization"] is False
    assert contract["permits_future_database_apply_authorization_final_verifier_gate"] is False
    assert contract["permits_future_database_apply_controlled_apply_final_preflight"] is False
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "authorization_evidence_execution_preflight_ready" in check_keys
    assert "authorization_evidence_execution_closeout_contract_complete" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["performs_detached_signature_verification"] is False
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_authorization_evidence"] is False
    assert closeout["safety"]["executes_database_apply"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_evidence_execution_closeout_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-authorization-evidence-execution-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_authorization_evidence_execution_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    final_gate = closeout["future_database_apply_authorization_final_verifier_gate"]
    package = closeout["authorization_evidence_execution_closeout"]
    contract = closeout["authorization_evidence_execution_closeout_contract"]
    check_keys = [
        check["key"]
        for check in closeout["authorization_evidence_execution_closeout_checks"]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT_READY"
    )
    assert closeout["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_pass_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_waiting_count"] == 0
    assert closeout["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert (
        closeout["summary"][
            "authorization_detached_verification_evidence_validation_ready_count"
        ]
        == 1
    )
    assert closeout["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_preflight_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_count"] == 1
    assert closeout["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert closeout["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_field_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["authorization_evidence_execution_field_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert closeout["summary"]["required_external_receipt_evidence_count"] == 10
    assert closeout["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_script_count"] == 0
    assert closeout["summary"]["executes_migration_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert final_gate["final_verifier_gate_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-closeout-"
    )
    assert (
        final_gate["source_authorization_evidence_execution_preflight_id"].startswith(
            "pchome-db-apply-authorization-evidence-execution-preflight-"
        )
    )
    assert final_gate["source_verifier_receipt_closeout_id"].startswith(
        "pchome-db-apply-authorization-verifier-receipt-closeout-"
    )
    assert (
        final_gate["ready_for_future_database_apply_authorization_final_verifier_gate"]
        is True
    )
    assert (
        final_gate["can_enter_future_database_apply_controlled_apply_final_preflight"]
        is True
    )
    assert final_gate["authorization_evidence_execution_closeout_ready"] is True
    assert final_gate["final_verifier_gate_ready"] is True
    assert final_gate["final_verifier_gate_executed"] is False
    assert final_gate["ready_for_database_apply_now"] is False
    assert final_gate["database_apply_authorized"] is False
    assert final_gate["issues_database_apply_authorization"] is False
    assert final_gate["signs_database_apply_authorization"] is False
    assert final_gate["executes_authorization_evidence"] is False
    assert final_gate["executes_database_apply"] is False
    assert final_gate["detached_signature_verification_performed"] is False
    assert final_gate["verifier_receipt_persisted"] is False
    assert final_gate["external_signed_authorization_receipt_included"] is False
    assert final_gate["signed_authorization_receipt_included"] is False
    assert final_gate["signature_material_included"] is False
    assert final_gate["secret_material_included"] is False
    assert package["closeout_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-closeout-"
    )
    assert package["authorization_material_type"] == (
        "authorization_evidence_execution_closeout"
    )
    assert package["ready_for_future_authorization_evidence_execution_closeout"] is True
    assert package["authorization_evidence_execution_closeout_field_count"] == 12
    assert package["authorization_evidence_execution_closeout_acceptance_gate_count"] == 10
    assert package["authorization_evidence_execution_field_count"] == 12
    assert package["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert "final_verifier_gate_endpoint" in package[
        "authorization_evidence_execution_closeout_fields"
    ]
    assert "no_database_apply_authorized_by_closeout" in package[
        "authorization_evidence_execution_closeout_acceptance_gates"
    ]
    assert package["requires_detached_signature_verification"] is True
    assert package["detached_signature_verification_performed"] is False
    assert package["verifier_receipt_persisted"] is False
    assert package["external_signed_authorization_receipt_included"] is False
    assert package["signed_authorization_receipt_included"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["executes_endpoint_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["executes_database_apply"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["requires_fresh_production_truth_in_same_run"] is True
    assert package["requires_post_apply_verifier"] is True
    assert contract["permits_future_database_apply_authorization_final_verifier_gate"] is True
    assert contract["permits_future_database_apply_controlled_apply_final_preflight"] is True
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "authorization_evidence_execution_preflight_ready" in check_keys
    assert "final_verifier_handoff_ready" in check_keys
    assert "verifier_hash_and_receipt_chain_locked" in check_keys
    assert "preflight_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["performs_detached_signature_verification"] is False
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_authorization_evidence"] is False
    assert closeout["safety"]["executes_database_apply"] is False
    assert closeout["safety"]["signs_database_apply_authorization"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_apply_final_preflight_waits_without_ready_final_gate():
    preflight = build_pchome_auto_policy_db_apply_controlled_apply_final_preflight(
        _payload(),
        batch_size=1,
    )

    future_preflight = preflight["future_database_apply_controlled_apply_final_preflight"]
    package = preflight["controlled_apply_final_preflight"]
    contract = preflight["controlled_apply_final_preflight_contract"]
    rollback_binding = package["rollback_binding"]
    verifier_binding = package["post_apply_verifier_binding"]
    check_keys = [check["key"] for check in preflight["controlled_apply_final_preflight_checks"]]
    assert preflight["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_apply_final_preflight"
    )
    assert (
        preflight["result"]
        == "WAITING_FOR_DB_APPLY_AUTHORIZATION_EVIDENCE_EXECUTION_CLOSEOUT"
    )
    assert preflight["summary"]["controlled_apply_final_preflight_ready_count"] == 0
    assert preflight["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert preflight["summary"]["controlled_apply_final_preflight_waiting_count"] > 0
    assert preflight["summary"]["authorization_evidence_execution_closeout_ready_count"] == 0
    assert preflight["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert preflight["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert preflight["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 0
    assert preflight["summary"]["controlled_apply_final_preflight_count"] == 1
    assert preflight["summary"]["controlled_apply_final_preflight_field_count"] == 12
    assert preflight["summary"]["controlled_apply_final_preflight_acceptance_gate_count"] == 10
    assert preflight["summary"]["rollback_binding_count"] == 1
    assert preflight["summary"]["rollback_binding_field_count"] == 8
    assert preflight["summary"]["post_apply_verifier_binding_count"] == 1
    assert preflight["summary"]["post_apply_verifier_binding_field_count"] == 8
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_migration_count"] == 0
    assert preflight["summary"]["executes_endpoint_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_preflight["controlled_apply_preflight_id"].startswith(
        "pchome-db-apply-controlled-apply-final-preflight-"
    )
    assert (
        future_preflight["ready_for_future_database_apply_controlled_apply_final_preflight"]
        is False
    )
    assert (
        future_preflight["can_enter_future_database_apply_controlled_dry_run_package"]
        is False
    )
    assert future_preflight["controlled_apply_final_preflight_ready"] is False
    assert future_preflight["rollback_binding_ready"] is False
    assert future_preflight["post_apply_verifier_binding_ready"] is False
    assert future_preflight["ready_for_database_apply_now"] is False
    assert future_preflight["database_apply_authorized"] is False
    assert future_preflight["issues_database_apply_authorization"] is False
    assert future_preflight["signs_database_apply_authorization"] is False
    assert future_preflight["executes_authorization_evidence"] is False
    assert future_preflight["executes_database_apply"] is False
    assert future_preflight["executes_endpoint"] is False
    assert future_preflight["executes_sql"] is False
    assert future_preflight["writes_database"] is False
    assert package["authorization_material_type"] == "controlled_apply_final_preflight"
    assert (
        package["ready_for_future_database_apply_controlled_apply_final_preflight"]
        is False
    )
    assert package["controlled_apply_final_preflight_field_count"] == 12
    assert package["controlled_apply_final_preflight_acceptance_gate_count"] == 10
    assert package["rollback_binding_count"] == 1
    assert package["rollback_binding_field_count"] == 8
    assert package["post_apply_verifier_binding_count"] == 1
    assert package["post_apply_verifier_binding_field_count"] == 8
    assert rollback_binding["rollback_execution_authorized"] is False
    assert rollback_binding["rollback_executes_sql"] is False
    assert rollback_binding["rollback_writes_database"] is False
    assert rollback_binding["rollback_reads_secret"] is False
    assert verifier_binding["verifier_must_run_after_apply"] is True
    assert verifier_binding["verifier_execution_authorized_in_preview"] is False
    assert verifier_binding["database_apply_authorized"] is False
    assert package["dry_run_only"] is True
    assert package["check_mode_only"] is True
    assert package["rollback_bound"] is False
    assert package["post_apply_verifier_bound"] is False
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["executes_database_apply"] is False
    assert package["executes_endpoint_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert contract["permits_future_database_apply_controlled_dry_run_package"] is False
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "final_verifier_gate_ready" in check_keys
    assert "rollback_binding_complete" in check_keys
    assert "post_apply_verifier_binding_complete" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["executes_endpoint"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False
    assert preflight["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_apply_final_preflight_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-apply-final-preflight.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    preflight = build_pchome_auto_policy_db_apply_controlled_apply_final_preflight(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_preflight = preflight["future_database_apply_controlled_apply_final_preflight"]
    package = preflight["controlled_apply_final_preflight"]
    contract = preflight["controlled_apply_final_preflight_contract"]
    rollback_binding = package["rollback_binding"]
    verifier_binding = package["post_apply_verifier_binding"]
    check_keys = [check["key"] for check in preflight["controlled_apply_final_preflight_checks"]]
    assert preflight["result"] == "DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT_READY"
    assert preflight["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert preflight["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert preflight["summary"]["controlled_apply_final_preflight_pass_count"] == 12
    assert preflight["summary"]["controlled_apply_final_preflight_waiting_count"] == 0
    assert preflight["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert preflight["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert preflight["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert preflight["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert preflight["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert preflight["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert preflight["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert preflight["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert preflight["summary"]["controlled_apply_final_preflight_count"] == 1
    assert preflight["summary"]["controlled_apply_final_preflight_field_count"] == 12
    assert preflight["summary"]["controlled_apply_final_preflight_acceptance_gate_count"] == 10
    assert preflight["summary"]["rollback_binding_count"] == 1
    assert preflight["summary"]["rollback_binding_field_count"] == 8
    assert preflight["summary"]["post_apply_verifier_binding_count"] == 1
    assert preflight["summary"]["post_apply_verifier_binding_field_count"] == 8
    assert preflight["summary"]["post_apply_verifier_required_count"] == 1
    assert preflight["summary"]["same_run_truth_required_count"] == 1
    assert preflight["summary"]["reads_secret_count"] == 0
    assert preflight["summary"]["executes_script_count"] == 0
    assert preflight["summary"]["executes_migration_count"] == 0
    assert preflight["summary"]["executes_endpoint_count"] == 0
    assert preflight["summary"]["executes_sql_count"] == 0
    assert preflight["summary"]["writes_database_count"] == 0
    assert preflight["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_preflight["controlled_apply_preflight_id"].startswith(
        "pchome-db-apply-controlled-apply-final-preflight-"
    )
    assert future_preflight["source_final_verifier_gate_id"].startswith(
        "pchome-db-apply-authorization-evidence-execution-closeout-"
    )
    assert (
        future_preflight["ready_for_future_database_apply_controlled_apply_final_preflight"]
        is True
    )
    assert (
        future_preflight["can_enter_future_database_apply_controlled_dry_run_package"]
        is True
    )
    assert future_preflight["controlled_apply_final_preflight_ready"] is True
    assert future_preflight["rollback_binding_ready"] is True
    assert future_preflight["post_apply_verifier_binding_ready"] is True
    assert future_preflight["ready_for_database_apply_now"] is False
    assert future_preflight["database_apply_authorized"] is False
    assert future_preflight["issues_database_apply_authorization"] is False
    assert future_preflight["signs_database_apply_authorization"] is False
    assert future_preflight["executes_authorization_evidence"] is False
    assert future_preflight["executes_database_apply"] is False
    assert future_preflight["executes_endpoint"] is False
    assert future_preflight["executes_sql"] is False
    assert future_preflight["writes_database"] is False
    assert package["controlled_apply_preflight_id"].startswith(
        "pchome-db-apply-controlled-apply-final-preflight-"
    )
    assert package["authorization_material_type"] == "controlled_apply_final_preflight"
    assert (
        package["ready_for_future_database_apply_controlled_apply_final_preflight"]
        is True
    )
    assert package["controlled_apply_final_preflight_field_count"] == 12
    assert package["controlled_apply_final_preflight_acceptance_gate_count"] == 10
    assert "rollback_binding_id" in package["controlled_apply_final_preflight_fields"]
    assert "post_apply_verifier_bound" in (
        package["controlled_apply_final_preflight_acceptance_gates"]
    )
    assert package["rollback_binding_count"] == 1
    assert package["rollback_binding_field_count"] == 8
    assert package["post_apply_verifier_binding_count"] == 1
    assert package["post_apply_verifier_binding_field_count"] == 8
    assert rollback_binding["rollback_execution_authorized"] is False
    assert rollback_binding["rollback_executes_sql"] is False
    assert rollback_binding["rollback_writes_database"] is False
    assert rollback_binding["rollback_reads_secret"] is False
    assert verifier_binding["verifier_must_run_after_apply"] is True
    assert verifier_binding["verifier_execution_authorized_in_preview"] is False
    assert verifier_binding["database_apply_authorized"] is False
    assert package["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert package["hash_matches"] is True
    assert package["dry_run_only"] is True
    assert package["check_mode_only"] is True
    assert package["rollback_bound"] is True
    assert package["post_apply_verifier_bound"] is True
    assert package["requires_fresh_production_truth_in_same_run"] is True
    assert package["requires_post_apply_verifier"] is True
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["executes_database_apply"] is False
    assert package["executes_endpoint_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert contract["permits_future_database_apply_controlled_dry_run_package"] is True
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "final_verifier_gate_ready" in check_keys
    assert "rollback_binding_complete" in check_keys
    assert "post_apply_verifier_binding_complete" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "final_verifier_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert preflight["safety"]["reads_secret_in_preview"] is False
    assert preflight["safety"]["executes_endpoint"] is False
    assert preflight["safety"]["executes_sql"] is False
    assert preflight["safety"]["writes_database"] is False
    assert preflight["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_package_waits_without_ready_final_preflight():
    package = build_pchome_auto_policy_db_apply_controlled_dry_run_package(
        _payload(),
        batch_size=1,
    )

    future_receipt = package[
        "future_database_apply_controlled_dry_run_execution_receipt"
    ]
    dry_run_package = package["controlled_dry_run_package"]
    receipt = dry_run_package["dry_run_execution_receipt_preview"]
    command_shape = dry_run_package["dry_run_command_shape"]
    contract = package["controlled_dry_run_package_contract"]
    check_keys = [check["key"] for check in package["controlled_dry_run_package_checks"]]
    assert package["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_package"
    )
    assert package["result"] == "WAITING_FOR_DB_APPLY_CONTROLLED_APPLY_FINAL_PREFLIGHT"
    assert package["summary"]["controlled_dry_run_package_ready_count"] == 0
    assert package["summary"]["controlled_dry_run_package_check_count"] == 12
    assert package["summary"]["controlled_dry_run_package_waiting_count"] > 0
    assert package["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert package["summary"]["controlled_apply_final_preflight_ready_count"] == 0
    assert package["summary"]["controlled_dry_run_package_count"] == 1
    assert package["summary"]["controlled_dry_run_package_field_count"] == 12
    assert package["summary"]["controlled_dry_run_acceptance_gate_count"] == 10
    assert package["summary"]["dry_run_execution_receipt_preview_count"] == 1
    assert package["summary"]["dry_run_execution_receipt_field_count"] == 8
    assert package["summary"]["rollback_binding_count"] == 1
    assert package["summary"]["post_apply_verifier_binding_count"] == 1
    assert package["summary"]["reads_secret_count"] == 0
    assert package["summary"]["executes_script_count"] == 0
    assert package["summary"]["executes_migration_count"] == 0
    assert package["summary"]["executes_endpoint_count"] == 0
    assert package["summary"]["executes_sql_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert package["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_receipt["dry_run_package_id"].startswith(
        "pchome-db-apply-controlled-dry-run-package-"
    )
    assert (
        future_receipt[
            "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is False
    )
    assert (
        future_receipt[
            "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is False
    )
    assert future_receipt["controlled_dry_run_package_ready"] is False
    assert future_receipt["dry_run_execution_performed"] is False
    assert future_receipt["ready_for_database_apply_now"] is False
    assert future_receipt["database_apply_authorized"] is False
    assert future_receipt["issues_database_apply_authorization"] is False
    assert future_receipt["signs_database_apply_authorization"] is False
    assert future_receipt["executes_authorization_evidence"] is False
    assert future_receipt["executes_database_apply"] is False
    assert future_receipt["executes_endpoint"] is False
    assert future_receipt["executes_sql"] is False
    assert future_receipt["writes_database"] is False
    assert dry_run_package["authorization_material_type"] == "controlled_dry_run_package"
    assert (
        dry_run_package["ready_for_future_database_apply_controlled_dry_run_package"]
        is False
    )
    assert dry_run_package["controlled_dry_run_package_field_count"] == 12
    assert dry_run_package["controlled_dry_run_acceptance_gate_count"] == 10
    assert dry_run_package["dry_run_execution_receipt_preview_count"] == 1
    assert dry_run_package["dry_run_execution_receipt_field_count"] == 8
    assert dry_run_package["rollback_binding_count"] == 1
    assert dry_run_package["post_apply_verifier_binding_count"] == 1
    assert command_shape["dry_run_only"] is True
    assert command_shape["check_mode_only"] is True
    assert command_shape["execution_allowed"] is False
    assert command_shape["shell_command_included"] is False
    assert command_shape["sql_included"] is False
    assert command_shape["endpoint_execution_included"] is False
    assert command_shape["database_write_included"] is False
    assert command_shape["requires_fresh_production_truth_in_same_run"] is True
    assert command_shape["requires_rollback_binding"] is True
    assert command_shape["requires_post_apply_verifier_binding"] is True
    assert receipt["receipt_id"].endswith("-dry-run-receipt-preview")
    assert receipt["dry_run_status"] == "preview_only_not_executed"
    assert receipt["execution_performed"] is False
    assert receipt["stdout_included"] is False
    assert receipt["stderr_included"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_shell"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert receipt["reads_secret"] is False
    assert receipt["receipt_field_count"] == 8
    assert dry_run_package["dry_run_only"] is True
    assert dry_run_package["check_mode_only"] is True
    assert dry_run_package["accepts_plaintext_secret"] is False
    assert dry_run_package["reads_secret_in_preview"] is False
    assert dry_run_package["signature_material_included"] is False
    assert dry_run_package["secret_material_included"] is False
    assert dry_run_package["signs_database_apply_authorization"] is False
    assert dry_run_package["executes_authorization_evidence"] is False
    assert dry_run_package["executes_database_apply"] is False
    assert dry_run_package["executes_endpoint_in_preview"] is False
    assert dry_run_package["executes_sql_in_preview"] is False
    assert dry_run_package["writes_database_in_preview"] is False
    assert dry_run_package["ready_for_database_apply_now"] is False
    assert dry_run_package["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is False
    )
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "controlled_apply_final_preflight_ready" in check_keys
    assert "dry_run_command_shape_preview_only" in check_keys
    assert "dry_run_execution_receipt_preview_only" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert package["safety"]["reads_secret_in_preview"] is False
    assert package["safety"]["executes_endpoint"] is False
    assert package["safety"]["executes_sql"] is False
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_package_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-package.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    package = build_pchome_auto_policy_db_apply_controlled_dry_run_package(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_receipt = package[
        "future_database_apply_controlled_dry_run_execution_receipt"
    ]
    dry_run_package = package["controlled_dry_run_package"]
    receipt = dry_run_package["dry_run_execution_receipt_preview"]
    command_shape = dry_run_package["dry_run_command_shape"]
    contract = package["controlled_dry_run_package_contract"]
    check_keys = [check["key"] for check in package["controlled_dry_run_package_checks"]]
    assert package["result"] == "DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE_READY"
    assert package["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert package["summary"]["controlled_dry_run_package_check_count"] == 12
    assert package["summary"]["controlled_dry_run_package_pass_count"] == 12
    assert package["summary"]["controlled_dry_run_package_waiting_count"] == 0
    assert package["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert package["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert package["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert package["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert package["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert package["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert package["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert package["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert package["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert package["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert package["summary"]["controlled_dry_run_package_count"] == 1
    assert package["summary"]["controlled_dry_run_package_field_count"] == 12
    assert package["summary"]["controlled_dry_run_acceptance_gate_count"] == 10
    assert package["summary"]["dry_run_execution_receipt_preview_count"] == 1
    assert package["summary"]["dry_run_execution_receipt_field_count"] == 8
    assert package["summary"]["controlled_apply_final_preflight_count"] == 1
    assert package["summary"]["rollback_binding_count"] == 1
    assert package["summary"]["post_apply_verifier_binding_count"] == 1
    assert package["summary"]["post_apply_verifier_required_count"] == 1
    assert package["summary"]["same_run_truth_required_count"] == 1
    assert package["summary"]["reads_secret_count"] == 0
    assert package["summary"]["executes_script_count"] == 0
    assert package["summary"]["executes_migration_count"] == 0
    assert package["summary"]["executes_endpoint_count"] == 0
    assert package["summary"]["executes_sql_count"] == 0
    assert package["summary"]["writes_database_count"] == 0
    assert package["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_receipt["dry_run_package_id"].startswith(
        "pchome-db-apply-controlled-dry-run-package-"
    )
    assert (
        future_receipt[
            "ready_for_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is True
    )
    assert (
        future_receipt[
            "can_enter_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is True
    )
    assert future_receipt["controlled_dry_run_package_ready"] is True
    assert future_receipt["dry_run_execution_performed"] is False
    assert future_receipt["ready_for_database_apply_now"] is False
    assert future_receipt["database_apply_authorized"] is False
    assert future_receipt["issues_database_apply_authorization"] is False
    assert future_receipt["signs_database_apply_authorization"] is False
    assert future_receipt["executes_authorization_evidence"] is False
    assert future_receipt["executes_database_apply"] is False
    assert future_receipt["executes_endpoint"] is False
    assert future_receipt["executes_sql"] is False
    assert future_receipt["writes_database"] is False
    assert dry_run_package["authorization_material_type"] == "controlled_dry_run_package"
    assert (
        dry_run_package["ready_for_future_database_apply_controlled_dry_run_package"]
        is True
    )
    assert dry_run_package["controlled_dry_run_package_field_count"] == 12
    assert dry_run_package["controlled_dry_run_acceptance_gate_count"] == 10
    assert "dry_run_execution_receipt_id" in (
        dry_run_package["controlled_dry_run_package_fields"]
    )
    assert "dry_run_receipt_preview_only" in (
        dry_run_package["controlled_dry_run_acceptance_gates"]
    )
    assert dry_run_package["dry_run_execution_receipt_preview_count"] == 1
    assert dry_run_package["dry_run_execution_receipt_field_count"] == 8
    assert dry_run_package["rollback_binding_count"] == 1
    assert dry_run_package["post_apply_verifier_binding_count"] == 1
    assert dry_run_package["target_file"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert dry_run_package["hash_matches"] is True
    assert dry_run_package["target_migration_hash_locked"] is True
    assert command_shape["dry_run_only"] is True
    assert command_shape["check_mode_only"] is True
    assert command_shape["execution_allowed"] is False
    assert command_shape["shell_command_included"] is False
    assert command_shape["sql_included"] is False
    assert command_shape["endpoint_execution_included"] is False
    assert command_shape["database_write_included"] is False
    assert command_shape["requires_fresh_production_truth_in_same_run"] is True
    assert command_shape["requires_rollback_binding"] is True
    assert command_shape["requires_post_apply_verifier_binding"] is True
    assert receipt["receipt_id"].endswith("-dry-run-receipt-preview")
    assert receipt["source_dry_run_package_id"] == dry_run_package["dry_run_package_id"]
    assert receipt["dry_run_status"] == "preview_only_not_executed"
    assert receipt["dry_run_command_shape_hash"] == (
        dry_run_package["dry_run_command_shape_hash"]
    )
    assert receipt["execution_performed"] is False
    assert receipt["stdout_included"] is False
    assert receipt["stderr_included"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_shell"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert receipt["reads_secret"] is False
    assert receipt["receipt_field_count"] == 8
    assert dry_run_package["dry_run_only"] is True
    assert dry_run_package["check_mode_only"] is True
    assert dry_run_package["requires_fresh_production_truth_in_same_run"] is True
    assert dry_run_package["requires_post_apply_verifier"] is True
    assert dry_run_package["accepts_plaintext_secret"] is False
    assert dry_run_package["reads_secret_in_preview"] is False
    assert dry_run_package["signature_material_included"] is False
    assert dry_run_package["secret_material_included"] is False
    assert dry_run_package["signs_database_apply_authorization"] is False
    assert dry_run_package["executes_authorization_evidence"] is False
    assert dry_run_package["executes_database_apply"] is False
    assert dry_run_package["executes_endpoint_in_preview"] is False
    assert dry_run_package["executes_sql_in_preview"] is False
    assert dry_run_package["writes_database_in_preview"] is False
    assert dry_run_package["ready_for_database_apply_now"] is False
    assert dry_run_package["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_receipt"
        ]
        is True
    )
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "controlled_apply_final_preflight_ready" in check_keys
    assert "rollback_binding_carried_forward" in check_keys
    assert "post_apply_verifier_binding_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "dry_run_command_shape_preview_only" in check_keys
    assert "dry_run_execution_receipt_preview_only" in check_keys
    assert "final_preflight_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert package["safety"]["reads_secret_in_preview"] is False
    assert package["safety"]["executes_endpoint"] is False
    assert package["safety"]["executes_sql"] is False
    assert package["safety"]["writes_database"] is False
    assert package["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_receipt_closeout_waits_without_ready_package():
    closeout = build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_closeout(
        _payload(),
        batch_size=1,
    )

    future_verification = closeout[
        "future_database_apply_controlled_dry_run_result_parser_verification"
    ]
    receipt_closeout = closeout["controlled_dry_run_receipt_closeout"]
    parser = receipt_closeout["dry_run_result_parser"]
    validation = receipt_closeout["receipt_validation_report"]
    contract = closeout["controlled_dry_run_receipt_closeout_contract"]
    check_keys = [
        check["key"] for check in closeout["controlled_dry_run_receipt_closeout_checks"]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_receipt_closeout"
    )
    assert closeout["result"] == "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_PACKAGE"
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_waiting_count"] > 0
    assert closeout["summary"]["controlled_dry_run_package_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["dry_run_result_parser_count"] == 1
    assert closeout["summary"]["dry_run_result_parser_field_count"] == 10
    assert closeout["summary"]["receipt_validation_report_count"] == 1
    assert closeout["summary"]["receipt_validation_field_count"] == 8
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_verification["receipt_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-receipt-closeout-"
    )
    assert (
        future_verification[
            "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
        ]
        is False
    )
    assert (
        future_verification[
            "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is False
    )
    assert future_verification["controlled_dry_run_receipt_closeout_ready"] is False
    assert future_verification["dry_run_execution_performed"] is False
    assert future_verification["ready_for_database_apply_now"] is False
    assert future_verification["database_apply_authorized"] is False
    assert future_verification["executes_database_apply"] is False
    assert future_verification["executes_endpoint"] is False
    assert future_verification["executes_sql"] is False
    assert future_verification["writes_database"] is False
    assert receipt_closeout["authorization_material_type"] == (
        "controlled_dry_run_receipt_closeout"
    )
    assert (
        receipt_closeout[
            "ready_for_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is False
    )
    assert receipt_closeout["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert (
        receipt_closeout[
            "controlled_dry_run_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert parser["expected_receipt_status"] == "preview_only_not_executed"
    assert parser["execution_required"] is False
    assert parser["stdout_allowed"] is False
    assert parser["stderr_allowed"] is False
    assert parser["database_apply_authorized"] is False
    assert parser["parser_field_count"] == 10
    assert validation["receipt_validation_field_count"] == 8
    assert validation["execution_performed"] is False
    assert validation["stdout_included"] is False
    assert validation["stderr_included"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_shell"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert validation["reads_secret"] is False
    assert receipt_closeout["receipt_preview_only"] is True
    assert receipt_closeout["dry_run_only"] is True
    assert receipt_closeout["check_mode_only"] is True
    assert receipt_closeout["accepts_plaintext_secret"] is False
    assert receipt_closeout["reads_secret_in_preview"] is False
    assert receipt_closeout["signature_material_included"] is False
    assert receipt_closeout["secret_material_included"] is False
    assert receipt_closeout["signs_database_apply_authorization"] is False
    assert receipt_closeout["executes_authorization_evidence"] is False
    assert receipt_closeout["executes_database_apply"] is False
    assert receipt_closeout["executes_endpoint_in_preview"] is False
    assert receipt_closeout["executes_sql_in_preview"] is False
    assert receipt_closeout["writes_database_in_preview"] is False
    assert receipt_closeout["ready_for_database_apply_now"] is False
    assert receipt_closeout["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is False
    )
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "controlled_dry_run_package_ready" in check_keys
    assert "dry_run_result_parser_schema_complete" in check_keys
    assert "receipt_preview_schema_matches_parser" in check_keys
    assert "command_shape_hash_matches_receipt" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_receipt_closeout_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-receipt-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_closeout(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_verification = closeout[
        "future_database_apply_controlled_dry_run_result_parser_verification"
    ]
    receipt_closeout = closeout["controlled_dry_run_receipt_closeout"]
    parser = receipt_closeout["dry_run_result_parser"]
    validation = receipt_closeout["receipt_validation_report"]
    contract = closeout["controlled_dry_run_receipt_closeout_contract"]
    check_keys = [
        check["key"] for check in closeout["controlled_dry_run_receipt_closeout_checks"]
    ]
    assert closeout["result"] == "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT_READY"
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_check_count"] == 12
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_verifier_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert closeout["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["dry_run_result_parser_count"] == 1
    assert closeout["summary"]["dry_run_result_parser_field_count"] == 10
    assert closeout["summary"]["receipt_validation_report_count"] == 1
    assert closeout["summary"]["receipt_validation_field_count"] == 8
    assert closeout["summary"]["dry_run_execution_receipt_preview_count"] == 1
    assert closeout["summary"]["dry_run_execution_receipt_field_count"] == 8
    assert closeout["summary"]["controlled_dry_run_package_count"] == 1
    assert closeout["summary"]["rollback_binding_count"] == 1
    assert closeout["summary"]["post_apply_verifier_binding_count"] == 1
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_verification["receipt_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-receipt-closeout-"
    )
    assert (
        future_verification[
            "ready_for_future_database_apply_controlled_dry_run_result_parser_verification"
        ]
        is True
    )
    assert (
        future_verification[
            "can_enter_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is True
    )
    assert future_verification["controlled_dry_run_receipt_closeout_ready"] is True
    assert future_verification["receipt_validation_status"] == (
        "preview_validated_not_executed"
    )
    assert future_verification["dry_run_execution_performed"] is False
    assert future_verification["ready_for_database_apply_now"] is False
    assert future_verification["database_apply_authorized"] is False
    assert future_verification["executes_database_apply"] is False
    assert future_verification["executes_endpoint"] is False
    assert future_verification["executes_sql"] is False
    assert future_verification["writes_database"] is False
    assert receipt_closeout["authorization_material_type"] == (
        "controlled_dry_run_receipt_closeout"
    )
    assert (
        receipt_closeout[
            "ready_for_future_database_apply_controlled_dry_run_receipt_closeout"
        ]
        is True
    )
    assert receipt_closeout["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert (
        receipt_closeout[
            "controlled_dry_run_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert "dry_run_result_parser_id" in (
        receipt_closeout["controlled_dry_run_receipt_closeout_fields"]
    )
    assert "receipt_preview_schema_match" in (
        receipt_closeout["controlled_dry_run_receipt_closeout_acceptance_gates"]
    )
    assert parser["parser_id"] == receipt_closeout["dry_run_result_parser_id"]
    assert parser["expected_receipt_status"] == "preview_only_not_executed"
    assert parser["required_command_shape_hash"] == (
        receipt_closeout["dry_run_command_shape_hash"]
    )
    assert parser["execution_required"] is False
    assert parser["stdout_allowed"] is False
    assert parser["stderr_allowed"] is False
    assert parser["database_apply_authorized"] is False
    assert parser["parser_field_count"] == 10
    assert validation["receipt_validation_status"] == "preview_validated_not_executed"
    assert validation["receipt_validation_field_count"] == 8
    assert validation["dry_run_command_shape_hash"] == (
        receipt_closeout["dry_run_command_shape_hash"]
    )
    assert validation["execution_performed"] is False
    assert validation["stdout_included"] is False
    assert validation["stderr_included"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_shell"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert validation["reads_secret"] is False
    assert receipt_closeout["target_file"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert receipt_closeout["hash_matches"] is True
    assert receipt_closeout["target_migration_hash_locked"] is True
    assert receipt_closeout["receipt_preview_only"] is True
    assert receipt_closeout["dry_run_only"] is True
    assert receipt_closeout["check_mode_only"] is True
    assert receipt_closeout["requires_fresh_production_truth_in_same_run"] is True
    assert receipt_closeout["requires_post_apply_verifier"] is True
    assert receipt_closeout["accepts_plaintext_secret"] is False
    assert receipt_closeout["reads_secret_in_preview"] is False
    assert receipt_closeout["signature_material_included"] is False
    assert receipt_closeout["secret_material_included"] is False
    assert receipt_closeout["signs_database_apply_authorization"] is False
    assert receipt_closeout["executes_authorization_evidence"] is False
    assert receipt_closeout["executes_database_apply"] is False
    assert receipt_closeout["executes_endpoint_in_preview"] is False
    assert receipt_closeout["executes_sql_in_preview"] is False
    assert receipt_closeout["writes_database_in_preview"] is False
    assert receipt_closeout["ready_for_database_apply_now"] is False
    assert receipt_closeout["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_runner_readiness"
        ]
        is True
    )
    assert contract["executes_authorization_evidence"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["signs_database_apply_authorization"] is False
    assert contract["writes_database"] is False
    assert "controlled_dry_run_package_ready" in check_keys
    assert "dry_run_result_parser_schema_complete" in check_keys
    assert "receipt_preview_schema_matches_parser" in check_keys
    assert "command_shape_hash_matches_receipt" in check_keys
    assert "receipt_preview_only_not_executed" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "package_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_readiness_waits_without_ready_receipt_closeout():
    readiness = build_pchome_auto_policy_db_apply_controlled_dry_run_runner_readiness(
        _payload(),
        batch_size=1,
    )

    future_plan = readiness[
        "future_database_apply_controlled_dry_run_execution_plan_binding"
    ]
    runner = readiness["controlled_dry_run_runner_readiness"]
    plan = runner["execution_plan_binding"]
    validation = runner["receipt_validation_report"]
    parser = runner["dry_run_result_parser"]
    contract = readiness["controlled_dry_run_runner_readiness_contract"]
    check_keys = [
        check["key"] for check in readiness["controlled_dry_run_runner_readiness_checks"]
    ]
    assert readiness["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_readiness"
    )
    assert readiness["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_CLOSEOUT"
    )
    assert readiness["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 0
    assert readiness["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert readiness["summary"]["controlled_dry_run_runner_readiness_waiting_count"] > 0
    assert readiness["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert readiness["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 0
    assert readiness["summary"]["controlled_dry_run_runner_readiness_count"] == 1
    assert readiness["summary"]["controlled_dry_run_runner_readiness_field_count"] == 12
    assert (
        readiness["summary"][
            "controlled_dry_run_runner_readiness_acceptance_gate_count"
        ]
        == 10
    )
    assert readiness["summary"]["execution_plan_binding_count"] == 1
    assert readiness["summary"]["execution_plan_binding_field_count"] == 12
    assert readiness["summary"]["dry_run_result_parser_count"] == 1
    assert readiness["summary"]["dry_run_result_parser_field_count"] == 10
    assert readiness["summary"]["receipt_validation_report_count"] == 1
    assert readiness["summary"]["receipt_validation_field_count"] == 8
    assert readiness["summary"]["reads_secret_count"] == 0
    assert readiness["summary"]["executes_endpoint_count"] == 0
    assert readiness["summary"]["executes_sql_count"] == 0
    assert readiness["summary"]["writes_database_count"] == 0
    assert readiness["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_plan["runner_readiness_id"].startswith(
        "pchome-db-apply-controlled-dry-run-runner-readiness-"
    )
    assert (
        future_plan[
            "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding"
        ]
        is False
    )
    assert (
        future_plan[
            "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout"
        ]
        is False
    )
    assert future_plan["controlled_dry_run_runner_readiness_ready"] is False
    assert future_plan["execution_plan_bound"] is False
    assert future_plan["dry_run_execution_performed"] is False
    assert future_plan["runner_execution_authorized"] is False
    assert future_plan["dry_run_execution_authorized"] is False
    assert future_plan["ready_for_database_apply_now"] is False
    assert future_plan["database_apply_authorized"] is False
    assert future_plan["executes_database_apply"] is False
    assert future_plan["executes_endpoint"] is False
    assert future_plan["executes_sql"] is False
    assert future_plan["writes_database"] is False
    assert runner["authorization_material_type"] == "controlled_dry_run_runner_readiness"
    assert (
        runner["ready_for_future_database_apply_controlled_dry_run_runner_readiness"]
        is False
    )
    assert runner["controlled_dry_run_runner_readiness_field_count"] == 12
    assert runner["controlled_dry_run_runner_readiness_acceptance_gate_count"] == 10
    assert runner["execution_plan_binding_count"] == 1
    assert runner["execution_plan_binding_field_count"] == 12
    assert plan["runner_mode"] == "future_controlled_dry_run_runner_readiness_only"
    assert plan["plan_status"] == "plan_binding_preview_not_executable"
    assert plan["dry_run_only"] is True
    assert plan["check_mode_only"] is True
    assert plan["execution_authorized"] is False
    assert plan["dry_run_execution_authorized"] is False
    assert plan["runner_execution_authorized"] is False
    assert plan["shell_execution_included"] is False
    assert plan["endpoint_execution_included"] is False
    assert plan["sql_execution_included"] is False
    assert plan["database_write_included"] is False
    assert plan["stdout_capture_allowed"] is False
    assert plan["stderr_capture_allowed"] is False
    assert plan["database_apply_authorized"] is False
    assert plan["ready_for_database_apply_now"] is False
    assert parser["execution_required"] is False
    assert parser["database_apply_authorized"] is False
    assert validation["execution_performed"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert runner["runner_readiness_only"] is True
    assert runner["execution_plan_preview_only"] is True
    assert runner["runner_execution_authorized"] is False
    assert runner["dry_run_execution_authorized"] is False
    assert runner["accepts_plaintext_secret"] is False
    assert runner["reads_secret_in_preview"] is False
    assert runner["signature_material_included"] is False
    assert runner["secret_material_included"] is False
    assert runner["signs_database_apply_authorization"] is False
    assert runner["executes_authorization_evidence"] is False
    assert runner["executes_database_apply"] is False
    assert runner["executes_endpoint_in_preview"] is False
    assert runner["executes_sql_in_preview"] is False
    assert runner["writes_database_in_preview"] is False
    assert runner["ready_for_database_apply_now"] is False
    assert runner["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_plan_binding"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "receipt_closeout_ready" in check_keys
    assert "execution_plan_binding_preview_only" in check_keys
    assert "runner_execution_gate_closed" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert readiness["safety"]["reads_secret_in_preview"] is False
    assert readiness["safety"]["executes_endpoint"] is False
    assert readiness["safety"]["executes_sql"] is False
    assert readiness["safety"]["writes_database"] is False
    assert readiness["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_readiness_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-runner-readiness.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    readiness = build_pchome_auto_policy_db_apply_controlled_dry_run_runner_readiness(
        _payload(),
        batch_size=1,
        execute_fetch=True,
        http_get=fake_get,
    )

    future_plan = readiness[
        "future_database_apply_controlled_dry_run_execution_plan_binding"
    ]
    runner = readiness["controlled_dry_run_runner_readiness"]
    plan = runner["execution_plan_binding"]
    validation = runner["receipt_validation_report"]
    parser = runner["dry_run_result_parser"]
    contract = readiness["controlled_dry_run_runner_readiness_contract"]
    check_keys = [
        check["key"] for check in readiness["controlled_dry_run_runner_readiness_checks"]
    ]
    assert readiness["result"] == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS_READY"
    assert readiness["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert readiness["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert readiness["summary"]["controlled_dry_run_runner_readiness_pass_count"] == 12
    assert readiness["summary"]["controlled_dry_run_runner_readiness_waiting_count"] == 0
    assert readiness["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert readiness["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert readiness["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert readiness["summary"]["controlled_dry_run_package_check_count"] == 12
    assert readiness["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert readiness["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert readiness["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert readiness["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert readiness["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert readiness["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert readiness["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert readiness["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert readiness["summary"]["controlled_dry_run_runner_readiness_count"] == 1
    assert readiness["summary"]["controlled_dry_run_runner_readiness_field_count"] == 12
    assert (
        readiness["summary"][
            "controlled_dry_run_runner_readiness_acceptance_gate_count"
        ]
        == 10
    )
    assert readiness["summary"]["execution_plan_binding_count"] == 1
    assert readiness["summary"]["execution_plan_binding_field_count"] == 12
    assert readiness["summary"]["dry_run_result_parser_count"] == 1
    assert readiness["summary"]["dry_run_result_parser_field_count"] == 10
    assert readiness["summary"]["receipt_validation_report_count"] == 1
    assert readiness["summary"]["receipt_validation_field_count"] == 8
    assert readiness["summary"]["controlled_dry_run_receipt_closeout_count"] == 1
    assert readiness["summary"]["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert (
        readiness["summary"][
            "controlled_dry_run_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert readiness["summary"]["rollback_binding_count"] == 1
    assert readiness["summary"]["post_apply_verifier_binding_count"] == 1
    assert readiness["summary"]["post_apply_verifier_required_count"] == 1
    assert readiness["summary"]["same_run_truth_required_count"] == 1
    assert readiness["summary"]["reads_secret_count"] == 0
    assert readiness["summary"]["executes_endpoint_count"] == 0
    assert readiness["summary"]["executes_sql_count"] == 0
    assert readiness["summary"]["writes_database_count"] == 0
    assert readiness["summary"]["signs_database_apply_authorization_count"] == 0
    assert future_plan["runner_readiness_id"].startswith(
        "pchome-db-apply-controlled-dry-run-runner-readiness-"
    )
    assert (
        future_plan[
            "ready_for_future_database_apply_controlled_dry_run_execution_plan_binding"
        ]
        is True
    )
    assert (
        future_plan[
            "can_enter_future_database_apply_controlled_dry_run_execution_plan_closeout"
        ]
        is True
    )
    assert future_plan["controlled_dry_run_runner_readiness_ready"] is True
    assert future_plan["execution_plan_bound"] is True
    assert future_plan["dry_run_execution_performed"] is False
    assert future_plan["runner_execution_authorized"] is False
    assert future_plan["dry_run_execution_authorized"] is False
    assert future_plan["ready_for_database_apply_now"] is False
    assert future_plan["database_apply_authorized"] is False
    assert future_plan["executes_database_apply"] is False
    assert future_plan["executes_endpoint"] is False
    assert future_plan["executes_sql"] is False
    assert future_plan["writes_database"] is False
    assert runner["authorization_material_type"] == "controlled_dry_run_runner_readiness"
    assert (
        runner["ready_for_future_database_apply_controlled_dry_run_runner_readiness"]
        is True
    )
    assert runner["controlled_dry_run_runner_readiness_field_count"] == 12
    assert runner["controlled_dry_run_runner_readiness_acceptance_gate_count"] == 10
    assert "execution_plan_binding_id" in (
        runner["controlled_dry_run_runner_readiness_fields"]
    )
    assert "execution_plan_binding_preview_only" in (
        runner["controlled_dry_run_runner_readiness_acceptance_gates"]
    )
    assert runner["execution_plan_binding_count"] == 1
    assert runner["execution_plan_binding_field_count"] == 12
    assert plan["execution_plan_binding_id"] == future_plan["execution_plan_binding_id"]
    assert plan["runner_mode"] == "future_controlled_dry_run_runner_readiness_only"
    assert plan["plan_status"] == "plan_binding_preview_not_executable"
    assert plan["dry_run_only"] is True
    assert plan["check_mode_only"] is True
    assert plan["execution_authorized"] is False
    assert plan["dry_run_execution_authorized"] is False
    assert plan["runner_execution_authorized"] is False
    assert plan["shell_execution_included"] is False
    assert plan["endpoint_execution_included"] is False
    assert plan["sql_execution_included"] is False
    assert plan["database_write_included"] is False
    assert plan["stdout_capture_allowed"] is False
    assert plan["stderr_capture_allowed"] is False
    assert plan["database_apply_authorized"] is False
    assert plan["ready_for_database_apply_now"] is False
    assert parser["required_command_shape_hash"] == runner["dry_run_command_shape_hash"]
    assert parser["execution_required"] is False
    assert parser["database_apply_authorized"] is False
    assert validation["receipt_validation_status"] == "preview_validated_not_executed"
    assert validation["dry_run_command_shape_hash"] == runner["dry_run_command_shape_hash"]
    assert validation["execution_performed"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert runner["target_file"] == "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    assert runner["hash_matches"] is True
    assert runner["target_migration_hash_locked"] is True
    assert runner["runner_readiness_only"] is True
    assert runner["execution_plan_preview_only"] is True
    assert runner["runner_execution_authorized"] is False
    assert runner["dry_run_execution_authorized"] is False
    assert runner["accepts_plaintext_secret"] is False
    assert runner["reads_secret_in_preview"] is False
    assert runner["signature_material_included"] is False
    assert runner["secret_material_included"] is False
    assert runner["signs_database_apply_authorization"] is False
    assert runner["executes_authorization_evidence"] is False
    assert runner["executes_database_apply"] is False
    assert runner["executes_endpoint_in_preview"] is False
    assert runner["executes_sql_in_preview"] is False
    assert runner["writes_database_in_preview"] is False
    assert runner["ready_for_database_apply_now"] is False
    assert runner["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_plan_binding"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "receipt_closeout_ready" in check_keys
    assert "dry_run_result_parser_verified" in check_keys
    assert "receipt_validation_report_ready" in check_keys
    assert "command_shape_hash_bound" in check_keys
    assert "execution_plan_binding_preview_only" in check_keys
    assert "runner_execution_gate_closed" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert readiness["safety"]["reads_secret_in_preview"] is False
    assert readiness["safety"]["executes_endpoint"] is False
    assert readiness["safety"]["executes_sql"] is False
    assert readiness["safety"]["writes_database"] is False
    assert readiness["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout_waits_without_ready_runner_readiness():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_command_artifact_verification"
    ]
    plan_closeout = closeout["controlled_dry_run_execution_plan_closeout"]
    artifact = plan_closeout["non_executable_command_artifact"]
    contract = closeout["controlled_dry_run_execution_plan_closeout_contract"]
    check_keys = [
        check["key"]
        for check in closeout["controlled_dry_run_execution_plan_closeout_checks"]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_READINESS"
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_ready_count"
        ]
        == 0
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_check_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_waiting_count"
        ]
        > 0
    )
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_count"] == 1
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_field_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert closeout["summary"]["non_executable_command_artifact_count"] == 1
    assert closeout["summary"]["non_executable_command_artifact_field_count"] == 10
    assert closeout["summary"]["execution_plan_binding_count"] == 1
    assert closeout["summary"]["execution_plan_binding_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["execution_plan_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-execution-plan-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_command_artifact_verification"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_command_artifact_closeout"
        ]
        is False
    )
    assert future["execution_plan_closeout_ready"] is False
    assert future["non_executable_command_artifact_verified"] is False
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert plan_closeout["authorization_material_type"] == (
        "controlled_dry_run_execution_plan_closeout"
    )
    assert (
        plan_closeout[
            "ready_for_future_database_apply_controlled_dry_run_execution_plan_closeout"
        ]
        is False
    )
    assert plan_closeout["execution_plan_closeout_field_count"] == 12
    assert plan_closeout["execution_plan_closeout_acceptance_gate_count"] == 10
    assert plan_closeout["non_executable_command_artifact_count"] == 1
    assert plan_closeout["non_executable_command_artifact_field_count"] == 10
    assert plan_closeout["execution_plan_closeout_only"] is True
    assert plan_closeout["non_executable_command_artifact_only"] is True
    assert plan_closeout["runner_execution_authorized"] is False
    assert plan_closeout["dry_run_execution_authorized"] is False
    assert plan_closeout["execution_authorized"] is False
    assert plan_closeout["accepts_plaintext_secret"] is False
    assert plan_closeout["reads_secret_in_preview"] is False
    assert plan_closeout["signature_material_included"] is False
    assert plan_closeout["secret_material_included"] is False
    assert plan_closeout["signs_database_apply_authorization"] is False
    assert plan_closeout["executes_authorization_evidence"] is False
    assert plan_closeout["executes_database_apply"] is False
    assert plan_closeout["executes_endpoint_in_preview"] is False
    assert plan_closeout["executes_sql_in_preview"] is False
    assert plan_closeout["writes_database_in_preview"] is False
    assert plan_closeout["ready_for_database_apply_now"] is False
    assert plan_closeout["database_apply_authorized"] is False
    assert artifact["artifact_type"] == "non_executable_command_artifact_reference"
    assert artifact["command_text_included"] is False
    assert artifact["argv_included"] is False
    assert artifact.get("command_text") is None
    assert artifact.get("argv") is None
    assert artifact["shell_command_included"] is False
    assert artifact["endpoint_execution_included"] is False
    assert artifact["sql_execution_included"] is False
    assert artifact["database_write_included"] is False
    assert artifact["execution_authorized"] is False
    assert artifact["database_apply_authorized"] is False
    assert len(artifact["non_executable_command_artifact_sha256"]) == 64
    assert contract[
        "permits_future_database_apply_controlled_dry_run_command_artifact_verification"
    ] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "runner_readiness_ready" in check_keys
    assert "non_executable_command_artifact_bound" in check_keys
    assert "command_artifact_hash_locked" in check_keys
    assert "runner_execution_gate_closed" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-execution-plan-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_command_artifact_verification"
    ]
    plan_closeout = closeout["controlled_dry_run_execution_plan_closeout"]
    plan = plan_closeout["execution_plan_binding"]
    artifact = plan_closeout["non_executable_command_artifact"]
    validation = plan_closeout["receipt_validation_report"]
    parser = plan_closeout["dry_run_result_parser"]
    contract = closeout["controlled_dry_run_execution_plan_closeout_contract"]
    check_keys = [
        check["key"]
        for check in closeout["controlled_dry_run_execution_plan_closeout_checks"]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT_READY"
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_ready_count"
        ]
        == 1
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_check_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_pass_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_waiting_count"
        ]
        == 0
    )
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_check_count"] == 12
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert closeout["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert closeout["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_count"] == 1
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_field_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_execution_plan_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert closeout["summary"]["non_executable_command_artifact_count"] == 1
    assert closeout["summary"]["non_executable_command_artifact_field_count"] == 10
    assert closeout["summary"]["execution_plan_binding_count"] == 1
    assert closeout["summary"]["execution_plan_binding_field_count"] == 12
    assert closeout["summary"]["dry_run_result_parser_count"] == 1
    assert closeout["summary"]["dry_run_result_parser_field_count"] == 10
    assert closeout["summary"]["receipt_validation_report_count"] == 1
    assert closeout["summary"]["receipt_validation_field_count"] == 8
    assert closeout["summary"]["rollback_binding_count"] == 1
    assert closeout["summary"]["post_apply_verifier_binding_count"] == 1
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["execution_plan_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-execution-plan-closeout-"
    )
    assert future["non_executable_command_artifact_id"] == artifact["artifact_id"]
    assert (
        future["non_executable_command_artifact_sha256"]
        == artifact["non_executable_command_artifact_sha256"]
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_command_artifact_verification"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_command_artifact_closeout"
        ]
        is True
    )
    assert future["execution_plan_closeout_ready"] is True
    assert future["non_executable_command_artifact_verified"] is True
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert plan_closeout["authorization_material_type"] == (
        "controlled_dry_run_execution_plan_closeout"
    )
    assert (
        plan_closeout[
            "ready_for_future_database_apply_controlled_dry_run_execution_plan_closeout"
        ]
        is True
    )
    assert plan_closeout["execution_plan_closeout_field_count"] == 12
    assert plan_closeout["execution_plan_closeout_acceptance_gate_count"] == 10
    assert "non_executable_command_artifact_id" in (
        plan_closeout["execution_plan_closeout_fields"]
    )
    assert "non_executable_command_artifact_bound" in (
        plan_closeout["execution_plan_closeout_acceptance_gates"]
    )
    assert plan_closeout["non_executable_command_artifact_count"] == 1
    assert plan_closeout["non_executable_command_artifact_field_count"] == 10
    assert len(plan_closeout["non_executable_command_artifact_sha256"]) == 64
    assert plan_closeout["execution_plan_binding_count"] == 1
    assert plan_closeout["execution_plan_binding_field_count"] == 12
    assert plan["execution_plan_binding_id"] == future[
        "source_execution_plan_binding_id"
    ]
    assert plan["plan_status"] == "plan_binding_preview_not_executable"
    assert plan["dry_run_only"] is True
    assert plan["check_mode_only"] is True
    assert plan["execution_authorized"] is False
    assert plan["dry_run_execution_authorized"] is False
    assert plan["runner_execution_authorized"] is False
    assert plan["shell_execution_included"] is False
    assert plan["endpoint_execution_included"] is False
    assert plan["sql_execution_included"] is False
    assert plan["database_write_included"] is False
    assert plan["stdout_capture_allowed"] is False
    assert plan["stderr_capture_allowed"] is False
    assert plan["database_apply_authorized"] is False
    assert plan["ready_for_database_apply_now"] is False
    assert artifact["artifact_type"] == "non_executable_command_artifact_reference"
    assert artifact["source_execution_plan_binding_id"] == plan[
        "execution_plan_binding_id"
    ]
    assert artifact["dry_run_command_shape_hash"] == plan_closeout[
        "dry_run_command_shape_hash"
    ]
    assert artifact["command_text_included"] is False
    assert artifact["argv_included"] is False
    assert artifact.get("command_text") is None
    assert artifact.get("argv") is None
    assert artifact["shell_command_included"] is False
    assert artifact["endpoint_execution_included"] is False
    assert artifact["sql_execution_included"] is False
    assert artifact["database_write_included"] is False
    assert artifact["stdout_capture_allowed"] is False
    assert artifact["stderr_capture_allowed"] is False
    assert artifact["execution_authorized"] is False
    assert artifact["dry_run_execution_authorized"] is False
    assert artifact["runner_execution_authorized"] is False
    assert artifact["database_apply_authorized"] is False
    assert len(artifact["non_executable_command_artifact_sha256"]) == 64
    assert parser["required_command_shape_hash"] == plan_closeout[
        "dry_run_command_shape_hash"
    ]
    assert parser["execution_required"] is False
    assert parser["database_apply_authorized"] is False
    assert validation["receipt_validation_status"] == "preview_validated_not_executed"
    assert validation["execution_performed"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert plan_closeout["target_file"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert plan_closeout["hash_matches"] is True
    assert plan_closeout["target_migration_hash_locked"] is True
    assert plan_closeout["execution_plan_closeout_only"] is True
    assert plan_closeout["non_executable_command_artifact_only"] is True
    assert plan_closeout["runner_execution_authorized"] is False
    assert plan_closeout["dry_run_execution_authorized"] is False
    assert plan_closeout["execution_authorized"] is False
    assert plan_closeout["accepts_plaintext_secret"] is False
    assert plan_closeout["reads_secret_in_preview"] is False
    assert plan_closeout["signature_material_included"] is False
    assert plan_closeout["secret_material_included"] is False
    assert plan_closeout["signs_database_apply_authorization"] is False
    assert plan_closeout["executes_authorization_evidence"] is False
    assert plan_closeout["executes_database_apply"] is False
    assert plan_closeout["executes_endpoint_in_preview"] is False
    assert plan_closeout["executes_sql_in_preview"] is False
    assert plan_closeout["writes_database_in_preview"] is False
    assert plan_closeout["ready_for_database_apply_now"] is False
    assert plan_closeout["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_command_artifact_verification"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "runner_readiness_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "execution_plan_binding_preview_only" in check_keys
    assert "non_executable_command_artifact_bound" in check_keys
    assert "command_artifact_hash_locked" in check_keys
    assert "receipt_validation_and_parser_carried_forward" in check_keys
    assert "runner_execution_gate_closed" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bindings_carried_forward" in check_keys
    assert "runner_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout_waits_without_ready_execution_plan_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
    ]
    command_closeout = closeout["controlled_dry_run_command_artifact_closeout"]
    receipt_preflight = command_closeout["runner_execution_receipt_preflight"]
    artifact = command_closeout["non_executable_command_artifact"]
    contract = closeout["controlled_dry_run_command_artifact_closeout_contract"]
    check_keys = [
        check["key"]
        for check in closeout["controlled_dry_run_command_artifact_closeout_checks"]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PLAN_CLOSEOUT"
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_ready_count"
        ]
        == 0
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_check_count"
        ]
        == 12
    )
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_field_count"] == 12
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert closeout["summary"]["runner_execution_receipt_preflight_count"] == 1
    assert closeout["summary"]["runner_execution_receipt_preflight_field_count"] == 10
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["command_artifact_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-command-artifact-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout"
        ]
        is False
    )
    assert future["command_artifact_closeout_ready"] is False
    assert future["runner_execution_receipt_preflight_bound"] is False
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["stdout_capture_allowed"] is False
    assert future["stderr_capture_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert command_closeout["authorization_material_type"] == (
        "controlled_dry_run_command_artifact_closeout"
    )
    assert (
        command_closeout[
            "ready_for_future_database_apply_controlled_dry_run_command_artifact_closeout"
        ]
        is False
    )
    assert command_closeout["command_artifact_closeout_field_count"] == 12
    assert command_closeout["command_artifact_closeout_acceptance_gate_count"] == 10
    assert command_closeout["runner_execution_receipt_preflight_count"] == 1
    assert command_closeout["runner_execution_receipt_preflight_field_count"] == 10
    assert command_closeout["command_artifact_closeout_only"] is True
    assert command_closeout["runner_execution_receipt_preflight_only"] is True
    assert command_closeout["runner_execution_authorized"] is False
    assert command_closeout["dry_run_execution_authorized"] is False
    assert command_closeout["execution_authorized"] is False
    assert command_closeout["accepts_plaintext_secret"] is False
    assert command_closeout["reads_secret_in_preview"] is False
    assert command_closeout["signature_material_included"] is False
    assert command_closeout["secret_material_included"] is False
    assert command_closeout["signs_database_apply_authorization"] is False
    assert command_closeout["executes_database_apply"] is False
    assert command_closeout["executes_endpoint_in_preview"] is False
    assert command_closeout["executes_sql_in_preview"] is False
    assert command_closeout["writes_database_in_preview"] is False
    assert artifact["command_text_included"] is False
    assert artifact["argv_included"] is False
    assert artifact.get("command_text") is None
    assert artifact.get("argv") is None
    assert receipt_preflight["preflight_status"] == "preflight_only_not_executed"
    assert receipt_preflight["execution_required"] is False
    assert receipt_preflight["execution_authorized"] is False
    assert receipt_preflight["dry_run_execution_authorized"] is False
    assert receipt_preflight["runner_execution_authorized"] is False
    assert receipt_preflight["stdout_capture_allowed"] is False
    assert receipt_preflight["stderr_capture_allowed"] is False
    assert receipt_preflight["execution_performed"] is False
    assert receipt_preflight["database_apply_authorized"] is False
    assert receipt_preflight["writes_database"] is False
    assert contract[
        "permits_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
    ] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "execution_plan_closeout_ready" in check_keys
    assert "non_executable_command_artifact_hash_verified" in check_keys
    assert "runner_execution_receipt_preflight_no_execute" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-command-artifact-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
    ]
    command_closeout = closeout["controlled_dry_run_command_artifact_closeout"]
    receipt_preflight = command_closeout["runner_execution_receipt_preflight"]
    artifact = command_closeout["non_executable_command_artifact"]
    validation = command_closeout["receipt_validation_report"]
    parser = command_closeout["dry_run_result_parser"]
    contract = closeout["controlled_dry_run_command_artifact_closeout_contract"]
    check_keys = [
        check["key"]
        for check in closeout["controlled_dry_run_command_artifact_closeout_checks"]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT_READY"
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_ready_count"
        ]
        == 1
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_check_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_pass_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_waiting_count"
        ]
        == 0
    )
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_check_count"] == 12
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert closeout["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert closeout["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_field_count"] == 12
    assert (
        closeout["summary"][
            "controlled_dry_run_command_artifact_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert closeout["summary"]["runner_execution_receipt_preflight_count"] == 1
    assert closeout["summary"]["runner_execution_receipt_preflight_field_count"] == 10
    assert closeout["summary"]["non_executable_command_artifact_count"] == 1
    assert closeout["summary"]["non_executable_command_artifact_field_count"] == 10
    assert closeout["summary"]["execution_plan_binding_count"] == 1
    assert closeout["summary"]["execution_plan_binding_field_count"] == 12
    assert closeout["summary"]["dry_run_result_parser_count"] == 1
    assert closeout["summary"]["dry_run_result_parser_field_count"] == 10
    assert closeout["summary"]["receipt_validation_report_count"] == 1
    assert closeout["summary"]["receipt_validation_field_count"] == 8
    assert closeout["summary"]["rollback_binding_count"] == 1
    assert closeout["summary"]["post_apply_verifier_binding_count"] == 1
    assert closeout["summary"]["post_apply_verifier_required_count"] == 1
    assert closeout["summary"]["same_run_truth_required_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["command_artifact_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-command-artifact-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout"
        ]
        is True
    )
    assert future["command_artifact_closeout_ready"] is True
    assert future["runner_execution_receipt_preflight_bound"] is True
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["stdout_capture_allowed"] is False
    assert future["stderr_capture_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert command_closeout["authorization_material_type"] == (
        "controlled_dry_run_command_artifact_closeout"
    )
    assert (
        command_closeout[
            "ready_for_future_database_apply_controlled_dry_run_command_artifact_closeout"
        ]
        is True
    )
    assert command_closeout["command_artifact_closeout_field_count"] == 12
    assert command_closeout["command_artifact_closeout_acceptance_gate_count"] == 10
    assert "runner_execution_receipt_preflight_id" in (
        command_closeout["command_artifact_closeout_fields"]
    )
    assert "runner_execution_receipt_preflight_no_execute" in (
        command_closeout["command_artifact_closeout_acceptance_gates"]
    )
    assert command_closeout["runner_execution_receipt_preflight_count"] == 1
    assert command_closeout["runner_execution_receipt_preflight_field_count"] == 10
    assert command_closeout["non_executable_command_artifact_count"] == 1
    assert command_closeout["command_artifact_closeout_only"] is True
    assert command_closeout["runner_execution_receipt_preflight_only"] is True
    assert command_closeout["runner_execution_authorized"] is False
    assert command_closeout["dry_run_execution_authorized"] is False
    assert command_closeout["execution_authorized"] is False
    assert command_closeout["accepts_plaintext_secret"] is False
    assert command_closeout["reads_secret_in_preview"] is False
    assert command_closeout["signature_material_included"] is False
    assert command_closeout["secret_material_included"] is False
    assert command_closeout["signs_database_apply_authorization"] is False
    assert command_closeout["executes_database_apply"] is False
    assert command_closeout["executes_endpoint_in_preview"] is False
    assert command_closeout["executes_sql_in_preview"] is False
    assert command_closeout["writes_database_in_preview"] is False
    assert artifact["command_text_included"] is False
    assert artifact["argv_included"] is False
    assert artifact.get("command_text") is None
    assert artifact.get("argv") is None
    assert artifact["shell_command_included"] is False
    assert artifact["endpoint_execution_included"] is False
    assert artifact["sql_execution_included"] is False
    assert artifact["database_write_included"] is False
    assert artifact["execution_authorized"] is False
    assert artifact["database_apply_authorized"] is False
    assert len(artifact["non_executable_command_artifact_sha256"]) == 64
    assert receipt_preflight["preflight_id"] == future[
        "runner_execution_receipt_preflight_id"
    ]
    assert receipt_preflight["source_non_executable_command_artifact_id"] == artifact[
        "artifact_id"
    ]
    assert receipt_preflight["preflight_status"] == "preflight_only_not_executed"
    assert receipt_preflight["execution_required"] is False
    assert receipt_preflight["execution_authorized"] is False
    assert receipt_preflight["dry_run_execution_authorized"] is False
    assert receipt_preflight["runner_execution_authorized"] is False
    assert receipt_preflight["shell_execution_included"] is False
    assert receipt_preflight["endpoint_execution_included"] is False
    assert receipt_preflight["sql_execution_included"] is False
    assert receipt_preflight["database_write_included"] is False
    assert receipt_preflight["stdout_capture_allowed"] is False
    assert receipt_preflight["stderr_capture_allowed"] is False
    assert receipt_preflight["execution_performed"] is False
    assert receipt_preflight["stdout_included"] is False
    assert receipt_preflight["stderr_included"] is False
    assert receipt_preflight["database_apply_authorized"] is False
    assert receipt_preflight["writes_database"] is False
    assert parser["required_command_shape_hash"] == command_closeout[
        "dry_run_command_shape_hash"
    ]
    assert parser["execution_required"] is False
    assert validation["receipt_validation_status"] == "preview_validated_not_executed"
    assert validation["execution_performed"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert command_closeout["target_file"] == (
        "migrations/045_pchome_auto_policy_evidence_receipts.sql"
    )
    assert command_closeout["hash_matches"] is True
    assert command_closeout["target_migration_hash_locked"] is True
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "execution_plan_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "non_executable_command_artifact_hash_verified" in check_keys
    assert "non_executable_artifact_has_no_command_text_or_argv" in check_keys
    assert "runner_execution_receipt_preflight_bound" in check_keys
    assert "runner_execution_receipt_preflight_no_execute" in check_keys
    assert "result_parser_and_receipt_validation_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bindings_carried_forward" in check_keys
    assert "execution_plan_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout_waits_without_ready_command_artifact_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_post_receipt_parser_verification"
    ]
    receipt_closeout = closeout[
        "controlled_dry_run_runner_execution_receipt_closeout"
    ]
    preview = receipt_closeout["receipt_closeout_preview"]
    parser = receipt_closeout["post_receipt_parser_verification"]
    preflight = receipt_closeout["runner_execution_receipt_preflight"]
    contract = closeout[
        "controlled_dry_run_runner_execution_receipt_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_runner_execution_receipt_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_COMMAND_ARTIFACT_CLOSEOUT"
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_ready_count"
        ]
        == 0
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_check_count"
        ]
        == 12
    )
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_field_count"] == 12
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert closeout["summary"]["post_receipt_parser_verification_count"] == 1
    assert closeout["summary"]["post_receipt_parser_verification_field_count"] == 10
    assert closeout["summary"]["receipt_closeout_preview_count"] == 1
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["runner_execution_receipt_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-runner-execution-receipt-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_post_receipt_parser_verification"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_post_receipt_parser_closeout"
        ]
        is False
    )
    assert future["runner_execution_receipt_closeout_ready"] is False
    assert future["post_receipt_parser_verification_bound"] is False
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["stdout_capture_allowed"] is False
    assert future["stderr_capture_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert receipt_closeout["authorization_material_type"] == (
        "controlled_dry_run_runner_execution_receipt_closeout"
    )
    assert (
        receipt_closeout[
            "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout"
        ]
        is False
    )
    assert receipt_closeout["runner_execution_receipt_closeout_field_count"] == 12
    assert receipt_closeout["runner_execution_receipt_closeout_acceptance_gate_count"] == 10
    assert receipt_closeout["post_receipt_parser_verification_count"] == 1
    assert receipt_closeout["post_receipt_parser_verification_field_count"] == 10
    assert receipt_closeout["receipt_closeout_preview_count"] == 1
    assert receipt_closeout["runner_execution_receipt_closeout_only"] is True
    assert receipt_closeout["post_receipt_parser_verification_only"] is True
    assert receipt_closeout["runner_execution_authorized"] is False
    assert receipt_closeout["dry_run_execution_authorized"] is False
    assert receipt_closeout["execution_authorized"] is False
    assert receipt_closeout["accepts_plaintext_secret"] is False
    assert receipt_closeout["reads_secret_in_preview"] is False
    assert receipt_closeout["signature_material_included"] is False
    assert receipt_closeout["secret_material_included"] is False
    assert receipt_closeout["signs_database_apply_authorization"] is False
    assert receipt_closeout["executes_database_apply"] is False
    assert receipt_closeout["executes_endpoint_in_preview"] is False
    assert receipt_closeout["executes_sql_in_preview"] is False
    assert receipt_closeout["writes_database_in_preview"] is False
    assert preflight["preflight_status"] == "preflight_only_not_executed"
    assert preflight["execution_required"] is False
    assert preflight["execution_performed"] is False
    assert preflight["stdout_capture_allowed"] is False
    assert preflight["stderr_capture_allowed"] is False
    assert preflight["writes_database"] is False
    assert preview["receipt_status"] == "receipt_closeout_preview_not_executed"
    assert preview["execution_required"] is False
    assert preview["execution_performed"] is False
    assert preview["stdout_included"] is False
    assert preview["stderr_included"] is False
    assert preview["stdout_capture_allowed"] is False
    assert preview["stderr_capture_allowed"] is False
    assert preview["database_apply_authorized"] is False
    assert preview["writes_database"] is False
    assert preview["executes_endpoint"] is False
    assert preview["executes_sql"] is False
    assert parser["expected_preflight_status"] == "preflight_only_not_executed"
    assert parser["expected_receipt_status"] == "receipt_closeout_preview_not_executed"
    assert parser["expected_execution_performed"] is False
    assert parser["expected_stdout_included"] is False
    assert parser["expected_stderr_included"] is False
    assert parser["execution_required"] is False
    assert parser["stdout_allowed"] is False
    assert parser["stderr_allowed"] is False
    assert parser["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_post_receipt_parser_verification"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "command_artifact_closeout_ready" in check_keys
    assert "runner_execution_receipt_preflight_no_execute" in check_keys
    assert "post_receipt_parser_verification_bound" in check_keys
    assert "post_receipt_parser_blocks_execution" in check_keys
    assert "receipt_closeout_preview_only" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout_ready_after_fake_fetch_but_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-runner-receipt-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_post_receipt_parser_verification"
    ]
    receipt_closeout = closeout[
        "controlled_dry_run_runner_execution_receipt_closeout"
    ]
    preview = receipt_closeout["receipt_closeout_preview"]
    parser = receipt_closeout["post_receipt_parser_verification"]
    preflight = receipt_closeout["runner_execution_receipt_preflight"]
    contract = closeout[
        "controlled_dry_run_runner_execution_receipt_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_runner_execution_receipt_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT_READY"
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_ready_count"
        ]
        == 1
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_check_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_pass_count"
        ]
        == 12
    )
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_waiting_count"
        ]
        == 0
    )
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_check_count"] == 12
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_closeout_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert closeout["summary"]["authorization_evidence_execution_preflight_ready_count"] == 1
    assert closeout["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert closeout["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert closeout["summary"]["database_apply_authorization_final_verifier_gate_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_field_count"] == 12
    assert (
        closeout["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert closeout["summary"]["post_receipt_parser_verification_count"] == 1
    assert closeout["summary"]["post_receipt_parser_verification_field_count"] == 10
    assert closeout["summary"]["receipt_closeout_preview_count"] == 1
    assert closeout["summary"]["runner_execution_receipt_preflight_count"] == 1
    assert closeout["summary"]["runner_execution_receipt_preflight_field_count"] == 10
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["runner_execution_receipt_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-runner-execution-receipt-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_post_receipt_parser_verification"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_post_receipt_parser_closeout"
        ]
        is True
    )
    assert future["runner_execution_receipt_closeout_ready"] is True
    assert future["post_receipt_parser_verification_bound"] is True
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["stdout_capture_allowed"] is False
    assert future["stderr_capture_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert receipt_closeout["authorization_material_type"] == (
        "controlled_dry_run_runner_execution_receipt_closeout"
    )
    assert (
        receipt_closeout[
            "ready_for_future_database_apply_controlled_dry_run_runner_execution_receipt_closeout"
        ]
        is True
    )
    assert receipt_closeout["runner_execution_receipt_closeout_field_count"] == 12
    assert receipt_closeout["runner_execution_receipt_closeout_acceptance_gate_count"] == 10
    assert "post_receipt_parser_verification_id" in (
        receipt_closeout["runner_execution_receipt_closeout_fields"]
    )
    assert "post_receipt_parser_verification_bound" in (
        receipt_closeout["runner_execution_receipt_closeout_acceptance_gates"]
    )
    assert receipt_closeout["post_receipt_parser_verification_count"] == 1
    assert receipt_closeout["post_receipt_parser_verification_field_count"] == 10
    assert receipt_closeout["receipt_closeout_preview_count"] == 1
    assert receipt_closeout["runner_execution_receipt_closeout_only"] is True
    assert receipt_closeout["post_receipt_parser_verification_only"] is True
    assert receipt_closeout["runner_execution_authorized"] is False
    assert receipt_closeout["dry_run_execution_authorized"] is False
    assert receipt_closeout["execution_authorized"] is False
    assert receipt_closeout["accepts_plaintext_secret"] is False
    assert receipt_closeout["reads_secret_in_preview"] is False
    assert receipt_closeout["signature_material_included"] is False
    assert receipt_closeout["secret_material_included"] is False
    assert receipt_closeout["signs_database_apply_authorization"] is False
    assert receipt_closeout["executes_database_apply"] is False
    assert receipt_closeout["executes_endpoint_in_preview"] is False
    assert receipt_closeout["executes_sql_in_preview"] is False
    assert receipt_closeout["writes_database_in_preview"] is False
    assert preflight["preflight_status"] == "preflight_only_not_executed"
    assert preflight["execution_required"] is False
    assert preflight["execution_performed"] is False
    assert preflight["stdout_capture_allowed"] is False
    assert preflight["stderr_capture_allowed"] is False
    assert preflight["writes_database"] is False
    assert preview["receipt_status"] == "receipt_closeout_preview_not_executed"
    assert preview["execution_required"] is False
    assert preview["execution_performed"] is False
    assert preview["stdout_included"] is False
    assert preview["stderr_included"] is False
    assert preview["stdout_capture_allowed"] is False
    assert preview["stderr_capture_allowed"] is False
    assert preview["database_apply_authorized"] is False
    assert preview["writes_database"] is False
    assert preview["executes_endpoint"] is False
    assert preview["executes_sql"] is False
    assert parser["verification_id"] == future["post_receipt_parser_verification_id"]
    assert parser["expected_preflight_status"] == "preflight_only_not_executed"
    assert parser["expected_receipt_status"] == "receipt_closeout_preview_not_executed"
    assert parser["expected_execution_performed"] is False
    assert parser["expected_stdout_included"] is False
    assert parser["expected_stderr_included"] is False
    assert parser["execution_required"] is False
    assert parser["stdout_allowed"] is False
    assert parser["stderr_allowed"] is False
    assert parser["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_post_receipt_parser_verification"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "command_artifact_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "runner_execution_receipt_preflight_no_execute" in check_keys
    assert "post_receipt_parser_verification_bound" in check_keys
    assert "post_receipt_parser_blocks_execution" in check_keys
    assert "receipt_closeout_preview_only" in check_keys
    assert "result_parser_and_receipt_validation_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bindings_carried_forward" in check_keys
    assert "command_artifact_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout_waits_without_ready_runner_receipt():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
    ]
    parser_closeout = closeout[
        "controlled_dry_run_post_receipt_parser_closeout"
    ]
    enforcement = parser_closeout["no_apply_enforcement_verification"]
    contract = closeout[
        "controlled_dry_run_post_receipt_parser_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_post_receipt_parser_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_EXECUTION_RECEIPT_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["no_apply_enforcement_verification_count"] == 1
    assert closeout["summary"]["no_apply_enforcement_verification_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["post_receipt_parser_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-post-receipt-parser-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_apply_enforcement_closeout"
        ]
        is False
    )
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert parser_closeout["authorization_material_type"] == (
        "controlled_dry_run_post_receipt_parser_closeout"
    )
    assert parser_closeout["post_receipt_parser_closeout_field_count"] == 12
    assert parser_closeout["post_receipt_parser_closeout_acceptance_gate_count"] == 10
    assert parser_closeout["post_receipt_parser_closeout_only"] is True
    assert parser_closeout["no_apply_enforcement_verification_only"] is True
    assert parser_closeout["endpoint_execution_allowed"] is False
    assert parser_closeout["sql_execution_allowed"] is False
    assert parser_closeout["database_write_allowed"] is False
    assert parser_closeout["database_apply_authorized"] is False
    assert parser_closeout["signs_database_apply_authorization"] is False
    assert parser_closeout["executes_database_apply"] is False
    assert parser_closeout["executes_endpoint_in_preview"] is False
    assert parser_closeout["executes_sql_in_preview"] is False
    assert parser_closeout["writes_database_in_preview"] is False
    assert enforcement["enforcement_status"] == "no_apply_enforcement_preview_ready"
    assert enforcement["endpoint_execution_allowed"] is False
    assert enforcement["sql_execution_allowed"] is False
    assert enforcement["database_write_allowed"] is False
    assert enforcement["database_apply_authorized"] is False
    assert enforcement["executes_database_apply"] is False
    assert enforcement["executes_endpoint"] is False
    assert enforcement["executes_sql"] is False
    assert enforcement["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "runner_execution_receipt_closeout_ready" in check_keys
    assert "post_receipt_parser_verification_ready" in check_keys
    assert "no_apply_enforcement_verification_bound" in check_keys
    assert "no_apply_enforcement_blocks_endpoint_sql_db_write" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout_ready_after_fake_fetch_but_no_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-post-receipt-parser-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
    ]
    parser_closeout = closeout[
        "controlled_dry_run_post_receipt_parser_closeout"
    ]
    enforcement = parser_closeout["no_apply_enforcement_verification"]
    parser = parser_closeout["post_receipt_parser_verification"]
    preview = parser_closeout["receipt_closeout_preview"]
    contract = closeout[
        "controlled_dry_run_post_receipt_parser_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_post_receipt_parser_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["no_apply_enforcement_verification_count"] == 1
    assert closeout["summary"]["no_apply_enforcement_verification_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_apply_enforcement_closeout"
        ]
        is True
    )
    assert future["post_receipt_parser_closeout_ready"] is True
    assert future["no_apply_enforcement_verification_bound"] is True
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert parser_closeout["ready_for_future_database_apply_controlled_dry_run_post_receipt_parser_closeout"] is True
    assert parser_closeout["post_receipt_parser_closeout_only"] is True
    assert parser_closeout["no_apply_enforcement_verification_only"] is True
    assert parser_closeout["endpoint_execution_allowed"] is False
    assert parser_closeout["sql_execution_allowed"] is False
    assert parser_closeout["database_write_allowed"] is False
    assert parser_closeout["database_apply_authorized"] is False
    assert parser_closeout["signs_database_apply_authorization"] is False
    assert parser_closeout["executes_database_apply"] is False
    assert parser_closeout["executes_endpoint_in_preview"] is False
    assert parser_closeout["executes_sql_in_preview"] is False
    assert parser_closeout["writes_database_in_preview"] is False
    assert parser["parser_verification_status"] == "post_receipt_parser_preview_ready"
    assert parser["expected_execution_performed"] is False
    assert parser["expected_stdout_included"] is False
    assert parser["expected_stderr_included"] is False
    assert parser["database_apply_authorized"] is False
    assert preview["receipt_status"] == "receipt_closeout_preview_not_executed"
    assert preview["execution_performed"] is False
    assert preview["stdout_included"] is False
    assert preview["stderr_included"] is False
    assert preview["writes_database"] is False
    assert enforcement["verification_id"] == future["no_apply_enforcement_verification_id"]
    assert enforcement["source_post_receipt_parser_verification_id"] == parser["verification_id"]
    assert enforcement["endpoint_execution_allowed"] is False
    assert enforcement["sql_execution_allowed"] is False
    assert enforcement["database_write_allowed"] is False
    assert enforcement["database_apply_authorized"] is False
    assert enforcement["executes_database_apply"] is False
    assert enforcement["executes_endpoint"] is False
    assert enforcement["executes_sql"] is False
    assert enforcement["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "runner_execution_receipt_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "post_receipt_parser_verification_ready" in check_keys
    assert "post_receipt_parser_blocks_execution" in check_keys
    assert "receipt_closeout_preview_not_executed" in check_keys
    assert "no_apply_enforcement_verification_bound" in check_keys
    assert "no_apply_enforcement_blocks_endpoint_sql_db_write" in check_keys
    assert "result_parser_and_receipt_validation_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bindings_carried_forward" in check_keys
    assert "runner_execution_receipt_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout_waits_without_ready_parser_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
    ]
    enforcement_closeout = closeout[
        "controlled_dry_run_no_apply_enforcement_closeout"
    ]
    final_guard = enforcement_closeout["final_dry_run_executor_guard"]
    contract = closeout[
        "controlled_dry_run_no_apply_enforcement_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_apply_enforcement_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_POST_RECEIPT_PARSER_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["final_dry_run_executor_guard_count"] == 1
    assert closeout["summary"]["final_dry_run_executor_guard_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["no_apply_enforcement_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-no-apply-enforcement-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_final_executor_guard_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert enforcement_closeout["authorization_material_type"] == (
        "controlled_dry_run_no_apply_enforcement_closeout"
    )
    assert enforcement_closeout["no_apply_enforcement_closeout_field_count"] == 12
    assert enforcement_closeout["no_apply_enforcement_closeout_acceptance_gate_count"] == 10
    assert enforcement_closeout["no_apply_enforcement_closeout_only"] is True
    assert enforcement_closeout["final_dry_run_executor_guard_only"] is True
    assert enforcement_closeout["dry_run_executor_invocation_allowed"] is False
    assert enforcement_closeout["endpoint_execution_allowed"] is False
    assert enforcement_closeout["sql_execution_allowed"] is False
    assert enforcement_closeout["database_write_allowed"] is False
    assert enforcement_closeout["database_apply_authorized"] is False
    assert enforcement_closeout["signs_database_apply_authorization"] is False
    assert enforcement_closeout["executes_database_apply"] is False
    assert enforcement_closeout["executes_endpoint_in_preview"] is False
    assert enforcement_closeout["executes_sql_in_preview"] is False
    assert enforcement_closeout["writes_database_in_preview"] is False
    assert final_guard["guard_status"] == "final_dry_run_executor_guard_preview_ready"
    assert final_guard["dry_run_executor_invocation_allowed"] is False
    assert final_guard["endpoint_execution_allowed"] is False
    assert final_guard["sql_execution_allowed"] is False
    assert final_guard["database_write_allowed"] is False
    assert final_guard["database_apply_authorized"] is False
    assert final_guard["executes_database_apply"] is False
    assert final_guard["executes_endpoint"] is False
    assert final_guard["executes_sql"] is False
    assert final_guard["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "post_receipt_parser_closeout_ready" in check_keys
    assert "no_apply_enforcement_verification_ready" in check_keys
    assert "final_dry_run_executor_guard_bound" in check_keys
    assert "final_executor_guard_blocks_execution" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout_ready_after_fake_fetch_but_executor_guard_does_not_invoke():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-no-apply-enforcement-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
    ]
    enforcement_closeout = closeout[
        "controlled_dry_run_no_apply_enforcement_closeout"
    ]
    enforcement = enforcement_closeout["no_apply_enforcement_verification"]
    final_guard = enforcement_closeout["final_dry_run_executor_guard"]
    contract = closeout[
        "controlled_dry_run_no_apply_enforcement_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_apply_enforcement_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["final_dry_run_executor_guard_count"] == 1
    assert closeout["summary"]["final_dry_run_executor_guard_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_final_executor_guard_closeout"
        ]
        is True
    )
    assert future["no_apply_enforcement_closeout_ready"] is True
    assert future["final_dry_run_executor_guard_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert enforcement_closeout["ready_for_future_database_apply_controlled_dry_run_no_apply_enforcement_closeout"] is True
    assert enforcement_closeout["no_apply_enforcement_closeout_only"] is True
    assert enforcement_closeout["final_dry_run_executor_guard_only"] is True
    assert enforcement_closeout["dry_run_executor_invocation_allowed"] is False
    assert enforcement_closeout["endpoint_execution_allowed"] is False
    assert enforcement_closeout["sql_execution_allowed"] is False
    assert enforcement_closeout["database_write_allowed"] is False
    assert enforcement_closeout["database_apply_authorized"] is False
    assert enforcement_closeout["executes_database_apply"] is False
    assert enforcement_closeout["executes_endpoint_in_preview"] is False
    assert enforcement_closeout["executes_sql_in_preview"] is False
    assert enforcement_closeout["writes_database_in_preview"] is False
    assert enforcement["enforcement_status"] == "no_apply_enforcement_preview_ready"
    assert enforcement["endpoint_execution_allowed"] is False
    assert enforcement["sql_execution_allowed"] is False
    assert enforcement["database_write_allowed"] is False
    assert enforcement["database_apply_authorized"] is False
    assert enforcement["executes_endpoint"] is False
    assert enforcement["executes_sql"] is False
    assert enforcement["writes_database"] is False
    assert final_guard["guard_id"] == future["final_dry_run_executor_guard_id"]
    assert final_guard["guard_status"] == "final_dry_run_executor_guard_preview_ready"
    assert final_guard["dry_run_executor_invocation_allowed"] is False
    assert final_guard["stdout_capture_allowed"] is False
    assert final_guard["stderr_capture_allowed"] is False
    assert final_guard["database_apply_authorized"] is False
    assert final_guard["executes_database_apply"] is False
    assert final_guard["executes_endpoint"] is False
    assert final_guard["executes_sql"] is False
    assert final_guard["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "post_receipt_parser_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "no_apply_enforcement_verification_ready" in check_keys
    assert "no_apply_blocks_endpoint_sql_db_write" in check_keys
    assert "final_dry_run_executor_guard_bound" in check_keys
    assert "final_executor_guard_blocks_execution" in check_keys
    assert "parser_and_receipt_preview_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bindings_carried_forward" in check_keys
    assert "post_receipt_parser_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout_waits_without_ready_no_apply_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
    ]
    guard_closeout = closeout[
        "controlled_dry_run_final_executor_guard_closeout"
    ]
    replay = guard_closeout["pre_apply_replay_verifier"]
    final_guard = guard_closeout["final_dry_run_executor_guard"]
    contract = closeout[
        "controlled_dry_run_final_executor_guard_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_final_executor_guard_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_APPLY_ENFORCEMENT_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["pre_apply_replay_verifier_count"] == 1
    assert closeout["summary"]["pre_apply_replay_verifier_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["final_executor_guard_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-final-executor-guard-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_pre_apply_replay_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert guard_closeout["authorization_material_type"] == (
        "controlled_dry_run_final_executor_guard_closeout"
    )
    assert guard_closeout["final_executor_guard_closeout_field_count"] == 12
    assert guard_closeout["final_executor_guard_closeout_acceptance_gate_count"] == 10
    assert guard_closeout["final_executor_guard_closeout_only"] is True
    assert guard_closeout["pre_apply_replay_verifier_only"] is True
    assert guard_closeout["dry_run_executor_invocation_allowed"] is False
    assert guard_closeout["endpoint_execution_allowed"] is False
    assert guard_closeout["sql_execution_allowed"] is False
    assert guard_closeout["database_write_allowed"] is False
    assert guard_closeout["database_apply_authorized"] is False
    assert guard_closeout["executes_database_apply"] is False
    assert guard_closeout["executes_endpoint_in_preview"] is False
    assert guard_closeout["executes_sql_in_preview"] is False
    assert guard_closeout["writes_database_in_preview"] is False
    assert final_guard["guard_status"] == "final_dry_run_executor_guard_preview_ready"
    assert final_guard["dry_run_executor_invocation_allowed"] is False
    assert replay["verifier_status"] == "pre_apply_replay_verifier_preview_ready"
    assert replay["replay_mode"] == "pre_apply_replay_preview_only"
    assert replay["dry_run_executor_invocation_allowed"] is False
    assert replay["endpoint_execution_allowed"] is False
    assert replay["sql_execution_allowed"] is False
    assert replay["database_write_allowed"] is False
    assert replay["database_apply_authorized"] is False
    assert replay["executes_database_apply"] is False
    assert replay["executes_endpoint"] is False
    assert replay["executes_sql"] is False
    assert replay["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "no_apply_enforcement_closeout_ready" in check_keys
    assert "final_dry_run_executor_guard_ready" in check_keys
    assert "pre_apply_replay_verifier_bound" in check_keys
    assert "pre_apply_replay_verifier_preview_only" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout_ready_after_fake_fetch_but_replay_is_preview_only():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-final-executor-guard-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
    ]
    guard_closeout = closeout[
        "controlled_dry_run_final_executor_guard_closeout"
    ]
    replay = guard_closeout["pre_apply_replay_verifier"]
    final_guard = guard_closeout["final_dry_run_executor_guard"]
    contract = closeout[
        "controlled_dry_run_final_executor_guard_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_final_executor_guard_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["pre_apply_replay_verifier_count"] == 1
    assert closeout["summary"]["pre_apply_replay_verifier_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_pre_apply_replay_closeout"
        ]
        is True
    )
    assert future["final_executor_guard_closeout_ready"] is True
    assert future["pre_apply_replay_verifier_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert guard_closeout["ready_for_future_database_apply_controlled_dry_run_final_executor_guard_closeout"] is True
    assert guard_closeout["final_executor_guard_closeout_only"] is True
    assert guard_closeout["pre_apply_replay_verifier_only"] is True
    assert guard_closeout["dry_run_executor_invocation_allowed"] is False
    assert guard_closeout["endpoint_execution_allowed"] is False
    assert guard_closeout["sql_execution_allowed"] is False
    assert guard_closeout["database_write_allowed"] is False
    assert guard_closeout["database_apply_authorized"] is False
    assert guard_closeout["executes_database_apply"] is False
    assert guard_closeout["executes_endpoint_in_preview"] is False
    assert guard_closeout["executes_sql_in_preview"] is False
    assert guard_closeout["writes_database_in_preview"] is False
    assert final_guard["guard_status"] == "final_dry_run_executor_guard_preview_ready"
    assert final_guard["dry_run_executor_invocation_allowed"] is False
    assert replay["verification_id"] == future["pre_apply_replay_verifier_id"]
    assert replay["replay_mode"] == "pre_apply_replay_preview_only"
    assert replay["dry_run_executor_invocation_allowed"] is False
    assert replay["stdout_capture_allowed"] is False
    assert replay["stderr_capture_allowed"] is False
    assert replay["database_apply_authorized"] is False
    assert replay["executes_database_apply"] is False
    assert replay["executes_endpoint"] is False
    assert replay["executes_sql"] is False
    assert replay["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["writes_database"] is False
    assert "no_apply_enforcement_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "final_dry_run_executor_guard_ready" in check_keys
    assert "final_executor_guard_blocks_invocation" in check_keys
    assert "pre_apply_replay_verifier_bound" in check_keys
    assert "pre_apply_replay_verifier_preview_only" in check_keys
    assert "no_apply_enforcement_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bindings_carried_forward" in check_keys
    assert "no_apply_enforcement_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout_waits_without_ready_final_executor_guard_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
    ]
    replay_closeout = closeout[
        "controlled_dry_run_pre_apply_replay_closeout"
    ]
    readiness = replay_closeout["apply_executor_readiness_contract"]
    contract = closeout[
        "controlled_dry_run_pre_apply_replay_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_pre_apply_replay_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_EXECUTOR_GUARD_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["apply_executor_readiness_contract_count"] == 1
    assert closeout["summary"]["apply_executor_readiness_contract_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["pre_apply_replay_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-pre-apply-replay-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_apply_executor_readiness_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert replay_closeout["authorization_material_type"] == (
        "controlled_dry_run_pre_apply_replay_closeout"
    )
    assert replay_closeout["pre_apply_replay_closeout_field_count"] == 12
    assert replay_closeout["pre_apply_replay_closeout_acceptance_gate_count"] == 10
    assert replay_closeout["pre_apply_replay_closeout_only"] is True
    assert replay_closeout["apply_executor_readiness_contract_only"] is True
    assert replay_closeout["dry_run_executor_invocation_allowed"] is False
    assert replay_closeout["endpoint_execution_allowed"] is False
    assert replay_closeout["sql_execution_allowed"] is False
    assert replay_closeout["database_write_allowed"] is False
    assert replay_closeout["database_apply_authorized"] is False
    assert replay_closeout["executes_database_apply"] is False
    assert replay_closeout["executes_endpoint_in_preview"] is False
    assert replay_closeout["executes_sql_in_preview"] is False
    assert replay_closeout["writes_database_in_preview"] is False
    assert readiness["readiness_status"] == "apply_executor_readiness_contract_preview_ready"
    assert readiness["readiness_mode"] == "apply_executor_readiness_contract_preview_only"
    assert readiness["dry_run_executor_invocation_allowed"] is False
    assert readiness["endpoint_execution_allowed"] is False
    assert readiness["sql_execution_allowed"] is False
    assert readiness["database_write_allowed"] is False
    assert readiness["database_apply_authorized"] is False
    assert readiness["executes_database_apply"] is False
    assert readiness["executes_endpoint"] is False
    assert readiness["executes_sql"] is False
    assert readiness["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["writes_database"] is False
    assert "final_executor_guard_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "pre_apply_replay_verifier_ready" in check_keys
    assert "pre_apply_replay_preview_only" in check_keys
    assert "apply_executor_readiness_contract_bound" in check_keys
    assert "apply_executor_readiness_contract_blocks_apply" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout_ready_after_fake_fetch_but_executor_readiness_contract_blocks_apply():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-pre-apply-replay-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
    ]
    replay_closeout = closeout[
        "controlled_dry_run_pre_apply_replay_closeout"
    ]
    readiness = replay_closeout["apply_executor_readiness_contract"]
    replay = replay_closeout["pre_apply_replay_verifier"]
    contract = closeout[
        "controlled_dry_run_pre_apply_replay_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_pre_apply_replay_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["apply_executor_readiness_contract_count"] == 1
    assert closeout["summary"]["apply_executor_readiness_contract_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_apply_executor_readiness_closeout"
        ]
        is True
    )
    assert future["pre_apply_replay_closeout_ready"] is True
    assert future["apply_executor_readiness_contract_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert replay_closeout["ready_for_future_database_apply_controlled_dry_run_pre_apply_replay_closeout"] is True
    assert replay_closeout["pre_apply_replay_closeout_only"] is True
    assert replay_closeout["apply_executor_readiness_contract_only"] is True
    assert replay_closeout["dry_run_executor_invocation_allowed"] is False
    assert replay_closeout["endpoint_execution_allowed"] is False
    assert replay_closeout["sql_execution_allowed"] is False
    assert replay_closeout["database_write_allowed"] is False
    assert replay_closeout["database_apply_authorized"] is False
    assert replay_closeout["executes_database_apply"] is False
    assert replay_closeout["executes_endpoint_in_preview"] is False
    assert replay_closeout["executes_sql_in_preview"] is False
    assert replay_closeout["writes_database_in_preview"] is False
    assert readiness["contract_id"] == future["apply_executor_readiness_contract_id"]
    assert readiness["readiness_status"] == "apply_executor_readiness_contract_preview_ready"
    assert readiness["readiness_mode"] == "apply_executor_readiness_contract_preview_only"
    assert readiness["source_pre_apply_replay_verifier_id"] == replay["verification_id"]
    assert readiness["apply_executor_readiness_contract_field_count"] == 12
    assert readiness["dry_run_executor_invocation_allowed"] is False
    assert readiness["endpoint_execution_allowed"] is False
    assert readiness["sql_execution_allowed"] is False
    assert readiness["database_write_allowed"] is False
    assert readiness["ready_for_database_apply_now"] is False
    assert readiness["database_apply_authorized"] is False
    assert readiness["executes_database_apply"] is False
    assert readiness["executes_endpoint"] is False
    assert readiness["executes_sql"] is False
    assert readiness["writes_database"] is False
    assert replay["replay_mode"] == "pre_apply_replay_preview_only"
    assert replay["dry_run_executor_invocation_allowed"] is False
    assert replay["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["writes_database"] is False
    assert "final_executor_guard_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "pre_apply_replay_verifier_ready" in check_keys
    assert "pre_apply_replay_preview_only" in check_keys
    assert "apply_executor_readiness_contract_bound" in check_keys
    assert "apply_executor_readiness_contract_blocks_apply" in check_keys
    assert "final_guard_and_no_apply_enforcement_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "final_executor_guard_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout_waits_without_ready_pre_apply_replay_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_invocation_readiness_receipt"
    ]
    readiness_closeout = closeout[
        "controlled_dry_run_apply_executor_readiness_closeout"
    ]
    receipt = readiness_closeout["dry_run_invocation_readiness_receipt"]
    contract = closeout[
        "controlled_dry_run_apply_executor_readiness_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_apply_executor_readiness_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_PRE_APPLY_REPLAY_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["dry_run_invocation_readiness_receipt_count"] == 1
    assert closeout["summary"]["dry_run_invocation_readiness_receipt_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["apply_executor_readiness_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-apply-executor-readiness-closeout-"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_invocation_readiness_receipt"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_invocation_receipt_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert readiness_closeout["authorization_material_type"] == (
        "controlled_dry_run_apply_executor_readiness_closeout"
    )
    assert readiness_closeout["apply_executor_readiness_closeout_field_count"] == 12
    assert readiness_closeout["apply_executor_readiness_closeout_acceptance_gate_count"] == 10
    assert readiness_closeout["apply_executor_readiness_closeout_only"] is True
    assert readiness_closeout["dry_run_invocation_readiness_receipt_only"] is True
    assert readiness_closeout["dry_run_executor_invocation_allowed"] is False
    assert readiness_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert readiness_closeout["endpoint_execution_allowed"] is False
    assert readiness_closeout["sql_execution_allowed"] is False
    assert readiness_closeout["database_write_allowed"] is False
    assert readiness_closeout["database_apply_authorized"] is False
    assert readiness_closeout["executes_database_apply"] is False
    assert readiness_closeout["executes_endpoint_in_preview"] is False
    assert readiness_closeout["executes_sql_in_preview"] is False
    assert readiness_closeout["writes_database_in_preview"] is False
    assert receipt["receipt_status"] == "dry_run_invocation_readiness_receipt_preview_ready"
    assert receipt["receipt_mode"] == "dry_run_invocation_readiness_preview_only"
    assert receipt["dry_run_executor_invocation_allowed"] is False
    assert receipt["ready_for_dry_run_executor_invocation_now"] is False
    assert receipt["endpoint_execution_allowed"] is False
    assert receipt["sql_execution_allowed"] is False
    assert receipt["database_write_allowed"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_invocation_readiness_receipt"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "pre_apply_replay_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "apply_executor_readiness_contract_ready" in check_keys
    assert "apply_executor_readiness_contract_blocks_invocation" in check_keys
    assert "dry_run_invocation_readiness_receipt_bound" in check_keys
    assert "dry_run_invocation_readiness_receipt_no_execute" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout_ready_after_fake_fetch_but_invocation_receipt_is_preview_only():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-apply-executor-readiness-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_invocation_readiness_receipt"
    ]
    readiness_closeout = closeout[
        "controlled_dry_run_apply_executor_readiness_closeout"
    ]
    receipt = readiness_closeout["dry_run_invocation_readiness_receipt"]
    readiness = readiness_closeout["apply_executor_readiness_contract"]
    contract = closeout[
        "controlled_dry_run_apply_executor_readiness_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_apply_executor_readiness_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["dry_run_invocation_readiness_receipt_count"] == 1
    assert closeout["summary"]["dry_run_invocation_readiness_receipt_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_invocation_readiness_receipt"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_invocation_receipt_closeout"
        ]
        is True
    )
    assert future["apply_executor_readiness_closeout_ready"] is True
    assert future["dry_run_invocation_readiness_receipt_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert readiness_closeout["ready_for_future_database_apply_controlled_dry_run_apply_executor_readiness_closeout"] is True
    assert readiness_closeout["apply_executor_readiness_closeout_only"] is True
    assert readiness_closeout["dry_run_invocation_readiness_receipt_only"] is True
    assert readiness_closeout["dry_run_executor_invocation_allowed"] is False
    assert readiness_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert readiness_closeout["endpoint_execution_allowed"] is False
    assert readiness_closeout["sql_execution_allowed"] is False
    assert readiness_closeout["database_write_allowed"] is False
    assert readiness_closeout["database_apply_authorized"] is False
    assert readiness_closeout["executes_database_apply"] is False
    assert readiness_closeout["executes_endpoint_in_preview"] is False
    assert readiness_closeout["executes_sql_in_preview"] is False
    assert readiness_closeout["writes_database_in_preview"] is False
    assert receipt["receipt_id"] == future["dry_run_invocation_readiness_receipt_id"]
    assert receipt["receipt_status"] == "dry_run_invocation_readiness_receipt_preview_ready"
    assert receipt["receipt_mode"] == "dry_run_invocation_readiness_preview_only"
    assert receipt["dry_run_invocation_readiness_receipt_field_count"] == 12
    assert receipt["source_apply_executor_readiness_contract_id"] == readiness["contract_id"]
    assert receipt["dry_run_executor_invocation_allowed"] is False
    assert receipt["ready_for_dry_run_executor_invocation_now"] is False
    assert receipt["endpoint_execution_allowed"] is False
    assert receipt["sql_execution_allowed"] is False
    assert receipt["database_write_allowed"] is False
    assert receipt["ready_for_database_apply_now"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert readiness["readiness_mode"] == "apply_executor_readiness_contract_preview_only"
    assert readiness["dry_run_executor_invocation_allowed"] is False
    assert readiness["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_invocation_readiness_receipt"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "pre_apply_replay_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "apply_executor_readiness_contract_ready" in check_keys
    assert "apply_executor_readiness_contract_blocks_invocation" in check_keys
    assert "dry_run_invocation_readiness_receipt_bound" in check_keys
    assert "dry_run_invocation_readiness_receipt_no_execute" in check_keys
    assert "pre_apply_replay_and_final_guard_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "pre_apply_replay_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout_waits_without_ready_apply_executor_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_write_invocation_package"
    ]
    invocation_closeout = closeout[
        "controlled_dry_run_invocation_receipt_closeout"
    ]
    package = invocation_closeout["no_write_invocation_package"]
    contract = closeout[
        "controlled_dry_run_invocation_receipt_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_invocation_receipt_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_APPLY_EXECUTOR_READINESS_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["no_write_invocation_package_count"] == 1
    assert closeout["summary"]["no_write_invocation_package_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["invocation_receipt_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-invocation-receipt-closeout-"
    )
    assert future["no_write_invocation_package_id"].endswith(
        "-no-write-invocation-package"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_write_invocation_package"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_write_invocation_package_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert invocation_closeout["authorization_material_type"] == (
        "controlled_dry_run_invocation_receipt_closeout"
    )
    assert invocation_closeout["invocation_receipt_closeout_only"] is True
    assert invocation_closeout["no_write_invocation_package_only"] is True
    assert invocation_closeout["dry_run_executor_invocation_allowed"] is False
    assert invocation_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert invocation_closeout["endpoint_execution_allowed"] is False
    assert invocation_closeout["sql_execution_allowed"] is False
    assert invocation_closeout["database_write_allowed"] is False
    assert invocation_closeout["database_apply_authorized"] is False
    assert invocation_closeout["executes_database_apply"] is False
    assert invocation_closeout["executes_endpoint_in_preview"] is False
    assert invocation_closeout["executes_sql_in_preview"] is False
    assert invocation_closeout["writes_database_in_preview"] is False
    assert package["package_status"] == "no_write_invocation_package_preview_ready"
    assert package["package_mode"] == "no_write_invocation_package_preview_only"
    assert package["no_write_invocation_package_field_count"] == 12
    assert package["dry_run_executor_invocation_allowed"] is False
    assert package["ready_for_no_write_dry_run_invocation_package_now"] is False
    assert package["ready_for_actual_dry_run_execution_now"] is False
    assert package["endpoint_execution_allowed"] is False
    assert package["sql_execution_allowed"] is False
    assert package["database_write_allowed"] is False
    assert package["database_apply_authorized"] is False
    assert package["executes_database_apply"] is False
    assert package["executes_endpoint"] is False
    assert package["executes_sql"] is False
    assert package["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_write_invocation_package"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "apply_executor_readiness_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "dry_run_invocation_readiness_receipt_ready" in check_keys
    assert "dry_run_invocation_readiness_receipt_no_execute" in check_keys
    assert "no_write_invocation_package_bound" in check_keys
    assert "no_write_invocation_package_blocks_execution" in check_keys
    assert "apply_executor_readiness_and_replay_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "apply_executor_readiness_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout_ready_after_fake_fetch_but_package_is_no_write():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-invocation-receipt-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_write_invocation_package"
    ]
    invocation_closeout = closeout[
        "controlled_dry_run_invocation_receipt_closeout"
    ]
    package = invocation_closeout["no_write_invocation_package"]
    receipt = invocation_closeout["dry_run_invocation_readiness_receipt"]
    readiness_closeout = invocation_closeout["apply_executor_readiness_closeout"]
    contract = closeout[
        "controlled_dry_run_invocation_receipt_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_invocation_receipt_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["no_write_invocation_package_count"] == 1
    assert closeout["summary"]["no_write_invocation_package_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_write_invocation_package"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_write_invocation_package_closeout"
        ]
        is True
    )
    assert future["invocation_receipt_closeout_ready"] is True
    assert future["no_write_invocation_package_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert invocation_closeout["ready_for_future_database_apply_controlled_dry_run_invocation_receipt_closeout"] is True
    assert invocation_closeout["invocation_receipt_closeout_field_count"] == 12
    assert invocation_closeout["invocation_receipt_closeout_acceptance_gate_count"] == 10
    assert invocation_closeout["no_write_invocation_package_count"] == 1
    assert invocation_closeout["no_write_invocation_package_field_count"] == 12
    assert invocation_closeout["dry_run_executor_invocation_allowed"] is False
    assert invocation_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert invocation_closeout["endpoint_execution_allowed"] is False
    assert invocation_closeout["sql_execution_allowed"] is False
    assert invocation_closeout["database_write_allowed"] is False
    assert invocation_closeout["database_apply_authorized"] is False
    assert invocation_closeout["executes_database_apply"] is False
    assert invocation_closeout["executes_endpoint_in_preview"] is False
    assert invocation_closeout["executes_sql_in_preview"] is False
    assert invocation_closeout["writes_database_in_preview"] is False
    assert package["package_id"] == future["no_write_invocation_package_id"]
    assert package["source_invocation_receipt_closeout_id"] == future["invocation_receipt_closeout_id"]
    assert package["source_dry_run_invocation_readiness_receipt_id"] == receipt["receipt_id"]
    assert package["source_apply_executor_readiness_closeout_id"] == readiness_closeout["apply_executor_readiness_closeout_id"]
    assert package["required_command_shape_hash"] == receipt["required_command_shape_hash"]
    assert package["package_status"] == "no_write_invocation_package_preview_ready"
    assert package["package_mode"] == "no_write_invocation_package_preview_only"
    assert package["dry_run_executor_invocation_allowed"] is False
    assert package["ready_for_no_write_dry_run_invocation_package_now"] is False
    assert package["ready_for_actual_dry_run_execution_now"] is False
    assert package["endpoint_execution_allowed"] is False
    assert package["sql_execution_allowed"] is False
    assert package["database_write_allowed"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert package["issues_database_apply_authorization"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["executes_database_apply"] is False
    assert package["executes_endpoint"] is False
    assert package["executes_sql"] is False
    assert package["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_write_invocation_package"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "apply_executor_readiness_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "dry_run_invocation_readiness_receipt_ready" in check_keys
    assert "dry_run_invocation_readiness_receipt_no_execute" in check_keys
    assert "no_write_invocation_package_bound" in check_keys
    assert "no_write_invocation_package_blocks_execution" in check_keys
    assert "apply_executor_readiness_and_replay_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "apply_executor_readiness_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout_waits_without_ready_invocation_receipt_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_execution_preflight_guard"
    ]
    package_closeout = closeout[
        "controlled_dry_run_no_write_invocation_package_closeout"
    ]
    guard = package_closeout["execution_preflight_guard"]
    package = package_closeout["no_write_invocation_package"]
    contract = closeout[
        "controlled_dry_run_no_write_invocation_package_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_write_invocation_package_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_INVOCATION_RECEIPT_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["execution_preflight_guard_count"] == 1
    assert closeout["summary"]["execution_preflight_guard_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["no_write_invocation_package_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-no-write-invocation-package-closeout-"
    )
    assert future["execution_preflight_guard_id"].endswith(
        "-execution-preflight-guard"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_execution_preflight_guard"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_execution_preflight_guard_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert package_closeout["authorization_material_type"] == (
        "controlled_dry_run_no_write_invocation_package_closeout"
    )
    assert package_closeout["no_write_invocation_package_closeout_only"] is True
    assert package_closeout["execution_preflight_guard_only"] is True
    assert package_closeout["dry_run_executor_invocation_allowed"] is False
    assert package_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert package_closeout["endpoint_execution_allowed"] is False
    assert package_closeout["sql_execution_allowed"] is False
    assert package_closeout["database_write_allowed"] is False
    assert package_closeout["database_apply_authorized"] is False
    assert package_closeout["executes_database_apply"] is False
    assert package_closeout["executes_endpoint_in_preview"] is False
    assert package_closeout["executes_sql_in_preview"] is False
    assert package_closeout["writes_database_in_preview"] is False
    assert package["package_mode"] == "no_write_invocation_package_preview_only"
    assert package["dry_run_executor_invocation_allowed"] is False
    assert package["executes_database_apply"] is False
    assert guard["guard_status"] == "execution_preflight_guard_preview_ready"
    assert guard["guard_mode"] == "execution_preflight_guard_preview_only"
    assert guard["execution_preflight_guard_field_count"] == 12
    assert guard["dry_run_executor_invocation_allowed"] is False
    assert guard["ready_for_execution_preflight_guard_now"] is False
    assert guard["ready_for_dry_run_executor_invocation_now"] is False
    assert guard["ready_for_actual_dry_run_execution_now"] is False
    assert guard["endpoint_execution_allowed"] is False
    assert guard["sql_execution_allowed"] is False
    assert guard["database_write_allowed"] is False
    assert guard["database_apply_authorized"] is False
    assert guard["executes_database_apply"] is False
    assert guard["executes_endpoint"] is False
    assert guard["executes_sql"] is False
    assert guard["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_preflight_guard"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "invocation_receipt_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "no_write_invocation_package_ready" in check_keys
    assert "no_write_invocation_package_no_execute" in check_keys
    assert "execution_preflight_guard_bound" in check_keys
    assert "execution_preflight_guard_blocks_execution" in check_keys
    assert "invocation_receipt_and_apply_readiness_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "invocation_receipt_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout_ready_after_fake_fetch_but_guard_is_preview_only():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-no-write-invocation-package-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_execution_preflight_guard"
    ]
    package_closeout = closeout[
        "controlled_dry_run_no_write_invocation_package_closeout"
    ]
    guard = package_closeout["execution_preflight_guard"]
    package = package_closeout["no_write_invocation_package"]
    invocation_closeout = package_closeout["invocation_receipt_closeout"]
    contract = closeout[
        "controlled_dry_run_no_write_invocation_package_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_write_invocation_package_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["execution_preflight_guard_count"] == 1
    assert closeout["summary"]["execution_preflight_guard_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_execution_preflight_guard"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_execution_preflight_guard_closeout"
        ]
        is True
    )
    assert future["no_write_invocation_package_closeout_ready"] is True
    assert future["execution_preflight_guard_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert (
        package_closeout[
            "ready_for_future_database_apply_controlled_dry_run_no_write_invocation_package_closeout"
        ]
        is True
    )
    assert package_closeout["no_write_invocation_package_closeout_field_count"] == 12
    assert package_closeout["no_write_invocation_package_closeout_acceptance_gate_count"] == 10
    assert package_closeout["execution_preflight_guard_count"] == 1
    assert package_closeout["execution_preflight_guard_field_count"] == 12
    assert package_closeout["dry_run_executor_invocation_allowed"] is False
    assert package_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert package_closeout["endpoint_execution_allowed"] is False
    assert package_closeout["sql_execution_allowed"] is False
    assert package_closeout["database_write_allowed"] is False
    assert package_closeout["database_apply_authorized"] is False
    assert package_closeout["executes_database_apply"] is False
    assert package_closeout["executes_endpoint_in_preview"] is False
    assert package_closeout["executes_sql_in_preview"] is False
    assert package_closeout["writes_database_in_preview"] is False
    assert guard["guard_id"] == future["execution_preflight_guard_id"]
    assert guard["source_no_write_invocation_package_closeout_id"] == future["no_write_invocation_package_closeout_id"]
    assert guard["source_no_write_invocation_package_id"] == package["package_id"]
    assert guard["source_invocation_receipt_closeout_id"] == invocation_closeout["invocation_receipt_closeout_id"]
    assert guard["required_command_shape_hash"] == package["required_command_shape_hash"]
    assert guard["guard_status"] == "execution_preflight_guard_preview_ready"
    assert guard["guard_mode"] == "execution_preflight_guard_preview_only"
    assert guard["dry_run_executor_invocation_allowed"] is False
    assert guard["ready_for_execution_preflight_guard_now"] is False
    assert guard["ready_for_dry_run_executor_invocation_now"] is False
    assert guard["ready_for_actual_dry_run_execution_now"] is False
    assert guard["endpoint_execution_allowed"] is False
    assert guard["sql_execution_allowed"] is False
    assert guard["database_write_allowed"] is False
    assert guard["ready_for_database_apply_now"] is False
    assert guard["database_apply_authorized"] is False
    assert guard["issues_database_apply_authorization"] is False
    assert guard["signs_database_apply_authorization"] is False
    assert guard["executes_authorization_evidence"] is False
    assert guard["executes_database_apply"] is False
    assert guard["executes_endpoint"] is False
    assert guard["executes_sql"] is False
    assert guard["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_preflight_guard"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "invocation_receipt_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "no_write_invocation_package_ready" in check_keys
    assert "no_write_invocation_package_no_execute" in check_keys
    assert "execution_preflight_guard_bound" in check_keys
    assert "execution_preflight_guard_blocks_execution" in check_keys
    assert "invocation_receipt_and_apply_readiness_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "invocation_receipt_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout_waits_without_ready_package_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_runner_invocation_boundary"
    ]
    guard_closeout = closeout[
        "controlled_dry_run_execution_preflight_guard_closeout"
    ]
    boundary = guard_closeout["runner_invocation_boundary"]
    guard = guard_closeout["execution_preflight_guard"]
    contract = closeout[
        "controlled_dry_run_execution_preflight_guard_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_execution_preflight_guard_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_INVOCATION_PACKAGE_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["runner_invocation_boundary_count"] == 1
    assert closeout["summary"]["runner_invocation_boundary_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["execution_preflight_guard_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-execution-preflight-guard-closeout-"
    )
    assert future["runner_invocation_boundary_id"].endswith(
        "-runner-invocation-boundary"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_runner_invocation_boundary"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_runner_invocation_boundary_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert guard_closeout["authorization_material_type"] == (
        "controlled_dry_run_execution_preflight_guard_closeout"
    )
    assert guard_closeout["execution_preflight_guard_closeout_only"] is True
    assert guard_closeout["runner_invocation_boundary_only"] is True
    assert guard_closeout["dry_run_executor_invocation_allowed"] is False
    assert guard_closeout["runner_invocation_allowed"] is False
    assert guard_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert guard_closeout["endpoint_execution_allowed"] is False
    assert guard_closeout["sql_execution_allowed"] is False
    assert guard_closeout["database_write_allowed"] is False
    assert guard_closeout["database_apply_authorized"] is False
    assert guard_closeout["executes_database_apply"] is False
    assert guard_closeout["executes_endpoint_in_preview"] is False
    assert guard_closeout["executes_sql_in_preview"] is False
    assert guard_closeout["writes_database_in_preview"] is False
    assert guard["guard_mode"] == "execution_preflight_guard_preview_only"
    assert guard["dry_run_executor_invocation_allowed"] is False
    assert guard["executes_database_apply"] is False
    assert boundary["boundary_status"] == "runner_invocation_boundary_preview_ready"
    assert boundary["boundary_mode"] == "runner_invocation_boundary_preview_only"
    assert boundary["runner_invocation_boundary_field_count"] == 12
    assert boundary["dry_run_executor_invocation_allowed"] is False
    assert boundary["runner_invocation_allowed"] is False
    assert boundary["ready_for_runner_invocation_boundary_now"] is False
    assert boundary["ready_for_dry_run_executor_invocation_now"] is False
    assert boundary["ready_for_actual_dry_run_execution_now"] is False
    assert boundary["endpoint_execution_allowed"] is False
    assert boundary["sql_execution_allowed"] is False
    assert boundary["database_write_allowed"] is False
    assert boundary["database_apply_authorized"] is False
    assert boundary["executes_database_apply"] is False
    assert boundary["executes_endpoint"] is False
    assert boundary["executes_sql"] is False
    assert boundary["writes_database"] is False
    assert boundary["captures_stdout"] is False
    assert boundary["captures_stderr"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_runner_invocation_boundary"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "no_write_invocation_package_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "execution_preflight_guard_ready" in check_keys
    assert "execution_preflight_guard_no_execute" in check_keys
    assert "runner_invocation_boundary_bound" in check_keys
    assert "runner_invocation_boundary_blocks_execution" in check_keys
    assert "no_write_package_and_invocation_receipt_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "no_write_invocation_package_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout_ready_after_fake_fetch_but_boundary_blocks_runner():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-execution-preflight-guard-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_runner_invocation_boundary"
    ]
    guard_closeout = closeout[
        "controlled_dry_run_execution_preflight_guard_closeout"
    ]
    boundary = guard_closeout["runner_invocation_boundary"]
    guard = guard_closeout["execution_preflight_guard"]
    package_closeout = guard_closeout["no_write_invocation_package_closeout"]
    contract = closeout[
        "controlled_dry_run_execution_preflight_guard_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_execution_preflight_guard_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["runner_invocation_boundary_count"] == 1
    assert closeout["summary"]["runner_invocation_boundary_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_runner_invocation_boundary"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_runner_invocation_boundary_closeout"
        ]
        is True
    )
    assert future["execution_preflight_guard_closeout_ready"] is True
    assert future["runner_invocation_boundary_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert (
        guard_closeout[
            "ready_for_future_database_apply_controlled_dry_run_execution_preflight_guard_closeout"
        ]
        is True
    )
    assert guard_closeout["execution_preflight_guard_closeout_field_count"] == 12
    assert guard_closeout["execution_preflight_guard_closeout_acceptance_gate_count"] == 10
    assert guard_closeout["runner_invocation_boundary_count"] == 1
    assert guard_closeout["runner_invocation_boundary_field_count"] == 12
    assert guard_closeout["dry_run_executor_invocation_allowed"] is False
    assert guard_closeout["runner_invocation_allowed"] is False
    assert guard_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert guard_closeout["endpoint_execution_allowed"] is False
    assert guard_closeout["sql_execution_allowed"] is False
    assert guard_closeout["database_write_allowed"] is False
    assert guard_closeout["database_apply_authorized"] is False
    assert guard_closeout["executes_database_apply"] is False
    assert guard_closeout["executes_endpoint_in_preview"] is False
    assert guard_closeout["executes_sql_in_preview"] is False
    assert guard_closeout["writes_database_in_preview"] is False
    assert boundary["boundary_id"] == future["runner_invocation_boundary_id"]
    assert boundary["source_execution_preflight_guard_closeout_id"] == future["execution_preflight_guard_closeout_id"]
    assert boundary["source_execution_preflight_guard_id"] == guard["guard_id"]
    assert boundary["source_no_write_invocation_package_closeout_id"] == package_closeout["no_write_invocation_package_closeout_id"]
    assert boundary["required_command_shape_hash"] == guard["required_command_shape_hash"]
    assert boundary["boundary_status"] == "runner_invocation_boundary_preview_ready"
    assert boundary["boundary_mode"] == "runner_invocation_boundary_preview_only"
    assert boundary["dry_run_executor_invocation_allowed"] is False
    assert boundary["runner_invocation_allowed"] is False
    assert boundary["ready_for_runner_invocation_boundary_now"] is False
    assert boundary["ready_for_dry_run_executor_invocation_now"] is False
    assert boundary["ready_for_actual_dry_run_execution_now"] is False
    assert boundary["endpoint_execution_allowed"] is False
    assert boundary["sql_execution_allowed"] is False
    assert boundary["database_write_allowed"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["database_apply_authorized"] is False
    assert boundary["issues_database_apply_authorization"] is False
    assert boundary["signs_database_apply_authorization"] is False
    assert boundary["executes_authorization_evidence"] is False
    assert boundary["executes_database_apply"] is False
    assert boundary["executes_endpoint"] is False
    assert boundary["executes_sql"] is False
    assert boundary["writes_database"] is False
    assert boundary["captures_stdout"] is False
    assert boundary["captures_stderr"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_runner_invocation_boundary"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "no_write_invocation_package_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "execution_preflight_guard_ready" in check_keys
    assert "execution_preflight_guard_no_execute" in check_keys
    assert "runner_invocation_boundary_bound" in check_keys
    assert "runner_invocation_boundary_blocks_execution" in check_keys
    assert "no_write_package_and_invocation_receipt_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "no_write_invocation_package_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout_waits_without_ready_guard_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
    ]
    boundary_closeout = closeout[
        "controlled_dry_run_runner_invocation_boundary_closeout"
    ]
    handoff = boundary_closeout["no_execution_receipt_handoff"]
    boundary = boundary_closeout["runner_invocation_boundary"]
    contract = closeout[
        "controlled_dry_run_runner_invocation_boundary_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_runner_invocation_boundary_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_PREFLIGHT_GUARD_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["no_execution_receipt_handoff_count"] == 1
    assert closeout["summary"]["no_execution_receipt_handoff_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["runner_invocation_boundary_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-runner-invocation-boundary-closeout-"
    )
    assert future["no_execution_receipt_handoff_id"].endswith(
        "-no-execution-receipt-handoff"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_execution_receipt_handoff_closeout"
        ]
        is False
    )
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["execution_receipt_present"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert boundary_closeout["authorization_material_type"] == (
        "controlled_dry_run_runner_invocation_boundary_closeout"
    )
    assert boundary_closeout["runner_invocation_boundary_closeout_only"] is True
    assert boundary_closeout["no_execution_receipt_handoff_only"] is True
    assert boundary_closeout["dry_run_executor_invocation_allowed"] is False
    assert boundary_closeout["runner_invocation_allowed"] is False
    assert boundary_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert boundary_closeout["endpoint_execution_allowed"] is False
    assert boundary_closeout["sql_execution_allowed"] is False
    assert boundary_closeout["database_write_allowed"] is False
    assert boundary_closeout["database_apply_authorized"] is False
    assert boundary_closeout["executes_database_apply"] is False
    assert boundary_closeout["executes_endpoint_in_preview"] is False
    assert boundary_closeout["executes_sql_in_preview"] is False
    assert boundary_closeout["writes_database_in_preview"] is False
    assert boundary_closeout["captures_stdout"] is False
    assert boundary_closeout["captures_stderr"] is False
    assert boundary["boundary_mode"] == "runner_invocation_boundary_preview_only"
    assert boundary["dry_run_executor_invocation_allowed"] is False
    assert boundary["runner_invocation_allowed"] is False
    assert handoff["handoff_status"] == "no_execution_receipt_handoff_preview_ready"
    assert handoff["handoff_mode"] == "no_execution_receipt_handoff_preview_only"
    assert handoff["no_execution_receipt_handoff_field_count"] == 12
    assert handoff["execution_receipt_present"] is False
    assert handoff["execution_receipt_required"] is False
    assert handoff["dry_run_executor_invocation_allowed"] is False
    assert handoff["runner_invocation_allowed"] is False
    assert handoff["ready_for_no_execution_receipt_handoff_now"] is False
    assert handoff["ready_for_dry_run_executor_invocation_now"] is False
    assert handoff["ready_for_actual_dry_run_execution_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["executes_database_apply"] is False
    assert handoff["executes_endpoint"] is False
    assert handoff["executes_sql"] is False
    assert handoff["writes_database"] is False
    assert handoff["stdout_included"] is False
    assert handoff["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "execution_preflight_guard_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "runner_invocation_boundary_ready" in check_keys
    assert "runner_invocation_boundary_no_execute" in check_keys
    assert "no_execution_receipt_handoff_bound" in check_keys
    assert "no_execution_receipt_handoff_blocks_execution" in check_keys
    assert "execution_preflight_guard_and_no_write_package_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "execution_preflight_guard_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout_ready_after_fake_fetch_but_handoff_is_no_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-runner-invocation-boundary-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
    ]
    boundary_closeout = closeout[
        "controlled_dry_run_runner_invocation_boundary_closeout"
    ]
    handoff = boundary_closeout["no_execution_receipt_handoff"]
    boundary = boundary_closeout["runner_invocation_boundary"]
    guard_closeout = boundary_closeout["execution_preflight_guard_closeout"]
    contract = closeout[
        "controlled_dry_run_runner_invocation_boundary_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_runner_invocation_boundary_closeout_checks"
        ]
    ]
    assert (
        closeout["result"]
        == "DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["no_execution_receipt_handoff_count"] == 1
    assert closeout["summary"]["no_execution_receipt_handoff_field_count"] == 12
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_execution_receipt_handoff_closeout"
        ]
        is True
    )
    assert future["runner_invocation_boundary_closeout_ready"] is True
    assert future["no_execution_receipt_handoff_bound"] is True
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["dry_run_execution_performed"] is False
    assert future["execution_receipt_present"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert (
        boundary_closeout[
            "ready_for_future_database_apply_controlled_dry_run_runner_invocation_boundary_closeout"
        ]
        is True
    )
    assert boundary_closeout["runner_invocation_boundary_closeout_field_count"] == 12
    assert boundary_closeout["runner_invocation_boundary_closeout_acceptance_gate_count"] == 10
    assert boundary_closeout["no_execution_receipt_handoff_count"] == 1
    assert boundary_closeout["no_execution_receipt_handoff_field_count"] == 12
    assert boundary_closeout["dry_run_executor_invocation_allowed"] is False
    assert boundary_closeout["runner_invocation_allowed"] is False
    assert boundary_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert boundary_closeout["endpoint_execution_allowed"] is False
    assert boundary_closeout["sql_execution_allowed"] is False
    assert boundary_closeout["database_write_allowed"] is False
    assert boundary_closeout["database_apply_authorized"] is False
    assert boundary_closeout["executes_database_apply"] is False
    assert boundary_closeout["executes_endpoint_in_preview"] is False
    assert boundary_closeout["executes_sql_in_preview"] is False
    assert boundary_closeout["writes_database_in_preview"] is False
    assert boundary_closeout["captures_stdout"] is False
    assert boundary_closeout["captures_stderr"] is False
    assert handoff["handoff_id"] == future["no_execution_receipt_handoff_id"]
    assert handoff["source_runner_invocation_boundary_closeout_id"] == future["runner_invocation_boundary_closeout_id"]
    assert handoff["source_runner_invocation_boundary_id"] == boundary["boundary_id"]
    assert handoff["source_execution_preflight_guard_closeout_id"] == guard_closeout["execution_preflight_guard_closeout_id"]
    assert handoff["required_command_shape_hash"] == boundary["required_command_shape_hash"]
    assert handoff["handoff_status"] == "no_execution_receipt_handoff_preview_ready"
    assert handoff["handoff_mode"] == "no_execution_receipt_handoff_preview_only"
    assert handoff["execution_receipt_present"] is False
    assert handoff["execution_receipt_required"] is False
    assert handoff["dry_run_executor_invocation_allowed"] is False
    assert handoff["runner_invocation_allowed"] is False
    assert handoff["ready_for_no_execution_receipt_handoff_now"] is False
    assert handoff["ready_for_dry_run_executor_invocation_now"] is False
    assert handoff["ready_for_actual_dry_run_execution_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["issues_database_apply_authorization"] is False
    assert handoff["signs_database_apply_authorization"] is False
    assert handoff["executes_authorization_evidence"] is False
    assert handoff["executes_database_apply"] is False
    assert handoff["executes_endpoint"] is False
    assert handoff["executes_sql"] is False
    assert handoff["writes_database"] is False
    assert handoff["captures_stdout"] is False
    assert handoff["captures_stderr"] is False
    assert handoff["stdout_included"] is False
    assert handoff["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "execution_preflight_guard_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "runner_invocation_boundary_ready" in check_keys
    assert "runner_invocation_boundary_no_execute" in check_keys
    assert "no_execution_receipt_handoff_bound" in check_keys
    assert "no_execution_receipt_handoff_blocks_execution" in check_keys
    assert "execution_preflight_guard_and_no_write_package_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "execution_preflight_guard_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout_waits_without_ready_boundary_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
    ]
    handoff_closeout = closeout[
        "controlled_dry_run_no_execution_receipt_handoff_closeout"
    ]
    proof = handoff_closeout["final_no_runner_execution_proof"]
    contract = closeout[
        "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RUNNER_INVOCATION_BOUNDARY_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["final_no_runner_execution_proof_count"] == 1
    assert closeout["summary"]["final_no_runner_execution_proof_field_count"] == 12
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["no_execution_receipt_handoff_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout-"
    )
    assert future["final_no_runner_execution_proof_id"].endswith(
        "-final-no-runner-execution-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_final_no_runner_execution_proof_closeout"
        ]
        is False
    )
    assert future["no_execution_receipt_handoff_closeout_ready"] is False
    assert future["final_no_runner_execution_proof_bound"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert handoff_closeout["authorization_material_type"] == (
        "controlled_dry_run_no_execution_receipt_handoff_closeout"
    )
    assert handoff_closeout["no_execution_receipt_handoff_closeout_only"] is True
    assert handoff_closeout["final_no_runner_execution_proof_only"] is True
    assert handoff_closeout["dry_run_executor_invoked"] is False
    assert handoff_closeout["runner_invocation_performed"] is False
    assert handoff_closeout["endpoint_executed"] is False
    assert handoff_closeout["sql_executed"] is False
    assert handoff_closeout["database_written"] is False
    assert handoff_closeout["dry_run_executor_invocation_allowed"] is False
    assert handoff_closeout["runner_invocation_allowed"] is False
    assert handoff_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert handoff_closeout["endpoint_execution_allowed"] is False
    assert handoff_closeout["sql_execution_allowed"] is False
    assert handoff_closeout["database_write_allowed"] is False
    assert handoff_closeout["database_apply_authorized"] is False
    assert handoff_closeout["executes_database_apply"] is False
    assert handoff_closeout["executes_endpoint_in_preview"] is False
    assert handoff_closeout["executes_sql_in_preview"] is False
    assert handoff_closeout["writes_database_in_preview"] is False
    assert handoff_closeout["stdout_included"] is False
    assert handoff_closeout["stderr_included"] is False
    assert proof["proof_status"] == "final_no_runner_execution_proof_preview_ready"
    assert proof["proof_mode"] == "final_no_runner_execution_proof_preview_only"
    assert proof["final_no_runner_execution_proof_field_count"] == 12
    assert proof["execution_receipt_present"] is False
    assert proof["execution_receipt_required"] is False
    assert proof["dry_run_executor_invoked"] is False
    assert proof["runner_invocation_performed"] is False
    assert proof["endpoint_executed"] is False
    assert proof["sql_executed"] is False
    assert proof["database_written"] is False
    assert proof["dry_run_executor_invocation_allowed"] is False
    assert proof["runner_invocation_allowed"] is False
    assert proof["ready_for_dry_run_executor_invocation_now"] is False
    assert proof["ready_for_actual_dry_run_execution_now"] is False
    assert proof["endpoint_execution_allowed"] is False
    assert proof["sql_execution_allowed"] is False
    assert proof["database_write_allowed"] is False
    assert proof["database_apply_authorized"] is False
    assert proof["executes_database_apply"] is False
    assert proof["executes_endpoint"] is False
    assert proof["executes_sql"] is False
    assert proof["writes_database"] is False
    assert proof["stdout_included"] is False
    assert proof["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "runner_invocation_boundary_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "no_execution_receipt_handoff_ready" in check_keys
    assert "no_execution_receipt_handoff_no_execute" in check_keys
    assert "final_no_runner_execution_proof_bound" in check_keys
    assert "final_no_runner_execution_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "runner_invocation_boundary_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout_ready_after_fake_fetch_but_proof_is_no_runner_execution():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
    ]
    handoff_closeout = closeout[
        "controlled_dry_run_no_execution_receipt_handoff_closeout"
    ]
    proof = handoff_closeout["final_no_runner_execution_proof"]
    handoff = handoff_closeout["no_execution_receipt_handoff"]
    boundary_closeout = handoff_closeout["runner_invocation_boundary_closeout"]
    contract = closeout[
        "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["final_no_runner_execution_proof_count"] == 1
    assert closeout["summary"]["final_no_runner_execution_proof_field_count"] == 12
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_final_no_runner_execution_proof_closeout"
        ]
        is True
    )
    assert future["no_execution_receipt_handoff_closeout_ready"] is True
    assert future["final_no_runner_execution_proof_bound"] is True
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert (
        handoff_closeout[
            "ready_for_future_database_apply_controlled_dry_run_no_execution_receipt_handoff_closeout"
        ]
        is True
    )
    assert handoff_closeout["no_execution_receipt_handoff_closeout_field_count"] == 12
    assert handoff_closeout["no_execution_receipt_handoff_closeout_acceptance_gate_count"] == 10
    assert handoff_closeout["final_no_runner_execution_proof_count"] == 1
    assert handoff_closeout["final_no_runner_execution_proof_field_count"] == 12
    assert handoff_closeout["dry_run_executor_invoked"] is False
    assert handoff_closeout["runner_invocation_performed"] is False
    assert handoff_closeout["endpoint_executed"] is False
    assert handoff_closeout["sql_executed"] is False
    assert handoff_closeout["database_written"] is False
    assert handoff_closeout["dry_run_executor_invocation_allowed"] is False
    assert handoff_closeout["runner_invocation_allowed"] is False
    assert handoff_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert handoff_closeout["endpoint_execution_allowed"] is False
    assert handoff_closeout["sql_execution_allowed"] is False
    assert handoff_closeout["database_write_allowed"] is False
    assert handoff_closeout["database_apply_authorized"] is False
    assert handoff_closeout["executes_database_apply"] is False
    assert handoff_closeout["executes_endpoint_in_preview"] is False
    assert handoff_closeout["executes_sql_in_preview"] is False
    assert handoff_closeout["writes_database_in_preview"] is False
    assert handoff_closeout["stdout_included"] is False
    assert handoff_closeout["stderr_included"] is False
    assert proof["proof_id"] == future["final_no_runner_execution_proof_id"]
    assert proof["source_no_execution_receipt_handoff_closeout_id"] == future["no_execution_receipt_handoff_closeout_id"]
    assert proof["source_no_execution_receipt_handoff_id"] == handoff["handoff_id"]
    assert proof["source_runner_invocation_boundary_closeout_id"] == boundary_closeout["runner_invocation_boundary_closeout_id"]
    assert proof["required_command_shape_hash"] == handoff["required_command_shape_hash"]
    assert proof["proof_status"] == "final_no_runner_execution_proof_preview_ready"
    assert proof["proof_mode"] == "final_no_runner_execution_proof_preview_only"
    assert proof["execution_receipt_present"] is False
    assert proof["execution_receipt_required"] is False
    assert proof["dry_run_executor_invoked"] is False
    assert proof["runner_invocation_performed"] is False
    assert proof["endpoint_executed"] is False
    assert proof["sql_executed"] is False
    assert proof["database_written"] is False
    assert proof["dry_run_executor_invocation_allowed"] is False
    assert proof["runner_invocation_allowed"] is False
    assert proof["ready_for_final_no_runner_execution_proof_now"] is False
    assert proof["ready_for_dry_run_executor_invocation_now"] is False
    assert proof["ready_for_actual_dry_run_execution_now"] is False
    assert proof["endpoint_execution_allowed"] is False
    assert proof["sql_execution_allowed"] is False
    assert proof["database_write_allowed"] is False
    assert proof["database_apply_authorized"] is False
    assert proof["executes_database_apply"] is False
    assert proof["executes_endpoint"] is False
    assert proof["executes_sql"] is False
    assert proof["writes_database"] is False
    assert proof["captures_stdout"] is False
    assert proof["captures_stderr"] is False
    assert proof["stdout_included"] is False
    assert proof["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "runner_invocation_boundary_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "no_execution_receipt_handoff_ready" in check_keys
    assert "no_execution_receipt_handoff_no_execute" in check_keys
    assert "final_no_runner_execution_proof_bound" in check_keys
    assert "final_no_runner_execution_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "runner_invocation_boundary_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout_waits_without_ready_handoff_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
    ]
    proof_closeout = closeout[
        "controlled_dry_run_final_no_runner_execution_proof_closeout"
    ]
    quarantine = proof_closeout["controlled_executor_quarantine_proof"]
    contract = closeout[
        "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_EXECUTION_RECEIPT_HANDOFF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["controlled_executor_quarantine_proof_count"] == 1
    assert closeout["summary"]["controlled_executor_quarantine_proof_field_count"] == 12
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["final_no_runner_execution_proof_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout-"
    )
    assert future["controlled_executor_quarantine_proof_id"].endswith(
        "-controlled-executor-quarantine-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout"
        ]
        is False
    )
    assert future["final_no_runner_execution_proof_closeout_ready"] is False
    assert future["controlled_executor_quarantine_proof_bound"] is False
    assert future["controlled_executor_quarantine_bound"] is True
    assert future["executor_quarantine_enforced"] is True
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert proof_closeout["authorization_material_type"] == (
        "controlled_dry_run_final_no_runner_execution_proof_closeout"
    )
    assert proof_closeout["final_no_runner_execution_proof_closeout_only"] is True
    assert proof_closeout["controlled_executor_quarantine_proof_only"] is True
    assert proof_closeout["controlled_executor_quarantine_bound"] is True
    assert proof_closeout["executor_quarantine_enforced"] is True
    assert proof_closeout["dry_run_executor_invoked"] is False
    assert proof_closeout["runner_invocation_performed"] is False
    assert proof_closeout["endpoint_executed"] is False
    assert proof_closeout["sql_executed"] is False
    assert proof_closeout["database_written"] is False
    assert proof_closeout["dry_run_executor_invocation_allowed"] is False
    assert proof_closeout["runner_invocation_allowed"] is False
    assert proof_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert proof_closeout["endpoint_execution_allowed"] is False
    assert proof_closeout["sql_execution_allowed"] is False
    assert proof_closeout["database_write_allowed"] is False
    assert proof_closeout["database_apply_authorized"] is False
    assert proof_closeout["executes_database_apply"] is False
    assert proof_closeout["executes_endpoint_in_preview"] is False
    assert proof_closeout["executes_sql_in_preview"] is False
    assert proof_closeout["writes_database_in_preview"] is False
    assert proof_closeout["stdout_included"] is False
    assert proof_closeout["stderr_included"] is False
    assert quarantine["quarantine_status"] == "controlled_executor_quarantine_proof_preview_ready"
    assert quarantine["quarantine_mode"] == "controlled_executor_quarantine_proof_preview_only"
    assert quarantine["controlled_executor_quarantine_proof_field_count"] == 12
    assert quarantine["controlled_executor_quarantine_bound"] is True
    assert quarantine["executor_quarantine_enforced"] is True
    assert quarantine["dry_run_executor_invoked"] is False
    assert quarantine["runner_invocation_performed"] is False
    assert quarantine["endpoint_executed"] is False
    assert quarantine["sql_executed"] is False
    assert quarantine["database_written"] is False
    assert quarantine["execution_receipt_present"] is False
    assert quarantine["execution_receipt_required"] is False
    assert quarantine["dry_run_executor_invocation_allowed"] is False
    assert quarantine["runner_invocation_allowed"] is False
    assert quarantine["ready_for_controlled_executor_quarantine_now"] is False
    assert quarantine["ready_for_dry_run_executor_invocation_now"] is False
    assert quarantine["ready_for_actual_dry_run_execution_now"] is False
    assert quarantine["endpoint_execution_allowed"] is False
    assert quarantine["sql_execution_allowed"] is False
    assert quarantine["database_write_allowed"] is False
    assert quarantine["database_apply_authorized"] is False
    assert quarantine["executes_database_apply"] is False
    assert quarantine["executes_endpoint"] is False
    assert quarantine["executes_sql"] is False
    assert quarantine["writes_database"] is False
    assert quarantine["stdout_included"] is False
    assert quarantine["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "no_execution_receipt_handoff_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "final_no_runner_execution_proof_ready" in check_keys
    assert "final_no_runner_execution_proof_no_execute" in check_keys
    assert "controlled_executor_quarantine_proof_bound" in check_keys
    assert "controlled_executor_quarantine_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "no_execution_receipt_handoff_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout_ready_after_fake_fetch_but_quarantine_is_no_executor():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
    ]
    proof_closeout = closeout[
        "controlled_dry_run_final_no_runner_execution_proof_closeout"
    ]
    quarantine = proof_closeout["controlled_executor_quarantine_proof"]
    final_proof = proof_closeout["final_no_runner_execution_proof"]
    handoff_closeout = proof_closeout["no_execution_receipt_handoff_closeout"]
    contract = closeout[
        "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["controlled_executor_quarantine_proof_count"] == 1
    assert closeout["summary"]["controlled_executor_quarantine_proof_field_count"] == 12
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout"
        ]
        is True
    )
    assert future["final_no_runner_execution_proof_closeout_ready"] is True
    assert future["controlled_executor_quarantine_proof_bound"] is True
    assert future["controlled_executor_quarantine_bound"] is True
    assert future["executor_quarantine_enforced"] is True
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert (
        proof_closeout[
            "ready_for_future_database_apply_controlled_dry_run_final_no_runner_execution_proof_closeout"
        ]
        is True
    )
    assert proof_closeout["final_no_runner_execution_proof_closeout_field_count"] == 12
    assert proof_closeout["final_no_runner_execution_proof_closeout_acceptance_gate_count"] == 10
    assert proof_closeout["controlled_executor_quarantine_proof_count"] == 1
    assert proof_closeout["controlled_executor_quarantine_proof_field_count"] == 12
    assert proof_closeout["controlled_executor_quarantine_bound"] is True
    assert proof_closeout["executor_quarantine_enforced"] is True
    assert proof_closeout["dry_run_executor_invoked"] is False
    assert proof_closeout["runner_invocation_performed"] is False
    assert proof_closeout["endpoint_executed"] is False
    assert proof_closeout["sql_executed"] is False
    assert proof_closeout["database_written"] is False
    assert proof_closeout["dry_run_executor_invocation_allowed"] is False
    assert proof_closeout["runner_invocation_allowed"] is False
    assert proof_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert proof_closeout["endpoint_execution_allowed"] is False
    assert proof_closeout["sql_execution_allowed"] is False
    assert proof_closeout["database_write_allowed"] is False
    assert proof_closeout["database_apply_authorized"] is False
    assert proof_closeout["executes_database_apply"] is False
    assert proof_closeout["executes_endpoint_in_preview"] is False
    assert proof_closeout["executes_sql_in_preview"] is False
    assert proof_closeout["writes_database_in_preview"] is False
    assert proof_closeout["stdout_included"] is False
    assert proof_closeout["stderr_included"] is False
    assert quarantine["quarantine_proof_id"] == future["controlled_executor_quarantine_proof_id"]
    assert quarantine["source_final_no_runner_execution_proof_closeout_id"] == future["final_no_runner_execution_proof_closeout_id"]
    assert quarantine["source_final_no_runner_execution_proof_id"] == final_proof["proof_id"]
    assert quarantine["source_no_execution_receipt_handoff_closeout_id"] == handoff_closeout["no_execution_receipt_handoff_closeout_id"]
    assert quarantine["required_command_shape_hash"] == final_proof["required_command_shape_hash"]
    assert quarantine["quarantine_status"] == "controlled_executor_quarantine_proof_preview_ready"
    assert quarantine["quarantine_mode"] == "controlled_executor_quarantine_proof_preview_only"
    assert quarantine["controlled_executor_quarantine_bound"] is True
    assert quarantine["executor_quarantine_enforced"] is True
    assert quarantine["dry_run_executor_invoked"] is False
    assert quarantine["runner_invocation_performed"] is False
    assert quarantine["endpoint_executed"] is False
    assert quarantine["sql_executed"] is False
    assert quarantine["database_written"] is False
    assert quarantine["dry_run_executor_invocation_allowed"] is False
    assert quarantine["runner_invocation_allowed"] is False
    assert quarantine["ready_for_controlled_executor_quarantine_now"] is False
    assert quarantine["ready_for_dry_run_executor_invocation_now"] is False
    assert quarantine["ready_for_actual_dry_run_execution_now"] is False
    assert quarantine["endpoint_execution_allowed"] is False
    assert quarantine["sql_execution_allowed"] is False
    assert quarantine["database_write_allowed"] is False
    assert quarantine["database_apply_authorized"] is False
    assert quarantine["executes_database_apply"] is False
    assert quarantine["executes_endpoint"] is False
    assert quarantine["executes_sql"] is False
    assert quarantine["writes_database"] is False
    assert quarantine["captures_stdout"] is False
    assert quarantine["captures_stderr"] is False
    assert quarantine["stdout_included"] is False
    assert quarantine["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "no_execution_receipt_handoff_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "final_no_runner_execution_proof_ready" in check_keys
    assert "final_no_runner_execution_proof_no_execute" in check_keys
    assert "controlled_executor_quarantine_proof_bound" in check_keys
    assert "controlled_executor_quarantine_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "no_execution_receipt_handoff_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout_waits_without_ready_final_proof_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
    ]
    quarantine_closeout = closeout[
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
    ]
    freeze = quarantine_closeout["dry_run_execution_envelope_freeze_proof"]
    contract = closeout[
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_FINAL_NO_RUNNER_EXECUTION_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["dry_run_execution_envelope_freeze_proof_count"] == 1
    assert closeout["summary"]["dry_run_execution_envelope_freeze_proof_field_count"] == 12
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["controlled_executor_quarantine_proof_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-controlled-executor-quarantine-proof-closeout-"
    )
    assert future["dry_run_execution_envelope_freeze_proof_id"].endswith(
        "-dry-run-execution-envelope-freeze-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout"
        ]
        is False
    )
    assert future["controlled_executor_quarantine_proof_closeout_ready"] is False
    assert future["dry_run_execution_envelope_freeze_proof_bound"] is False
    assert future["controlled_executor_quarantine_bound"] is True
    assert future["executor_quarantine_enforced"] is True
    assert future["execution_envelope_frozen"] is True
    assert future["execution_envelope_mutation_allowed"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert quarantine_closeout["authorization_material_type"] == (
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
    )
    assert quarantine_closeout["controlled_executor_quarantine_proof_closeout_only"] is True
    assert quarantine_closeout["dry_run_execution_envelope_freeze_proof_only"] is True
    assert quarantine_closeout["execution_envelope_frozen"] is True
    assert quarantine_closeout["execution_envelope_mutation_allowed"] is False
    assert quarantine_closeout["dry_run_executor_invoked"] is False
    assert quarantine_closeout["runner_invocation_performed"] is False
    assert quarantine_closeout["endpoint_executed"] is False
    assert quarantine_closeout["sql_executed"] is False
    assert quarantine_closeout["database_written"] is False
    assert quarantine_closeout["dry_run_executor_invocation_allowed"] is False
    assert quarantine_closeout["runner_invocation_allowed"] is False
    assert quarantine_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert quarantine_closeout["endpoint_execution_allowed"] is False
    assert quarantine_closeout["sql_execution_allowed"] is False
    assert quarantine_closeout["database_write_allowed"] is False
    assert quarantine_closeout["database_apply_authorized"] is False
    assert quarantine_closeout["executes_database_apply"] is False
    assert quarantine_closeout["executes_endpoint_in_preview"] is False
    assert quarantine_closeout["executes_sql_in_preview"] is False
    assert quarantine_closeout["writes_database_in_preview"] is False
    assert quarantine_closeout["stdout_included"] is False
    assert quarantine_closeout["stderr_included"] is False
    assert freeze["freeze_status"] == "dry_run_execution_envelope_freeze_proof_preview_ready"
    assert freeze["freeze_mode"] == "dry_run_execution_envelope_freeze_proof_preview_only"
    assert freeze["dry_run_execution_envelope_freeze_proof_field_count"] == 12
    assert freeze["execution_envelope_frozen"] is True
    assert freeze["execution_envelope_mutation_allowed"] is False
    assert freeze["dry_run_executor_invoked"] is False
    assert freeze["runner_invocation_performed"] is False
    assert freeze["endpoint_executed"] is False
    assert freeze["sql_executed"] is False
    assert freeze["database_written"] is False
    assert freeze["execution_receipt_present"] is False
    assert freeze["execution_receipt_required"] is False
    assert freeze["dry_run_executor_invocation_allowed"] is False
    assert freeze["runner_invocation_allowed"] is False
    assert freeze["ready_for_dry_run_executor_invocation_now"] is False
    assert freeze["ready_for_actual_dry_run_execution_now"] is False
    assert freeze["endpoint_execution_allowed"] is False
    assert freeze["sql_execution_allowed"] is False
    assert freeze["database_write_allowed"] is False
    assert freeze["database_apply_authorized"] is False
    assert freeze["executes_database_apply"] is False
    assert freeze["executes_endpoint"] is False
    assert freeze["executes_sql"] is False
    assert freeze["writes_database"] is False
    assert freeze["stdout_included"] is False
    assert freeze["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "final_no_runner_execution_proof_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "controlled_executor_quarantine_proof_ready" in check_keys
    assert "controlled_executor_quarantine_proof_no_execute" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_bound" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "final_no_runner_execution_proof_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_after_fake_fetch_but_envelope_is_frozen():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-envelope-freeze-proof.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
    ]
    quarantine_closeout = closeout[
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
    ]
    freeze = quarantine_closeout["dry_run_execution_envelope_freeze_proof"]
    quarantine = quarantine_closeout["controlled_executor_quarantine_proof"]
    source_closeout = quarantine_closeout["final_no_runner_execution_proof_closeout"]
    final_proof = quarantine_closeout["final_no_runner_execution_proof"]
    contract = closeout[
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_preflight_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_invocation_package_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_invocation_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_apply_executor_readiness_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_pre_apply_replay_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_executor_guard_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_apply_enforcement_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_post_receipt_parser_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_execution_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_command_artifact_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_plan_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_runner_readiness_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_package_ready_count"] == 1
    assert closeout["summary"]["controlled_apply_final_preflight_ready_count"] == 1
    assert closeout["summary"]["dry_run_execution_envelope_freeze_proof_count"] == 1
    assert closeout["summary"]["dry_run_execution_envelope_freeze_proof_field_count"] == 12
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout"
        ]
        is True
    )
    assert future["controlled_executor_quarantine_proof_closeout_ready"] is True
    assert future["dry_run_execution_envelope_freeze_proof_bound"] is True
    assert future["controlled_executor_quarantine_bound"] is True
    assert future["executor_quarantine_enforced"] is True
    assert future["execution_envelope_frozen"] is True
    assert future["execution_envelope_mutation_allowed"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["ready_for_actual_dry_run_execution_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert (
        quarantine_closeout[
            "ready_for_future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout"
        ]
        is True
    )
    assert quarantine_closeout["controlled_executor_quarantine_proof_closeout_field_count"] == 12
    assert quarantine_closeout["controlled_executor_quarantine_proof_closeout_acceptance_gate_count"] == 10
    assert quarantine_closeout["dry_run_execution_envelope_freeze_proof_count"] == 1
    assert quarantine_closeout["dry_run_execution_envelope_freeze_proof_field_count"] == 12
    assert quarantine_closeout["controlled_executor_quarantine_proof_closeout_only"] is True
    assert quarantine_closeout["dry_run_execution_envelope_freeze_proof_only"] is True
    assert quarantine_closeout["execution_envelope_frozen"] is True
    assert quarantine_closeout["execution_envelope_mutation_allowed"] is False
    assert quarantine_closeout["dry_run_executor_invoked"] is False
    assert quarantine_closeout["runner_invocation_performed"] is False
    assert quarantine_closeout["endpoint_executed"] is False
    assert quarantine_closeout["sql_executed"] is False
    assert quarantine_closeout["database_written"] is False
    assert quarantine_closeout["dry_run_executor_invocation_allowed"] is False
    assert quarantine_closeout["runner_invocation_allowed"] is False
    assert quarantine_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert quarantine_closeout["endpoint_execution_allowed"] is False
    assert quarantine_closeout["sql_execution_allowed"] is False
    assert quarantine_closeout["database_write_allowed"] is False
    assert quarantine_closeout["database_apply_authorized"] is False
    assert quarantine_closeout["executes_database_apply"] is False
    assert quarantine_closeout["executes_endpoint_in_preview"] is False
    assert quarantine_closeout["executes_sql_in_preview"] is False
    assert quarantine_closeout["writes_database_in_preview"] is False
    assert quarantine_closeout["stdout_included"] is False
    assert quarantine_closeout["stderr_included"] is False
    assert freeze["freeze_proof_id"] == future["dry_run_execution_envelope_freeze_proof_id"]
    assert freeze["source_controlled_executor_quarantine_proof_closeout_id"] == future["controlled_executor_quarantine_proof_closeout_id"]
    assert freeze["source_controlled_executor_quarantine_proof_id"] == quarantine["quarantine_proof_id"]
    assert freeze["source_final_no_runner_execution_proof_closeout_id"] == source_closeout["final_no_runner_execution_proof_closeout_id"]
    assert freeze["source_final_no_runner_execution_proof_id"] == final_proof["proof_id"]
    assert freeze["required_command_shape_hash"] == quarantine["required_command_shape_hash"]
    assert freeze["freeze_status"] == "dry_run_execution_envelope_freeze_proof_preview_ready"
    assert freeze["freeze_mode"] == "dry_run_execution_envelope_freeze_proof_preview_only"
    assert freeze["execution_envelope_frozen"] is True
    assert freeze["execution_envelope_mutation_allowed"] is False
    assert freeze["dry_run_executor_invoked"] is False
    assert freeze["runner_invocation_performed"] is False
    assert freeze["endpoint_executed"] is False
    assert freeze["sql_executed"] is False
    assert freeze["database_written"] is False
    assert freeze["execution_receipt_present"] is False
    assert freeze["dry_run_executor_invocation_allowed"] is False
    assert freeze["runner_invocation_allowed"] is False
    assert freeze["ready_for_dry_run_executor_invocation_now"] is False
    assert freeze["ready_for_actual_dry_run_execution_now"] is False
    assert freeze["endpoint_execution_allowed"] is False
    assert freeze["sql_execution_allowed"] is False
    assert freeze["database_write_allowed"] is False
    assert freeze["database_apply_authorized"] is False
    assert freeze["executes_database_apply"] is False
    assert freeze["executes_endpoint"] is False
    assert freeze["executes_sql"] is False
    assert freeze["writes_database"] is False
    assert freeze["captures_stdout"] is False
    assert freeze["captures_stderr"] is False
    assert freeze["stdout_included"] is False
    assert freeze["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert contract["ready_for_actual_dry_run_execution_now"] is False
    assert contract["writes_database"] is False
    assert "final_no_runner_execution_proof_closeout_ready" in check_keys
    assert "controlled_executor_quarantine_proof_ready" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_bound" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_blocks_execution" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout_waits_without_ready_quarantine_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
    ]
    freeze_closeout = closeout[
        "controlled_dry_run_execution_envelope_freeze_proof_closeout"
    ]
    handoff = freeze_closeout["frozen_envelope_verifier_handoff"]
    contract = closeout[
        "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_CONTROLLED_EXECUTOR_QUARANTINE_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["frozen_envelope_verifier_handoff_count"] == 1
    assert closeout["summary"]["frozen_envelope_verifier_handoff_field_count"] == 12
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["execution_envelope_freeze_proof_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-execution-envelope-freeze-proof-closeout-"
    )
    assert future["frozen_envelope_verifier_handoff_id"].endswith(
        "-frozen-envelope-verifier-handoff"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
        ]
        is False
    )
    assert future["execution_envelope_freeze_proof_closeout_ready"] is False
    assert future["frozen_envelope_verifier_handoff_bound"] is False
    assert future["execution_envelope_frozen"] is True
    assert future["execution_envelope_mutation_allowed"] is False
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert freeze_closeout["authorization_material_type"] == (
        "controlled_dry_run_execution_envelope_freeze_proof_closeout"
    )
    assert freeze_closeout["execution_envelope_freeze_proof_closeout_only"] is True
    assert freeze_closeout["frozen_envelope_verifier_handoff_only"] is True
    assert freeze_closeout["execution_envelope_frozen"] is True
    assert freeze_closeout["execution_envelope_mutation_allowed"] is False
    assert freeze_closeout["verifier_invocation_allowed"] is False
    assert freeze_closeout["verifier_invoked"] is False
    assert freeze_closeout["verifier_receipt_present"] is False
    assert freeze_closeout["dry_run_executor_invoked"] is False
    assert freeze_closeout["runner_invocation_performed"] is False
    assert freeze_closeout["endpoint_executed"] is False
    assert freeze_closeout["sql_executed"] is False
    assert freeze_closeout["database_written"] is False
    assert freeze_closeout["ready_for_verifier_invocation_now"] is False
    assert freeze_closeout["ready_for_dry_run_executor_invocation_now"] is False
    assert freeze_closeout["endpoint_execution_allowed"] is False
    assert freeze_closeout["sql_execution_allowed"] is False
    assert freeze_closeout["database_write_allowed"] is False
    assert freeze_closeout["database_apply_authorized"] is False
    assert freeze_closeout["executes_database_apply"] is False
    assert freeze_closeout["executes_endpoint_in_preview"] is False
    assert freeze_closeout["executes_sql_in_preview"] is False
    assert freeze_closeout["writes_database_in_preview"] is False
    assert handoff["handoff_status"] == "frozen_envelope_verifier_handoff_preview_ready"
    assert handoff["verifier_handoff_mode"] == "frozen_envelope_verifier_handoff_preview_only"
    assert handoff["frozen_envelope_verifier_handoff_field_count"] == 12
    assert handoff["execution_envelope_frozen"] is True
    assert handoff["execution_envelope_mutation_allowed"] is False
    assert handoff["verifier_handoff_bound"] is True
    assert handoff["verifier_invocation_allowed"] is False
    assert handoff["verifier_invoked"] is False
    assert handoff["verifier_receipt_present"] is False
    assert handoff["dry_run_executor_invoked"] is False
    assert handoff["runner_invocation_performed"] is False
    assert handoff["endpoint_executed"] is False
    assert handoff["sql_executed"] is False
    assert handoff["database_written"] is False
    assert handoff["ready_for_verifier_invocation_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["executes_database_apply"] is False
    assert handoff["executes_endpoint"] is False
    assert handoff["executes_sql"] is False
    assert handoff["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
        ]
        is False
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert "controlled_executor_quarantine_proof_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_ready" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_no_execute" in check_keys
    assert "frozen_envelope_verifier_handoff_bound" in check_keys
    assert "frozen_envelope_verifier_handoff_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "controlled_executor_quarantine_proof_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_after_fake_fetch_but_verifier_is_handoff_only():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-verifier-handoff.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
    ]
    freeze_closeout = closeout[
        "controlled_dry_run_execution_envelope_freeze_proof_closeout"
    ]
    handoff = freeze_closeout["frozen_envelope_verifier_handoff"]
    freeze = freeze_closeout["dry_run_execution_envelope_freeze_proof"]
    source_closeout = freeze_closeout["controlled_executor_quarantine_proof_closeout"]
    contract = closeout[
        "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_ready_count"] == 1
    assert closeout["summary"]["frozen_envelope_verifier_handoff_count"] == 1
    assert closeout["summary"]["frozen_envelope_verifier_handoff_field_count"] == 12
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
        ]
        is True
    )
    assert future["execution_envelope_freeze_proof_closeout_ready"] is True
    assert future["frozen_envelope_verifier_handoff_bound"] is True
    assert future["execution_envelope_frozen"] is True
    assert future["execution_envelope_mutation_allowed"] is False
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert freeze_closeout["ready_for_future_database_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout"] is True
    assert freeze_closeout["execution_envelope_freeze_proof_closeout_field_count"] == 12
    assert freeze_closeout["execution_envelope_freeze_proof_closeout_acceptance_gate_count"] == 10
    assert freeze_closeout["frozen_envelope_verifier_handoff_count"] == 1
    assert freeze_closeout["frozen_envelope_verifier_handoff_field_count"] == 12
    assert freeze_closeout["execution_envelope_freeze_proof_closeout_only"] is True
    assert freeze_closeout["frozen_envelope_verifier_handoff_only"] is True
    assert freeze_closeout["execution_envelope_frozen"] is True
    assert freeze_closeout["execution_envelope_mutation_allowed"] is False
    assert freeze_closeout["verifier_invocation_allowed"] is False
    assert freeze_closeout["verifier_invoked"] is False
    assert freeze_closeout["verifier_receipt_present"] is False
    assert freeze_closeout["dry_run_executor_invoked"] is False
    assert freeze_closeout["runner_invocation_performed"] is False
    assert freeze_closeout["endpoint_executed"] is False
    assert freeze_closeout["sql_executed"] is False
    assert freeze_closeout["database_written"] is False
    assert freeze_closeout["ready_for_verifier_invocation_now"] is False
    assert freeze_closeout["endpoint_execution_allowed"] is False
    assert freeze_closeout["sql_execution_allowed"] is False
    assert freeze_closeout["database_write_allowed"] is False
    assert freeze_closeout["database_apply_authorized"] is False
    assert freeze_closeout["executes_database_apply"] is False
    assert freeze_closeout["executes_endpoint_in_preview"] is False
    assert freeze_closeout["executes_sql_in_preview"] is False
    assert freeze_closeout["writes_database_in_preview"] is False
    assert handoff["handoff_id"] == future["frozen_envelope_verifier_handoff_id"]
    assert handoff["source_execution_envelope_freeze_proof_closeout_id"] == future["execution_envelope_freeze_proof_closeout_id"]
    assert handoff["source_dry_run_execution_envelope_freeze_proof_id"] == freeze["freeze_proof_id"]
    assert handoff["source_controlled_executor_quarantine_proof_closeout_id"] == source_closeout["controlled_executor_quarantine_proof_closeout_id"]
    assert handoff["required_command_shape_hash"] == freeze["required_command_shape_hash"]
    assert handoff["handoff_status"] == "frozen_envelope_verifier_handoff_preview_ready"
    assert handoff["verifier_handoff_mode"] == "frozen_envelope_verifier_handoff_preview_only"
    assert handoff["execution_envelope_frozen"] is True
    assert handoff["execution_envelope_mutation_allowed"] is False
    assert handoff["verifier_handoff_bound"] is True
    assert handoff["verifier_invocation_allowed"] is False
    assert handoff["verifier_invoked"] is False
    assert handoff["verifier_receipt_present"] is False
    assert handoff["dry_run_executor_invoked"] is False
    assert handoff["runner_invocation_performed"] is False
    assert handoff["endpoint_executed"] is False
    assert handoff["sql_executed"] is False
    assert handoff["database_written"] is False
    assert handoff["ready_for_verifier_invocation_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["executes_database_apply"] is False
    assert handoff["executes_endpoint"] is False
    assert handoff["executes_sql"] is False
    assert handoff["writes_database"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
        ]
        is True
    )
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert contract["ready_for_dry_run_executor_invocation_now"] is False
    assert "controlled_executor_quarantine_proof_closeout_ready" in check_keys
    assert "dry_run_execution_envelope_freeze_proof_ready" in check_keys
    assert "frozen_envelope_verifier_handoff_bound" in check_keys
    assert "frozen_envelope_verifier_handoff_blocks_execution" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_waits_without_ready_freeze_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
    ]
    handoff_closeout = closeout[
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
    ]
    lock = handoff_closeout["verifier_invocation_lock_proof"]
    contract = closeout[
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_EXECUTION_ENVELOPE_FREEZE_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_invocation_lock_proof_count"] == 1
    assert closeout["summary"]["verifier_invocation_lock_proof_field_count"] == 12
    assert closeout["summary"]["verifier_invocation_locked_count"] == 1
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["frozen_envelope_verifier_handoff_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-frozen-envelope-verifier-handoff-closeout-"
    )
    assert future["verifier_invocation_lock_proof_id"].endswith(
        "-verifier-invocation-lock-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout"
        ]
        is False
    )
    assert future["frozen_envelope_verifier_handoff_closeout_ready"] is False
    assert future["execution_envelope_freeze_proof_closeout_ready"] is False
    assert future["verifier_invocation_lock_proof_bound"] is False
    assert future["verifier_invocation_locked"] is True
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert handoff_closeout["authorization_material_type"] == (
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
    )
    assert handoff_closeout["frozen_envelope_verifier_handoff_closeout_only"] is True
    assert handoff_closeout["verifier_invocation_lock_proof_only"] is True
    assert handoff_closeout["verifier_invocation_locked"] is True
    assert handoff_closeout["verifier_invocation_allowed"] is False
    assert handoff_closeout["verifier_invoked"] is False
    assert handoff_closeout["verifier_receipt_present"] is False
    assert handoff_closeout["dry_run_executor_invoked"] is False
    assert handoff_closeout["runner_invocation_performed"] is False
    assert handoff_closeout["endpoint_executed"] is False
    assert handoff_closeout["sql_executed"] is False
    assert handoff_closeout["database_written"] is False
    assert handoff_closeout["ready_for_verifier_invocation_now"] is False
    assert handoff_closeout["endpoint_execution_allowed"] is False
    assert handoff_closeout["sql_execution_allowed"] is False
    assert handoff_closeout["database_write_allowed"] is False
    assert handoff_closeout["database_apply_authorized"] is False
    assert handoff_closeout["executes_database_apply"] is False
    assert handoff_closeout["executes_endpoint_in_preview"] is False
    assert handoff_closeout["executes_sql_in_preview"] is False
    assert handoff_closeout["writes_database_in_preview"] is False
    assert lock["lock_status"] == "verifier_invocation_lock_proof_preview_ready"
    assert lock["lock_mode"] == "verifier_invocation_lock_proof_preview_only"
    assert lock["verifier_invocation_lock_proof_field_count"] == 12
    assert lock["verifier_invocation_locked"] is True
    assert lock["verifier_invocation_allowed"] is False
    assert lock["verifier_invoked"] is False
    assert lock["verifier_receipt_present"] is False
    assert lock["dry_run_executor_invoked"] is False
    assert lock["runner_invocation_performed"] is False
    assert lock["endpoint_executed"] is False
    assert lock["sql_executed"] is False
    assert lock["database_written"] is False
    assert lock["ready_for_verifier_invocation_now"] is False
    assert lock["endpoint_execution_allowed"] is False
    assert lock["sql_execution_allowed"] is False
    assert lock["database_write_allowed"] is False
    assert lock["database_apply_authorized"] is False
    assert lock["executes_database_apply"] is False
    assert lock["executes_endpoint"] is False
    assert lock["executes_sql"] is False
    assert lock["writes_database"] is False
    assert lock["stdout_included"] is False
    assert lock["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
        ]
        is False
    )
    assert contract["verifier_invocation_locked"] is True
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert "execution_envelope_freeze_proof_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "frozen_envelope_verifier_handoff_ready" in check_keys
    assert "frozen_envelope_verifier_handoff_no_execute" in check_keys
    assert "verifier_invocation_lock_proof_bound" in check_keys
    assert "verifier_invocation_lock_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "execution_envelope_freeze_proof_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_after_fake_fetch_but_verifier_invocation_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-verifier-lock.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
    ]
    handoff_closeout = closeout[
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
    ]
    lock = handoff_closeout["verifier_invocation_lock_proof"]
    handoff = handoff_closeout["frozen_envelope_verifier_handoff"]
    source_closeout = handoff_closeout["execution_envelope_freeze_proof_closeout"]
    freeze = handoff_closeout["dry_run_execution_envelope_freeze_proof"]
    contract = closeout[
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["verifier_invocation_lock_proof_count"] == 1
    assert closeout["summary"]["verifier_invocation_lock_proof_field_count"] == 12
    assert closeout["summary"]["verifier_invocation_locked_count"] == 1
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout"
        ]
        is True
    )
    assert future["frozen_envelope_verifier_handoff_closeout_ready"] is True
    assert future["execution_envelope_freeze_proof_closeout_ready"] is True
    assert future["frozen_envelope_verifier_handoff_ready"] is True
    assert future["verifier_invocation_lock_proof_bound"] is True
    assert future["verifier_invocation_locked"] is True
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert handoff_closeout["ready_for_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"] is True
    assert handoff_closeout["frozen_envelope_verifier_handoff_closeout_field_count"] == 12
    assert handoff_closeout["frozen_envelope_verifier_handoff_closeout_acceptance_gate_count"] == 10
    assert handoff_closeout["verifier_invocation_lock_proof_count"] == 1
    assert handoff_closeout["verifier_invocation_lock_proof_field_count"] == 12
    assert handoff_closeout["frozen_envelope_verifier_handoff_closeout_only"] is True
    assert handoff_closeout["verifier_invocation_lock_proof_only"] is True
    assert handoff_closeout["verifier_invocation_locked"] is True
    assert handoff_closeout["verifier_invocation_allowed"] is False
    assert handoff_closeout["verifier_invoked"] is False
    assert handoff_closeout["verifier_receipt_present"] is False
    assert handoff_closeout["dry_run_executor_invoked"] is False
    assert handoff_closeout["runner_invocation_performed"] is False
    assert handoff_closeout["endpoint_executed"] is False
    assert handoff_closeout["sql_executed"] is False
    assert handoff_closeout["database_written"] is False
    assert handoff_closeout["ready_for_verifier_invocation_now"] is False
    assert handoff_closeout["endpoint_execution_allowed"] is False
    assert handoff_closeout["sql_execution_allowed"] is False
    assert handoff_closeout["database_write_allowed"] is False
    assert handoff_closeout["database_apply_authorized"] is False
    assert handoff_closeout["executes_database_apply"] is False
    assert handoff_closeout["executes_endpoint_in_preview"] is False
    assert handoff_closeout["executes_sql_in_preview"] is False
    assert handoff_closeout["writes_database_in_preview"] is False
    assert lock["lock_proof_id"] == future["verifier_invocation_lock_proof_id"]
    assert (
        lock["source_frozen_envelope_verifier_handoff_closeout_id"]
        == future["frozen_envelope_verifier_handoff_closeout_id"]
    )
    assert lock["source_frozen_envelope_verifier_handoff_id"] == handoff["handoff_id"]
    assert (
        lock["source_execution_envelope_freeze_proof_closeout_id"]
        == source_closeout["execution_envelope_freeze_proof_closeout_id"]
    )
    assert lock["source_dry_run_execution_envelope_freeze_proof_id"] == freeze["freeze_proof_id"]
    assert lock["required_command_shape_hash"] == freeze["required_command_shape_hash"]
    assert lock["lock_status"] == "verifier_invocation_lock_proof_preview_ready"
    assert lock["lock_mode"] == "verifier_invocation_lock_proof_preview_only"
    assert lock["verifier_invocation_locked"] is True
    assert lock["verifier_invocation_allowed"] is False
    assert lock["verifier_invoked"] is False
    assert lock["verifier_receipt_present"] is False
    assert lock["verifier_receipt_required"] is False
    assert lock["dry_run_executor_invoked"] is False
    assert lock["runner_invocation_performed"] is False
    assert lock["endpoint_executed"] is False
    assert lock["sql_executed"] is False
    assert lock["database_written"] is False
    assert lock["ready_for_verifier_invocation_now"] is False
    assert lock["endpoint_execution_allowed"] is False
    assert lock["sql_execution_allowed"] is False
    assert lock["database_write_allowed"] is False
    assert lock["database_apply_authorized"] is False
    assert lock["executes_database_apply"] is False
    assert lock["executes_endpoint"] is False
    assert lock["executes_sql"] is False
    assert lock["writes_database"] is False
    assert lock["stdout_included"] is False
    assert lock["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
        ]
        is True
    )
    assert contract["verifier_invocation_locked"] is True
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert "execution_envelope_freeze_proof_closeout_ready" in check_keys
    assert "frozen_envelope_verifier_handoff_ready" in check_keys
    assert "frozen_envelope_verifier_handoff_no_execute" in check_keys
    assert "verifier_invocation_lock_proof_bound" in check_keys
    assert "verifier_invocation_lock_proof_blocks_execution" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout_waits_without_ready_lock_closeout():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
    ]
    lock_closeout = closeout[
        "controlled_dry_run_verifier_invocation_lock_proof_closeout"
    ]
    receipt = lock_closeout["verifier_no_execution_receipt_proof"]
    contract = closeout[
        "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_FROZEN_ENVELOPE_VERIFIER_HANDOFF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_no_execution_receipt_proof_count"] == 1
    assert closeout["summary"]["verifier_no_execution_receipt_proof_field_count"] == 12
    assert closeout["summary"]["verifier_invocation_locked_count"] == 1
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["verifier_invocation_lock_proof_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-verifier-invocation-lock-proof-closeout-"
    )
    assert future["verifier_no_execution_receipt_proof_id"].endswith(
        "-verifier-no-execution-receipt-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
        ]
        is False
    )
    assert future["verifier_invocation_lock_proof_closeout_ready"] is False
    assert future["frozen_envelope_verifier_handoff_closeout_ready"] is False
    assert future["verifier_no_execution_receipt_proof_bound"] is False
    assert future["verifier_invocation_locked"] is True
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert lock_closeout["authorization_material_type"] == (
        "controlled_dry_run_verifier_invocation_lock_proof_closeout"
    )
    assert lock_closeout["verifier_invocation_lock_proof_closeout_only"] is True
    assert lock_closeout["verifier_no_execution_receipt_proof_only"] is True
    assert lock_closeout["verifier_invocation_locked"] is True
    assert lock_closeout["verifier_invocation_allowed"] is False
    assert lock_closeout["verifier_invoked"] is False
    assert lock_closeout["verifier_receipt_present"] is False
    assert lock_closeout["dry_run_executor_invoked"] is False
    assert lock_closeout["runner_invocation_performed"] is False
    assert lock_closeout["endpoint_executed"] is False
    assert lock_closeout["sql_executed"] is False
    assert lock_closeout["database_written"] is False
    assert receipt["receipt_status"] == "verifier_no_execution_receipt_proof_preview_ready"
    assert receipt["receipt_mode"] == "verifier_no_execution_receipt_proof_preview_only"
    assert receipt["verifier_no_execution_receipt_proof_field_count"] == 12
    assert receipt["verifier_invocation_locked"] is True
    assert receipt["verifier_invocation_allowed"] is False
    assert receipt["verifier_invoked"] is False
    assert receipt["verifier_receipt_present"] is False
    assert receipt["dry_run_executor_invoked"] is False
    assert receipt["runner_invocation_performed"] is False
    assert receipt["endpoint_executed"] is False
    assert receipt["sql_executed"] is False
    assert receipt["database_written"] is False
    assert receipt["ready_for_verifier_invocation_now"] is False
    assert receipt["endpoint_execution_allowed"] is False
    assert receipt["sql_execution_allowed"] is False
    assert receipt["database_write_allowed"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert receipt["stdout_included"] is False
    assert receipt["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        ]
        is False
    )
    assert contract["verifier_invocation_locked"] is True
    assert contract["verifier_invoked"] is False
    assert contract["verifier_receipt_present"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert "frozen_envelope_verifier_handoff_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "verifier_invocation_lock_proof_ready" in check_keys
    assert "verifier_invocation_lock_proof_no_execute" in check_keys
    assert "verifier_no_execution_receipt_proof_bound" in check_keys
    assert "verifier_no_execution_receipt_proof_blocks_execution" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "frozen_envelope_verifier_handoff_closeout_contract_blocks_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_after_fake_fetch_but_verifier_receipt_is_absent():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-verifier-no-receipt.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
    ]
    lock_closeout = closeout[
        "controlled_dry_run_verifier_invocation_lock_proof_closeout"
    ]
    receipt = lock_closeout["verifier_no_execution_receipt_proof"]
    lock = lock_closeout["verifier_invocation_lock_proof"]
    source_closeout = lock_closeout["frozen_envelope_verifier_handoff_closeout"]
    contract = closeout[
        "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_verifier_invocation_lock_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["verifier_no_execution_receipt_proof_count"] == 1
    assert closeout["summary"]["verifier_no_execution_receipt_proof_field_count"] == 12
    assert closeout["summary"]["verifier_invocation_locked_count"] == 1
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["reads_secret_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
        ]
        is True
    )
    assert future["verifier_invocation_lock_proof_closeout_ready"] is True
    assert future["frozen_envelope_verifier_handoff_closeout_ready"] is True
    assert future["verifier_invocation_lock_proof_ready"] is True
    assert future["verifier_no_execution_receipt_proof_bound"] is True
    assert future["verifier_invocation_locked"] is True
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert lock_closeout["ready_for_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"] is True
    assert lock_closeout["verifier_invocation_lock_proof_closeout_field_count"] == 12
    assert lock_closeout["verifier_invocation_lock_proof_closeout_acceptance_gate_count"] == 10
    assert lock_closeout["verifier_no_execution_receipt_proof_count"] == 1
    assert lock_closeout["verifier_no_execution_receipt_proof_field_count"] == 12
    assert lock_closeout["verifier_invocation_lock_proof_closeout_only"] is True
    assert lock_closeout["verifier_no_execution_receipt_proof_only"] is True
    assert lock_closeout["verifier_invocation_locked"] is True
    assert lock_closeout["verifier_invocation_allowed"] is False
    assert lock_closeout["verifier_invoked"] is False
    assert lock_closeout["verifier_receipt_present"] is False
    assert lock_closeout["dry_run_executor_invoked"] is False
    assert lock_closeout["runner_invocation_performed"] is False
    assert lock_closeout["endpoint_executed"] is False
    assert lock_closeout["sql_executed"] is False
    assert lock_closeout["database_written"] is False
    assert receipt["receipt_proof_id"] == future["verifier_no_execution_receipt_proof_id"]
    assert (
        receipt["source_verifier_invocation_lock_proof_closeout_id"]
        == future["verifier_invocation_lock_proof_closeout_id"]
    )
    assert receipt["source_verifier_invocation_lock_proof_id"] == lock["lock_proof_id"]
    assert (
        receipt["source_frozen_envelope_verifier_handoff_closeout_id"]
        == source_closeout["frozen_envelope_verifier_handoff_closeout_id"]
    )
    assert receipt["required_command_shape_hash"] == lock["required_command_shape_hash"]
    assert receipt["receipt_status"] == "verifier_no_execution_receipt_proof_preview_ready"
    assert receipt["receipt_mode"] == "verifier_no_execution_receipt_proof_preview_only"
    assert receipt["verifier_invocation_locked"] is True
    assert receipt["verifier_invocation_allowed"] is False
    assert receipt["verifier_invoked"] is False
    assert receipt["verifier_receipt_present"] is False
    assert receipt["verifier_receipt_required"] is False
    assert receipt["dry_run_executor_invoked"] is False
    assert receipt["runner_invocation_performed"] is False
    assert receipt["endpoint_executed"] is False
    assert receipt["sql_executed"] is False
    assert receipt["database_written"] is False
    assert receipt["ready_for_verifier_invocation_now"] is False
    assert receipt["endpoint_execution_allowed"] is False
    assert receipt["sql_execution_allowed"] is False
    assert receipt["database_write_allowed"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert receipt["stdout_included"] is False
    assert receipt["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        ]
        is True
    )
    assert contract["verifier_invocation_locked"] is True
    assert contract["verifier_invoked"] is False
    assert contract["verifier_receipt_present"] is False
    assert contract["executes_database_apply"] is False
    assert contract["executes_endpoint"] is False
    assert contract["executes_sql"] is False
    assert contract["database_apply_authorized"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert "frozen_envelope_verifier_handoff_closeout_ready" in check_keys
    assert "verifier_invocation_lock_proof_ready" in check_keys
    assert "verifier_invocation_lock_proof_no_execute" in check_keys
    assert "verifier_no_execution_receipt_proof_bound" in check_keys
    assert "verifier_no_execution_receipt_proof_blocks_execution" in check_keys
    assert "preview_has_no_side_effects_no_execution_no_signing" in check_keys
    assert closeout["safety"]["reads_secret_in_preview"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_waits_without_ready_receipt_proof():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
    ]
    receipt_closeout = closeout[
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
    ]
    guard = receipt_closeout["verifier_receipt_persistence_guard_proof"]
    contract = closeout[
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_INVOCATION_LOCK_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["verifier_receipt_persistence_guard_proof_count"] == 1
    assert closeout["summary"]["verifier_receipt_persistence_guard_proof_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_persistence_locked_count"] == 1
    assert closeout["summary"]["verifier_receipt_persistence_allowed_count"] == 0
    assert closeout["summary"]["verifier_receipt_persisted_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["verifier_no_execution_receipt_proof_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-verifier-no-execution-receipt-proof-closeout-"
    )
    assert future["verifier_receipt_persistence_guard_proof_id"].endswith(
        "-verifier-receipt-persistence-guard-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
        ]
        is False
    )
    assert future["verifier_no_execution_receipt_proof_closeout_ready"] is False
    assert future["verifier_invocation_lock_proof_closeout_ready"] is False
    assert future["verifier_receipt_persistence_guard_proof_bound"] is False
    assert future["verifier_receipt_persistence_locked"] is True
    assert future["verifier_receipt_persistence_allowed"] is False
    assert future["verifier_receipt_persisted"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["verifier_invoked"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_receipt_persistence_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert receipt_closeout["authorization_material_type"] == (
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
    )
    assert receipt_closeout["verifier_no_execution_receipt_proof_closeout_only"] is True
    assert receipt_closeout["verifier_receipt_persistence_guard_proof_only"] is True
    assert receipt_closeout["verifier_receipt_persistence_locked"] is True
    assert receipt_closeout["verifier_receipt_persistence_allowed"] is False
    assert receipt_closeout["verifier_receipt_persisted"] is False
    assert receipt_closeout["persists_verifier_receipt"] is False
    assert receipt_closeout["verifier_invoked"] is False
    assert receipt_closeout["endpoint_executed"] is False
    assert receipt_closeout["sql_executed"] is False
    assert receipt_closeout["database_written"] is False
    assert guard["guard_status"] == "verifier_receipt_persistence_guard_proof_preview_ready"
    assert guard["guard_mode"] == "verifier_receipt_persistence_guard_proof_preview_only"
    assert guard["verifier_receipt_persistence_guard_proof_field_count"] == 12
    assert guard["verifier_receipt_persistence_locked"] is True
    assert guard["verifier_receipt_persistence_allowed"] is False
    assert guard["verifier_receipt_persisted"] is False
    assert guard["persists_verifier_receipt"] is False
    assert guard["verifier_invoked"] is False
    assert guard["endpoint_executed"] is False
    assert guard["sql_executed"] is False
    assert guard["database_written"] is False
    assert guard["ready_for_verifier_receipt_persistence_now"] is False
    assert guard["endpoint_execution_allowed"] is False
    assert guard["sql_execution_allowed"] is False
    assert guard["database_write_allowed"] is False
    assert guard["database_apply_authorized"] is False
    assert guard["stdout_included"] is False
    assert guard["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        ]
        is False
    )
    assert contract["verifier_receipt_persistence_locked"] is True
    assert contract["verifier_receipt_persisted"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_receipt_persistence_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "verifier_invocation_lock_proof_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "verifier_no_execution_receipt_proof_ready" in check_keys
    assert "verifier_no_execution_receipt_proof_no_execute" in check_keys
    assert "verifier_receipt_persistence_guard_proof_bound" in check_keys
    assert "verifier_receipt_persistence_guard_proof_blocks_persistence" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "verifier_invocation_lock_proof_closeout_contract_blocks_persistence_and_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_persistence_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_after_fake_fetch_but_persistence_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-persistence-guard.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
    ]
    receipt_closeout = closeout[
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
    ]
    guard = receipt_closeout["verifier_receipt_persistence_guard_proof"]
    receipt = receipt_closeout["verifier_no_execution_receipt_proof"]
    source_closeout = receipt_closeout["verifier_invocation_lock_proof_closeout"]
    contract = closeout[
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["verifier_receipt_persistence_guard_proof_count"] == 1
    assert closeout["summary"]["verifier_receipt_persistence_guard_proof_field_count"] == 12
    assert closeout["summary"]["verifier_receipt_persistence_locked_count"] == 1
    assert closeout["summary"]["verifier_receipt_persistence_allowed_count"] == 0
    assert closeout["summary"]["verifier_receipt_persisted_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["verifier_receipt_present_count"] == 0
    assert closeout["summary"]["dry_run_executor_invoked_count"] == 0
    assert closeout["summary"]["runner_invocation_performed_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
        ]
        is True
    )
    assert future["verifier_no_execution_receipt_proof_closeout_ready"] is True
    assert future["verifier_invocation_lock_proof_closeout_ready"] is True
    assert future["verifier_no_execution_receipt_proof_ready"] is True
    assert future["verifier_receipt_persistence_guard_proof_bound"] is True
    assert future["verifier_receipt_persistence_locked"] is True
    assert future["verifier_receipt_persistence_allowed"] is False
    assert future["verifier_receipt_persisted"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["verifier_invoked"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_receipt_persistence_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert receipt_closeout["ready_for_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"] is True
    assert receipt_closeout["verifier_no_execution_receipt_proof_closeout_field_count"] == 12
    assert receipt_closeout["verifier_no_execution_receipt_proof_closeout_acceptance_gate_count"] == 10
    assert receipt_closeout["verifier_receipt_persistence_guard_proof_count"] == 1
    assert receipt_closeout["verifier_receipt_persistence_guard_proof_field_count"] == 12
    assert receipt_closeout["verifier_no_execution_receipt_proof_closeout_only"] is True
    assert receipt_closeout["verifier_receipt_persistence_guard_proof_only"] is True
    assert receipt_closeout["verifier_receipt_persistence_locked"] is True
    assert receipt_closeout["verifier_receipt_persistence_allowed"] is False
    assert receipt_closeout["verifier_receipt_persisted"] is False
    assert receipt_closeout["persists_verifier_receipt"] is False
    assert receipt_closeout["verifier_invoked"] is False
    assert receipt_closeout["endpoint_executed"] is False
    assert receipt_closeout["sql_executed"] is False
    assert receipt_closeout["database_written"] is False
    assert guard["guard_proof_id"] == future["verifier_receipt_persistence_guard_proof_id"]
    assert (
        guard["source_verifier_no_execution_receipt_proof_closeout_id"]
        == future["verifier_no_execution_receipt_proof_closeout_id"]
    )
    assert (
        guard["source_verifier_invocation_lock_proof_closeout_id"]
        == source_closeout["verifier_invocation_lock_proof_closeout_id"]
    )
    assert guard["source_verifier_no_execution_receipt_proof_id"] == receipt["receipt_proof_id"]
    assert guard["required_command_shape_hash"] == receipt["required_command_shape_hash"]
    assert guard["guard_status"] == "verifier_receipt_persistence_guard_proof_preview_ready"
    assert guard["guard_mode"] == "verifier_receipt_persistence_guard_proof_preview_only"
    assert guard["verifier_receipt_persistence_locked"] is True
    assert guard["verifier_receipt_persistence_allowed"] is False
    assert guard["verifier_receipt_persisted"] is False
    assert guard["persists_verifier_receipt"] is False
    assert guard["persistence_receipt_present"] is False
    assert guard["verifier_invoked"] is False
    assert guard["endpoint_executed"] is False
    assert guard["sql_executed"] is False
    assert guard["database_written"] is False
    assert guard["ready_for_verifier_receipt_persistence_now"] is False
    assert guard["endpoint_execution_allowed"] is False
    assert guard["sql_execution_allowed"] is False
    assert guard["database_write_allowed"] is False
    assert guard["database_apply_authorized"] is False
    assert guard["executes_database_apply"] is False
    assert guard["executes_endpoint"] is False
    assert guard["executes_sql"] is False
    assert guard["writes_database"] is False
    assert guard["stdout_included"] is False
    assert guard["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        ]
        is True
    )
    assert contract["verifier_receipt_persistence_locked"] is True
    assert contract["verifier_receipt_persistence_allowed"] is False
    assert contract["verifier_receipt_persisted"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_receipt_persistence_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "verifier_no_execution_receipt_proof_ready" in check_keys
    assert "verifier_no_execution_receipt_proof_no_execute" in check_keys
    assert "verifier_receipt_persistence_guard_proof_bound" in check_keys
    assert "verifier_receipt_persistence_guard_proof_blocks_persistence" in check_keys
    assert "preview_has_no_side_effects_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_waits_without_ready_storage_boundary():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
    ]
    storage_closeout = closeout[
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
    ]
    storage = storage_closeout["receipt_persistence_storage_boundary_proof"]
    contract = closeout[
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_NO_EXECUTION_RECEIPT_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["receipt_persistence_storage_boundary_proof_count"] == 1
    assert closeout["summary"]["receipt_persistence_storage_boundary_proof_field_count"] == 12
    assert closeout["summary"]["receipt_persistence_storage_boundary_locked_count"] == 1
    assert closeout["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_written_count"] == 0
    assert closeout["summary"]["verifier_receipt_persistence_allowed_count"] == 0
    assert closeout["summary"]["verifier_receipt_persisted_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["verifier_receipt_persistence_guard_proof_closeout_id"].startswith(
        "pchome-db-apply-controlled-dry-run-verifier-receipt-persistence-guard-proof-closeout-"
    )
    assert future["receipt_persistence_storage_boundary_proof_id"].endswith(
        "-receipt-persistence-storage-boundary-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
        ]
        is False
    )
    assert future["receipt_persistence_storage_boundary_locked"] is True
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["verifier_receipt_persistence_allowed"] is False
    assert future["verifier_receipt_persisted"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_receipt_persistence_storage_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert storage_closeout["verifier_receipt_persistence_guard_proof_closeout_only"] is True
    assert storage_closeout["receipt_persistence_storage_boundary_proof_only"] is True
    assert storage_closeout["receipt_persistence_storage_boundary_locked"] is True
    assert storage_closeout["receipt_persistence_storage_write_allowed"] is False
    assert storage_closeout["receipt_persistence_storage_written"] is False
    assert storage_closeout["persists_verifier_receipt"] is False
    assert storage_closeout["endpoint_executed"] is False
    assert storage_closeout["sql_executed"] is False
    assert storage_closeout["database_written"] is False
    assert storage["storage_boundary_status"] == "receipt_persistence_storage_boundary_proof_preview_ready"
    assert storage["storage_boundary_mode"] == "receipt_persistence_storage_boundary_proof_preview_only"
    assert storage["receipt_persistence_storage_boundary_proof_field_count"] == 12
    assert storage["receipt_persistence_storage_boundary_locked"] is True
    assert storage["receipt_persistence_storage_write_allowed"] is False
    assert storage["receipt_persistence_storage_written"] is False
    assert storage["verifier_receipt_persistence_allowed"] is False
    assert storage["verifier_receipt_persisted"] is False
    assert storage["persists_verifier_receipt"] is False
    assert storage["endpoint_execution_allowed"] is False
    assert storage["sql_execution_allowed"] is False
    assert storage["database_write_allowed"] is False
    assert storage["database_apply_authorized"] is False
    assert storage["stdout_included"] is False
    assert storage["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        ]
        is False
    )
    assert contract["receipt_persistence_storage_boundary_locked"] is True
    assert contract["receipt_persistence_storage_write_allowed"] is False
    assert contract["receipt_persistence_storage_written"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_receipt_persistence_storage_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "verifier_no_execution_receipt_proof_closeout_ready" in check_keys
    assert "source_chain_ids_match" in check_keys
    assert "verifier_receipt_persistence_guard_proof_ready" in check_keys
    assert "verifier_receipt_persistence_guard_proof_no_persistence" in check_keys
    assert "receipt_persistence_storage_boundary_proof_bound" in check_keys
    assert "receipt_persistence_storage_boundary_proof_blocks_storage" in check_keys
    assert "previous_closeouts_carried_forward" in check_keys
    assert "target_migration_hash_locked" in check_keys
    assert "rollback_and_post_apply_verifier_bound" in check_keys
    assert "verifier_no_execution_receipt_proof_closeout_contract_blocks_storage_persistence_and_database_apply" in check_keys
    assert "preview_has_no_side_effects_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_after_fake_fetch_but_storage_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-storage-boundary.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
    ]
    storage_closeout = closeout[
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
    ]
    storage = storage_closeout["receipt_persistence_storage_boundary_proof"]
    guard = storage_closeout["verifier_receipt_persistence_guard_proof"]
    contract = closeout[
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["receipt_persistence_storage_boundary_proof_count"] == 1
    assert closeout["summary"]["receipt_persistence_storage_boundary_proof_field_count"] == 12
    assert closeout["summary"]["receipt_persistence_storage_boundary_locked_count"] == 1
    assert closeout["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_written_count"] == 0
    assert closeout["summary"]["verifier_receipt_persistence_allowed_count"] == 0
    assert closeout["summary"]["verifier_receipt_persisted_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["endpoint_executed_count"] == 0
    assert closeout["summary"]["sql_executed_count"] == 0
    assert closeout["summary"]["database_written_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert closeout["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
        ]
        is True
    )
    assert future["verifier_receipt_persistence_guard_proof_closeout_ready"] is True
    assert future["verifier_no_execution_receipt_proof_closeout_ready"] is True
    assert future["verifier_receipt_persistence_guard_proof_ready"] is True
    assert future["receipt_persistence_storage_boundary_proof_bound"] is True
    assert future["receipt_persistence_storage_boundary_locked"] is True
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["verifier_receipt_persistence_allowed"] is False
    assert future["verifier_receipt_persisted"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_receipt_persistence_storage_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert storage_closeout["ready_for_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"] is True
    assert storage_closeout["verifier_receipt_persistence_guard_proof_closeout_field_count"] == 12
    assert storage_closeout["verifier_receipt_persistence_guard_proof_closeout_acceptance_gate_count"] == 10
    assert storage_closeout["receipt_persistence_storage_boundary_proof_count"] == 1
    assert storage_closeout["receipt_persistence_storage_boundary_proof_field_count"] == 12
    assert storage_closeout["verifier_receipt_persistence_guard_proof_closeout_only"] is True
    assert storage_closeout["receipt_persistence_storage_boundary_proof_only"] is True
    assert storage_closeout["receipt_persistence_storage_boundary_locked"] is True
    assert storage_closeout["receipt_persistence_storage_write_allowed"] is False
    assert storage_closeout["receipt_persistence_storage_written"] is False
    assert storage_closeout["verifier_receipt_persistence_allowed"] is False
    assert storage_closeout["verifier_receipt_persisted"] is False
    assert storage_closeout["persists_verifier_receipt"] is False
    assert storage_closeout["endpoint_executed"] is False
    assert storage_closeout["sql_executed"] is False
    assert storage_closeout["database_written"] is False
    assert storage["storage_boundary_proof_id"] == future["receipt_persistence_storage_boundary_proof_id"]
    assert (
        storage["source_verifier_receipt_persistence_guard_proof_closeout_id"]
        == future["verifier_receipt_persistence_guard_proof_closeout_id"]
    )
    assert (
        storage["source_verifier_receipt_persistence_guard_proof_id"]
        == guard["guard_proof_id"]
    )
    assert storage["required_command_shape_hash"] == guard["required_command_shape_hash"]
    assert storage["storage_boundary_status"] == "receipt_persistence_storage_boundary_proof_preview_ready"
    assert storage["storage_boundary_mode"] == "receipt_persistence_storage_boundary_proof_preview_only"
    assert storage["receipt_persistence_storage_boundary_locked"] is True
    assert storage["receipt_persistence_storage_write_allowed"] is False
    assert storage["receipt_persistence_storage_written"] is False
    assert storage["verifier_receipt_persistence_allowed"] is False
    assert storage["verifier_receipt_persisted"] is False
    assert storage["persists_verifier_receipt"] is False
    assert storage["endpoint_executed"] is False
    assert storage["sql_executed"] is False
    assert storage["database_written"] is False
    assert storage["ready_for_receipt_persistence_storage_now"] is False
    assert storage["endpoint_execution_allowed"] is False
    assert storage["sql_execution_allowed"] is False
    assert storage["database_write_allowed"] is False
    assert storage["database_apply_authorized"] is False
    assert storage["executes_database_apply"] is False
    assert storage["executes_endpoint"] is False
    assert storage["executes_sql"] is False
    assert storage["writes_database"] is False
    assert storage["stdout_included"] is False
    assert storage["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        ]
        is True
    )
    assert contract["receipt_persistence_storage_boundary_locked"] is True
    assert contract["receipt_persistence_storage_write_allowed"] is False
    assert contract["receipt_persistence_storage_written"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_receipt_persistence_storage_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "verifier_receipt_persistence_guard_proof_ready" in check_keys
    assert "verifier_receipt_persistence_guard_proof_no_persistence" in check_keys
    assert "receipt_persistence_storage_boundary_proof_bound" in check_keys
    assert "receipt_persistence_storage_boundary_proof_blocks_storage" in check_keys
    assert "preview_has_no_side_effects_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_waits_without_ready_ledger():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
    ]
    storage_closeout = closeout[
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
    ]
    ledger = storage_closeout["storage_boundary_no_write_ledger_proof"]
    contract = closeout[
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_VERIFIER_RECEIPT_PERSISTENCE_GUARD_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["storage_boundary_no_write_ledger_proof_count"] == 1
    assert closeout["summary"]["storage_boundary_no_write_ledger_proof_field_count"] == 12
    assert closeout["summary"]["storage_boundary_write_locked_count"] == 1
    assert closeout["summary"]["storage_boundary_write_allowed_count"] == 0
    assert closeout["summary"]["storage_boundary_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future["storage_boundary_no_write_ledger_proof_id"].endswith(
        "-storage-boundary-no-write-ledger-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        ]
        is False
    )
    assert future["storage_boundary_write_locked"] is True
    assert future["storage_boundary_write_allowed"] is False
    assert future["storage_boundary_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert storage_closeout["receipt_persistence_storage_boundary_proof_closeout_only"] is True
    assert storage_closeout["storage_boundary_no_write_ledger_proof_only"] is True
    assert storage_closeout["storage_boundary_no_write_ledger_proof_count"] == 1
    assert storage_closeout["storage_boundary_no_write_ledger_proof_field_count"] == 12
    assert storage_closeout["storage_boundary_write_locked"] is True
    assert storage_closeout["storage_boundary_write_allowed"] is False
    assert storage_closeout["storage_boundary_written"] is False
    assert storage_closeout["ledger_write_allowed"] is False
    assert storage_closeout["ledger_written"] is False
    assert storage_closeout["receipt_persistence_storage_write_allowed"] is False
    assert storage_closeout["receipt_persistence_storage_written"] is False
    assert storage_closeout["persists_verifier_receipt"] is False
    assert storage_closeout["endpoint_executed"] is False
    assert storage_closeout["sql_executed"] is False
    assert storage_closeout["database_written"] is False
    assert ledger["ledger_status"] == "storage_boundary_no_write_ledger_proof_preview_ready"
    assert ledger["ledger_mode"] == "storage_boundary_no_write_ledger_proof_preview_only"
    assert ledger["storage_boundary_write_locked"] is True
    assert ledger["storage_boundary_write_allowed"] is False
    assert ledger["storage_boundary_written"] is False
    assert ledger["ledger_write_allowed"] is False
    assert ledger["ledger_written"] is False
    assert ledger["receipt_persistence_storage_write_allowed"] is False
    assert ledger["receipt_persistence_storage_written"] is False
    assert ledger["persists_verifier_receipt"] is False
    assert ledger["endpoint_executed"] is False
    assert ledger["sql_executed"] is False
    assert ledger["database_written"] is False
    assert ledger["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        ]
        is False
    )
    assert contract["storage_boundary_write_allowed"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["receipt_persistence_storage_write_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "verifier_receipt_persistence_guard_proof_closeout_ready" in check_keys
    assert "receipt_persistence_storage_boundary_proof_ready" in check_keys
    assert "receipt_persistence_storage_boundary_proof_no_write" in check_keys
    assert "storage_boundary_no_write_ledger_proof_bound" in check_keys
    assert "storage_boundary_no_write_ledger_proof_blocks_write" in check_keys
    assert "preview_has_no_side_effects_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_after_fake_fetch_but_ledger_write_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-storage-ledger.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
    ]
    storage_closeout = closeout[
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
    ]
    previous_storage_closeout = storage_closeout[
        "verifier_receipt_persistence_guard_proof_closeout"
    ]
    storage = storage_closeout["receipt_persistence_storage_boundary_proof"]
    ledger = storage_closeout["storage_boundary_no_write_ledger_proof"]
    contract = closeout[
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["storage_boundary_no_write_ledger_proof_count"] == 1
    assert closeout["summary"]["storage_boundary_no_write_ledger_proof_field_count"] == 12
    assert closeout["summary"]["storage_boundary_write_locked_count"] == 1
    assert closeout["summary"]["storage_boundary_write_allowed_count"] == 0
    assert closeout["summary"]["storage_boundary_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
        ]
        is True
    )
    assert future["receipt_persistence_storage_boundary_proof_closeout_ready"] is True
    assert future["verifier_receipt_persistence_guard_proof_closeout_ready"] is True
    assert future["receipt_persistence_storage_boundary_proof_ready"] is True
    assert future["storage_boundary_no_write_ledger_proof_bound"] is True
    assert future["storage_boundary_write_locked"] is True
    assert future["storage_boundary_write_allowed"] is False
    assert future["storage_boundary_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert storage_closeout["receipt_persistence_storage_boundary_proof_closeout_field_count"] == 12
    assert storage_closeout["receipt_persistence_storage_boundary_proof_closeout_acceptance_gate_count"] == 10
    assert storage_closeout["receipt_persistence_storage_boundary_proof_closeout_only"] is True
    assert storage_closeout["storage_boundary_no_write_ledger_proof_only"] is True
    assert storage_closeout["source_verifier_receipt_persistence_guard_proof_closeout_id"] == previous_storage_closeout["verifier_receipt_persistence_guard_proof_closeout_id"]
    assert storage_closeout["source_receipt_persistence_storage_boundary_proof_id"] == storage["storage_boundary_proof_id"]
    assert ledger["source_receipt_persistence_storage_boundary_proof_closeout_id"] == storage_closeout["receipt_persistence_storage_boundary_proof_closeout_id"]
    assert ledger["source_verifier_receipt_persistence_guard_proof_closeout_id"] == previous_storage_closeout["verifier_receipt_persistence_guard_proof_closeout_id"]
    assert ledger["source_receipt_persistence_storage_boundary_proof_id"] == storage["storage_boundary_proof_id"]
    assert ledger["required_command_shape_hash"] == storage["required_command_shape_hash"]
    assert ledger["ledger_status"] == "storage_boundary_no_write_ledger_proof_preview_ready"
    assert ledger["ledger_mode"] == "storage_boundary_no_write_ledger_proof_preview_only"
    assert ledger["storage_boundary_write_locked"] is True
    assert ledger["storage_boundary_write_allowed"] is False
    assert ledger["storage_boundary_written"] is False
    assert ledger["ledger_write_allowed"] is False
    assert ledger["ledger_written"] is False
    assert ledger["receipt_persistence_storage_write_allowed"] is False
    assert ledger["receipt_persistence_storage_written"] is False
    assert ledger["verifier_receipt_persistence_allowed"] is False
    assert ledger["verifier_receipt_persisted"] is False
    assert ledger["persists_verifier_receipt"] is False
    assert ledger["verifier_invoked"] is False
    assert ledger["dry_run_executor_invoked"] is False
    assert ledger["runner_invocation_performed"] is False
    assert ledger["endpoint_executed"] is False
    assert ledger["sql_executed"] is False
    assert ledger["database_written"] is False
    assert ledger["ready_for_database_apply_now"] is False
    assert ledger["ready_for_storage_boundary_ledger_write_now"] is False
    assert ledger["ready_for_receipt_persistence_storage_now"] is False
    assert ledger["endpoint_execution_allowed"] is False
    assert ledger["sql_execution_allowed"] is False
    assert ledger["database_write_allowed"] is False
    assert ledger["database_apply_authorized"] is False
    assert ledger["stdout_included"] is False
    assert ledger["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        ]
        is True
    )
    assert contract["storage_boundary_write_allowed"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["receipt_persistence_storage_write_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_storage_boundary_ledger_write_now"] is False
    assert contract["ready_for_receipt_persistence_storage_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "storage_boundary_no_write_ledger_proof_bound" in check_keys
    assert "storage_boundary_no_write_ledger_proof_blocks_write" in check_keys
    assert "preview_has_no_side_effects_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_waits_without_ready_retention():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
    ]
    ledger_closeout = closeout[
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
    ]
    retention = ledger_closeout["no_write_ledger_retention_proof"]
    contract = closeout[
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_RECEIPT_PERSISTENCE_STORAGE_BOUNDARY_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["no_write_ledger_retention_proof_count"] == 1
    assert closeout["summary"]["no_write_ledger_retention_proof_field_count"] == 12
    assert closeout["summary"]["ledger_retention_write_locked_count"] == 1
    assert closeout["summary"]["ledger_retention_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_retention_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future["no_write_ledger_retention_proof_id"].endswith(
        "-no-write-ledger-retention-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        ]
        is False
    )
    assert future["ledger_retention_write_locked"] is True
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert ledger_closeout["storage_boundary_no_write_ledger_proof_closeout_only"] is True
    assert ledger_closeout["no_write_ledger_retention_proof_only"] is True
    assert ledger_closeout["no_write_ledger_retention_proof_count"] == 1
    assert ledger_closeout["no_write_ledger_retention_proof_field_count"] == 12
    assert ledger_closeout["ledger_retention_write_locked"] is True
    assert ledger_closeout["ledger_retention_write_allowed"] is False
    assert ledger_closeout["ledger_retention_written"] is False
    assert ledger_closeout["ledger_write_allowed"] is False
    assert ledger_closeout["ledger_written"] is False
    assert ledger_closeout["persists_verifier_receipt"] is False
    assert ledger_closeout["endpoint_executed"] is False
    assert ledger_closeout["sql_executed"] is False
    assert ledger_closeout["database_written"] is False
    assert retention["retention_status"] == "no_write_ledger_retention_proof_preview_ready"
    assert retention["retention_mode"] == "no_write_ledger_retention_proof_preview_only"
    assert retention["ledger_retention_write_locked"] is True
    assert retention["ledger_retention_write_allowed"] is False
    assert retention["ledger_retention_written"] is False
    assert retention["ledger_write_allowed"] is False
    assert retention["ledger_written"] is False
    assert retention["receipt_persistence_storage_write_allowed"] is False
    assert retention["receipt_persistence_storage_written"] is False
    assert retention["persists_verifier_receipt"] is False
    assert retention["endpoint_executed"] is False
    assert retention["sql_executed"] is False
    assert retention["database_written"] is False
    assert retention["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        ]
        is False
    )
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["ledger_retention_written"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "receipt_persistence_storage_boundary_proof_closeout_ready" in check_keys
    assert "storage_boundary_no_write_ledger_proof_ready" in check_keys
    assert "storage_boundary_no_write_ledger_proof_no_write" in check_keys
    assert "no_write_ledger_retention_proof_bound" in check_keys
    assert "no_write_ledger_retention_proof_blocks_persistence" in check_keys
    assert "preview_has_no_side_effects_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert "manual_review_not_required_for_safe_preview" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_after_fake_fetch_but_retention_write_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-ledger-retention.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
    ]
    ledger_closeout = closeout[
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
    ]
    source_closeout = ledger_closeout[
        "receipt_persistence_storage_boundary_proof_closeout"
    ]
    ledger = ledger_closeout["storage_boundary_no_write_ledger_proof"]
    retention = ledger_closeout["no_write_ledger_retention_proof"]
    contract = closeout[
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["no_write_ledger_retention_proof_count"] == 1
    assert closeout["summary"]["no_write_ledger_retention_proof_field_count"] == 12
    assert closeout["summary"]["ledger_retention_write_locked_count"] == 1
    assert closeout["summary"]["ledger_retention_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_retention_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert closeout["summary"]["receipt_persistence_storage_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout"
        ]
        is True
    )
    assert future["storage_boundary_no_write_ledger_proof_closeout_ready"] is True
    assert future["receipt_persistence_storage_boundary_proof_closeout_ready"] is True
    assert future["storage_boundary_no_write_ledger_proof_ready"] is True
    assert future["no_write_ledger_retention_proof_bound"] is True
    assert future["ledger_retention_write_locked"] is True
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert ledger_closeout["storage_boundary_no_write_ledger_proof_closeout_field_count"] == 12
    assert ledger_closeout["storage_boundary_no_write_ledger_proof_closeout_acceptance_gate_count"] == 10
    assert ledger_closeout["storage_boundary_no_write_ledger_proof_closeout_only"] is True
    assert ledger_closeout["no_write_ledger_retention_proof_only"] is True
    assert ledger_closeout["source_receipt_persistence_storage_boundary_proof_closeout_id"] == source_closeout["receipt_persistence_storage_boundary_proof_closeout_id"]
    assert ledger_closeout["source_storage_boundary_no_write_ledger_proof_id"] == ledger["ledger_proof_id"]
    assert retention["source_storage_boundary_no_write_ledger_proof_closeout_id"] == ledger_closeout["storage_boundary_no_write_ledger_proof_closeout_id"]
    assert retention["source_storage_boundary_no_write_ledger_proof_id"] == ledger["ledger_proof_id"]
    assert retention["source_receipt_persistence_storage_boundary_proof_closeout_id"] == source_closeout["receipt_persistence_storage_boundary_proof_closeout_id"]
    assert retention["required_command_shape_hash"] == ledger["required_command_shape_hash"]
    assert retention["retention_status"] == "no_write_ledger_retention_proof_preview_ready"
    assert retention["retention_mode"] == "no_write_ledger_retention_proof_preview_only"
    assert retention["ledger_retention_write_locked"] is True
    assert retention["ledger_retention_write_allowed"] is False
    assert retention["ledger_retention_written"] is False
    assert retention["retention_receipt_present"] is False
    assert retention["retention_receipt_required"] is False
    assert retention["ledger_write_allowed"] is False
    assert retention["ledger_written"] is False
    assert retention["receipt_persistence_storage_write_allowed"] is False
    assert retention["receipt_persistence_storage_written"] is False
    assert retention["verifier_receipt_persistence_allowed"] is False
    assert retention["verifier_receipt_persisted"] is False
    assert retention["persists_verifier_receipt"] is False
    assert retention["verifier_invoked"] is False
    assert retention["dry_run_executor_invoked"] is False
    assert retention["runner_invocation_performed"] is False
    assert retention["endpoint_executed"] is False
    assert retention["sql_executed"] is False
    assert retention["database_written"] is False
    assert retention["ready_for_database_apply_now"] is False
    assert retention["ready_for_no_write_ledger_retention_now"] is False
    assert retention["ready_for_storage_boundary_ledger_write_now"] is False
    assert retention["endpoint_execution_allowed"] is False
    assert retention["sql_execution_allowed"] is False
    assert retention["database_write_allowed"] is False
    assert retention["database_apply_authorized"] is False
    assert retention["stdout_included"] is False
    assert retention["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        ]
        is True
    )
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["ledger_retention_written"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["ledger_written"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_no_write_ledger_retention_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "no_write_ledger_retention_proof_bound" in check_keys
    assert "no_write_ledger_retention_proof_blocks_persistence" in check_keys
    assert "preview_has_no_side_effects_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False

def test_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout_waits_without_ready_archive():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
    ]
    archive_closeout = closeout[
        "controlled_dry_run_no_write_ledger_retention_proof_closeout"
    ]
    archive = archive_closeout["retention_boundary_no_write_archive_proof"]
    contract = closeout[
        "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_STORAGE_BOUNDARY_NO_WRITE_LEDGER_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["retention_boundary_no_write_archive_proof_count"] == 1
    assert closeout["summary"]["retention_boundary_no_write_archive_proof_field_count"] == 12
    assert closeout["summary"]["retention_archive_write_locked_count"] == 1
    assert closeout["summary"]["retention_archive_write_allowed_count"] == 0
    assert closeout["summary"]["retention_archive_written_count"] == 0
    assert closeout["summary"]["ledger_retention_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_retention_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future["retention_boundary_no_write_archive_proof_id"].endswith(
        "-retention-boundary-no-write-archive-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        ]
        is False
    )
    assert future["retention_archive_write_locked"] is True
    assert future["retention_archive_write_allowed"] is False
    assert future["retention_archive_written"] is False
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert archive_closeout["no_write_ledger_retention_proof_closeout_only"] is True
    assert archive_closeout["retention_boundary_no_write_archive_proof_only"] is True
    assert archive_closeout["retention_boundary_no_write_archive_proof_count"] == 1
    assert archive_closeout["retention_boundary_no_write_archive_proof_field_count"] == 12
    assert archive_closeout["retention_archive_write_locked"] is True
    assert archive_closeout["retention_archive_write_allowed"] is False
    assert archive_closeout["retention_archive_written"] is False
    assert archive_closeout["ledger_retention_write_allowed"] is False
    assert archive_closeout["ledger_retention_written"] is False
    assert archive_closeout["persists_verifier_receipt"] is False
    assert archive_closeout["endpoint_executed"] is False
    assert archive_closeout["sql_executed"] is False
    assert archive_closeout["database_written"] is False
    assert archive["archive_status"] == "retention_boundary_no_write_archive_proof_preview_ready"
    assert archive["archive_mode"] == "retention_boundary_no_write_archive_proof_preview_only"
    assert archive["retention_archive_write_locked"] is True
    assert archive["retention_archive_write_allowed"] is False
    assert archive["retention_archive_written"] is False
    assert archive["ledger_retention_write_allowed"] is False
    assert archive["ledger_retention_written"] is False
    assert archive["ledger_write_allowed"] is False
    assert archive["ledger_written"] is False
    assert archive["persists_verifier_receipt"] is False
    assert archive["endpoint_executed"] is False
    assert archive["sql_executed"] is False
    assert archive["database_written"] is False
    assert archive["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        ]
        is False
    )
    assert contract["retention_archive_write_allowed"] is False
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "storage_boundary_no_write_ledger_proof_closeout_ready" in check_keys
    assert "no_write_ledger_retention_proof_ready" in check_keys
    assert "no_write_ledger_retention_proof_no_write" in check_keys
    assert "retention_boundary_no_write_archive_proof_bound" in check_keys
    assert "retention_boundary_no_write_archive_proof_blocks_archive" in check_keys
    assert "preview_has_no_side_effects_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_after_fake_fetch_but_archive_write_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-retention-archive.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
    ]
    archive_closeout = closeout[
        "controlled_dry_run_no_write_ledger_retention_proof_closeout"
    ]
    source_closeout = archive_closeout[
        "storage_boundary_no_write_ledger_proof_closeout"
    ]
    retention = archive_closeout["no_write_ledger_retention_proof"]
    archive = archive_closeout["retention_boundary_no_write_archive_proof"]
    contract = closeout[
        "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_no_write_ledger_retention_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["retention_boundary_no_write_archive_proof_count"] == 1
    assert closeout["summary"]["retention_boundary_no_write_archive_proof_field_count"] == 12
    assert closeout["summary"]["retention_archive_write_locked_count"] == 1
    assert closeout["summary"]["retention_archive_write_allowed_count"] == 0
    assert closeout["summary"]["retention_archive_written_count"] == 0
    assert closeout["summary"]["ledger_retention_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_retention_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
        ]
        is True
    )
    assert future["no_write_ledger_retention_proof_closeout_ready"] is True
    assert future["storage_boundary_no_write_ledger_proof_closeout_ready"] is True
    assert future["no_write_ledger_retention_proof_ready"] is True
    assert future["retention_boundary_no_write_archive_proof_bound"] is True
    assert future["retention_archive_write_locked"] is True
    assert future["retention_archive_write_allowed"] is False
    assert future["retention_archive_written"] is False
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert archive_closeout["no_write_ledger_retention_proof_closeout_field_count"] == 12
    assert archive_closeout["no_write_ledger_retention_proof_closeout_acceptance_gate_count"] == 10
    assert archive_closeout["no_write_ledger_retention_proof_closeout_only"] is True
    assert archive_closeout["retention_boundary_no_write_archive_proof_only"] is True
    assert archive_closeout["source_storage_boundary_no_write_ledger_proof_closeout_id"] == source_closeout["storage_boundary_no_write_ledger_proof_closeout_id"]
    assert archive_closeout["source_no_write_ledger_retention_proof_id"] == retention["retention_proof_id"]
    assert archive["source_no_write_ledger_retention_proof_closeout_id"] == archive_closeout["no_write_ledger_retention_proof_closeout_id"]
    assert archive["source_no_write_ledger_retention_proof_id"] == retention["retention_proof_id"]
    assert archive["source_storage_boundary_no_write_ledger_proof_closeout_id"] == source_closeout["storage_boundary_no_write_ledger_proof_closeout_id"]
    assert archive["required_command_shape_hash"] == retention["required_command_shape_hash"]
    assert archive["archive_status"] == "retention_boundary_no_write_archive_proof_preview_ready"
    assert archive["archive_mode"] == "retention_boundary_no_write_archive_proof_preview_only"
    assert archive["retention_archive_write_locked"] is True
    assert archive["retention_archive_write_allowed"] is False
    assert archive["retention_archive_written"] is False
    assert archive["archive_receipt_present"] is False
    assert archive["archive_receipt_required"] is False
    assert archive["ledger_retention_write_allowed"] is False
    assert archive["ledger_retention_written"] is False
    assert archive["ledger_write_allowed"] is False
    assert archive["ledger_written"] is False
    assert archive["receipt_persistence_storage_write_allowed"] is False
    assert archive["receipt_persistence_storage_written"] is False
    assert archive["verifier_receipt_persistence_allowed"] is False
    assert archive["verifier_receipt_persisted"] is False
    assert archive["persists_verifier_receipt"] is False
    assert archive["verifier_invoked"] is False
    assert archive["dry_run_executor_invoked"] is False
    assert archive["runner_invocation_performed"] is False
    assert archive["endpoint_executed"] is False
    assert archive["sql_executed"] is False
    assert archive["database_written"] is False
    assert archive["ready_for_database_apply_now"] is False
    assert archive["ready_for_retention_boundary_archive_now"] is False
    assert archive["endpoint_execution_allowed"] is False
    assert archive["sql_execution_allowed"] is False
    assert archive["database_write_allowed"] is False
    assert archive["database_apply_authorized"] is False
    assert archive["stdout_included"] is False
    assert archive["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        ]
        is True
    )
    assert contract["retention_archive_write_allowed"] is False
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_retention_boundary_archive_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "retention_boundary_no_write_archive_proof_bound" in check_keys
    assert "retention_boundary_no_write_archive_proof_blocks_archive" in check_keys
    assert "preview_has_no_side_effects_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_waits_without_ready_handoff():
    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout(
            _payload(),
            batch_size=1,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
    ]
    handoff_closeout = closeout[
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
    ]
    handoff = handoff_closeout["archive_retention_sealed_handoff_proof"]
    contract = closeout[
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
    )
    assert closeout["result"] == (
        "WAITING_FOR_DB_APPLY_CONTROLLED_DRY_RUN_NO_WRITE_LEDGER_RETENTION_PROOF_CLOSEOUT"
    )
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_count"] == 1
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_field_count"] == 12
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_acceptance_gate_count"] == 10
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_count"] == 0
    assert closeout["summary"]["archive_retention_sealed_handoff_proof_count"] == 1
    assert closeout["summary"]["archive_retention_sealed_handoff_proof_field_count"] == 12
    assert closeout["summary"]["sealed_handoff_write_locked_count"] == 1
    assert closeout["summary"]["sealed_handoff_write_allowed_count"] == 0
    assert closeout["summary"]["sealed_handoff_written_count"] == 0
    assert closeout["summary"]["retention_archive_write_allowed_count"] == 0
    assert closeout["summary"]["retention_archive_written_count"] == 0
    assert closeout["summary"]["ledger_retention_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_retention_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert future["archive_retention_sealed_handoff_proof_id"].endswith(
        "-archive-retention-sealed-handoff-proof"
    )
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        ]
        is False
    )
    assert future["sealed_handoff_write_locked"] is True
    assert future["sealed_handoff_write_allowed"] is False
    assert future["sealed_handoff_written"] is False
    assert future["retention_archive_write_allowed"] is False
    assert future["retention_archive_written"] is False
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert handoff_closeout["retention_boundary_no_write_archive_proof_closeout_only"] is True
    assert handoff_closeout["archive_retention_sealed_handoff_proof_only"] is True
    assert handoff_closeout["archive_retention_sealed_handoff_proof_count"] == 1
    assert handoff_closeout["archive_retention_sealed_handoff_proof_field_count"] == 12
    assert handoff_closeout["sealed_handoff_write_locked"] is True
    assert handoff_closeout["sealed_handoff_write_allowed"] is False
    assert handoff_closeout["sealed_handoff_written"] is False
    assert handoff_closeout["retention_archive_write_allowed"] is False
    assert handoff_closeout["retention_archive_written"] is False
    assert handoff_closeout["ledger_retention_write_allowed"] is False
    assert handoff_closeout["ledger_retention_written"] is False
    assert handoff_closeout["persists_verifier_receipt"] is False
    assert handoff_closeout["endpoint_executed"] is False
    assert handoff_closeout["sql_executed"] is False
    assert handoff_closeout["database_written"] is False
    assert handoff["handoff_status"] == "archive_retention_sealed_handoff_proof_preview_ready"
    assert handoff["handoff_mode"] == "archive_retention_sealed_handoff_proof_preview_only"
    assert len(handoff["sealed_handoff_manifest_hash"]) == 64
    assert handoff["sealed_handoff_write_locked"] is True
    assert handoff["sealed_handoff_write_allowed"] is False
    assert handoff["sealed_handoff_written"] is False
    assert handoff["retention_archive_write_allowed"] is False
    assert handoff["retention_archive_written"] is False
    assert handoff["ledger_retention_write_allowed"] is False
    assert handoff["ledger_retention_written"] is False
    assert handoff["ledger_write_allowed"] is False
    assert handoff["ledger_written"] is False
    assert handoff["persists_verifier_receipt"] is False
    assert handoff["endpoint_executed"] is False
    assert handoff["sql_executed"] is False
    assert handoff["database_written"] is False
    assert handoff["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        ]
        is False
    )
    assert contract["sealed_handoff_write_allowed"] is False
    assert contract["retention_archive_write_allowed"] is False
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "no_write_ledger_retention_proof_closeout_ready" in check_keys
    assert "retention_boundary_no_write_archive_proof_ready" in check_keys
    assert "archive_retention_sealed_handoff_proof_bound" in check_keys
    assert "archive_retention_sealed_handoff_proof_blocks_handoff_write" in check_keys
    assert "sealed_handoff_has_nonsecret_machine_readable_manifest" in check_keys
    assert "preview_has_no_side_effects_no_handoff_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_ready_after_fake_fetch_but_sealed_handoff_write_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-sealed-handoff.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
    ]
    handoff_closeout = closeout[
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
    ]
    source_closeout = handoff_closeout[
        "no_write_ledger_retention_proof_closeout"
    ]
    archive = handoff_closeout["retention_boundary_no_write_archive_proof"]
    handoff = handoff_closeout["archive_retention_sealed_handoff_proof"]
    contract = closeout[
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_checks"
        ]
    ]
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_RETENTION_BOUNDARY_NO_WRITE_ARCHIVE_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["archive_retention_sealed_handoff_proof_count"] == 1
    assert closeout["summary"]["archive_retention_sealed_handoff_proof_field_count"] == 12
    assert closeout["summary"]["sealed_handoff_write_locked_count"] == 1
    assert closeout["summary"]["sealed_handoff_write_allowed_count"] == 0
    assert closeout["summary"]["sealed_handoff_written_count"] == 0
    assert closeout["summary"]["retention_archive_write_allowed_count"] == 0
    assert closeout["summary"]["retention_archive_written_count"] == 0
    assert closeout["summary"]["ledger_retention_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_retention_written_count"] == 0
    assert closeout["summary"]["ledger_write_allowed_count"] == 0
    assert closeout["summary"]["ledger_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
        ]
        is True
    )
    assert future["retention_boundary_no_write_archive_proof_closeout_ready"] is True
    assert future["no_write_ledger_retention_proof_closeout_ready"] is True
    assert future["retention_boundary_no_write_archive_proof_ready"] is True
    assert future["archive_retention_sealed_handoff_proof_bound"] is True
    assert future["sealed_handoff_write_locked"] is True
    assert future["sealed_handoff_write_allowed"] is False
    assert future["sealed_handoff_written"] is False
    assert future["retention_archive_write_allowed"] is False
    assert future["retention_archive_written"] is False
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert handoff_closeout["retention_boundary_no_write_archive_proof_closeout_field_count"] == 12
    assert handoff_closeout["retention_boundary_no_write_archive_proof_closeout_acceptance_gate_count"] == 10
    assert handoff_closeout["retention_boundary_no_write_archive_proof_closeout_only"] is True
    assert handoff_closeout["archive_retention_sealed_handoff_proof_only"] is True
    assert handoff_closeout["source_no_write_ledger_retention_proof_closeout_id"] == source_closeout["no_write_ledger_retention_proof_closeout_id"]
    assert handoff_closeout["source_retention_boundary_no_write_archive_proof_id"] == archive["archive_proof_id"]
    assert handoff["source_no_write_ledger_retention_proof_closeout_id"] == source_closeout["no_write_ledger_retention_proof_closeout_id"]
    assert handoff["source_retention_boundary_no_write_archive_proof_id"] == archive["archive_proof_id"]
    assert handoff["sealed_handoff_manifest"]["source_retention_boundary_no_write_archive_proof_id"] == archive["archive_proof_id"]
    assert len(handoff["sealed_handoff_manifest_hash"]) == 64
    assert handoff["handoff_status"] == "archive_retention_sealed_handoff_proof_preview_ready"
    assert handoff["handoff_mode"] == "archive_retention_sealed_handoff_proof_preview_only"
    assert handoff["sealed_handoff_write_locked"] is True
    assert handoff["sealed_handoff_write_allowed"] is False
    assert handoff["sealed_handoff_written"] is False
    assert handoff["retention_archive_write_allowed"] is False
    assert handoff["retention_archive_written"] is False
    assert handoff["ledger_retention_write_allowed"] is False
    assert handoff["ledger_retention_written"] is False
    assert handoff["ledger_write_allowed"] is False
    assert handoff["ledger_written"] is False
    assert handoff["persists_verifier_receipt"] is False
    assert handoff["verifier_invoked"] is False
    assert handoff["dry_run_executor_invoked"] is False
    assert handoff["runner_invocation_performed"] is False
    assert handoff["endpoint_executed"] is False
    assert handoff["sql_executed"] is False
    assert handoff["database_written"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["ready_for_archive_retention_sealed_handoff_write_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["stdout_included"] is False
    assert handoff["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        ]
        is True
    )
    assert contract["sealed_handoff_write_allowed"] is False
    assert contract["retention_archive_write_allowed"] is False
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_archive_retention_sealed_handoff_write_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "archive_retention_sealed_handoff_proof_bound" in check_keys
    assert "archive_retention_sealed_handoff_proof_blocks_handoff_write" in check_keys
    assert "sealed_handoff_has_nonsecret_machine_readable_manifest" in check_keys
    assert "preview_has_no_side_effects_no_handoff_no_archive_no_retention_no_ledger_no_storage_no_persistence_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_ready_after_fake_fetch_but_verifier_transfer_is_locked():
    class FakeResponse:
        status_code = 200
        encoding = "utf-8"
        content = b"""
        <html><head>
          <script type="application/ld+json">
            {
              "@context": "https://schema.org",
              "@type": "Product",
              "image": "https://cdn.example.test/db-apply-controlled-dry-run-verifier-transfer.jpg",
              "offers": {
                "@type": "Offer",
                "availability": "https://schema.org/InStock"
              }
            }
          </script>
        </head></html>
        """

    def fake_get(url, timeout, headers):
        return FakeResponse()

    closeout = (
        build_pchome_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout(
            _payload(),
            batch_size=1,
            execute_fetch=True,
            http_get=fake_get,
        )
    )

    future = closeout[
        "future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof"
    ]
    transfer_closeout = closeout[
        "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
    ]
    source_closeout = transfer_closeout[
        "retention_boundary_no_write_archive_proof_closeout"
    ]
    handoff = transfer_closeout["archive_retention_sealed_handoff_proof"]
    transfer = transfer_closeout["sealed_handoff_verifier_transfer_proof"]
    contract = closeout[
        "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_contract"
    ]
    check_keys = [
        check["key"]
        for check in closeout[
            "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_checks"
        ]
    ]
    assert closeout["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
    )
    assert closeout["result"] == (
        "DB_APPLY_CONTROLLED_DRY_RUN_ARCHIVE_RETENTION_SEALED_HANDOFF_PROOF_CLOSEOUT_READY"
    )
    assert closeout["summary"]["controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check_count"] == 12
    assert closeout["summary"]["controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_pass_count"] == 12
    assert closeout["summary"]["controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_waiting_count"] == 0
    assert closeout["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_ready_count"] == 1
    assert closeout["summary"]["sealed_handoff_verifier_transfer_proof_count"] == 1
    assert closeout["summary"]["sealed_handoff_verifier_transfer_proof_field_count"] == 12
    assert closeout["summary"]["sealed_handoff_manifest_hash_locked_count"] == 1
    assert closeout["summary"]["verifier_transfer_write_locked_count"] == 1
    assert closeout["summary"]["verifier_transfer_write_allowed_count"] == 0
    assert closeout["summary"]["verifier_transfer_written_count"] == 0
    assert closeout["summary"]["persists_verifier_receipt_count"] == 0
    assert closeout["summary"]["verifier_invoked_count"] == 0
    assert closeout["summary"]["executes_endpoint_count"] == 0
    assert closeout["summary"]["executes_sql_count"] == 0
    assert closeout["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof"
        ]
        is True
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof_closeout"
        ]
        is True
    )
    assert future["archive_retention_sealed_handoff_proof_closeout_ready"] is True
    assert future["retention_boundary_no_write_archive_proof_closeout_ready"] is True
    assert future["sealed_handoff_manifest_hash_locked"] is True
    assert future["sealed_handoff_verifier_transfer_proof_bound"] is True
    assert future["verifier_transfer_write_locked"] is True
    assert future["verifier_transfer_write_allowed"] is False
    assert future["verifier_transfer_written"] is False
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert transfer_closeout["archive_retention_sealed_handoff_proof_closeout_field_count"] == 12
    assert transfer_closeout["archive_retention_sealed_handoff_proof_closeout_acceptance_gate_count"] == 10
    assert transfer_closeout["archive_retention_sealed_handoff_proof_closeout_only"] is True
    assert transfer_closeout["sealed_handoff_verifier_transfer_proof_only"] is True
    assert transfer_closeout["source_retention_boundary_no_write_archive_proof_closeout_id"] == source_closeout["retention_boundary_no_write_archive_proof_closeout_id"]
    assert transfer_closeout["source_archive_retention_sealed_handoff_proof_id"] == handoff["archive_retention_sealed_handoff_proof_id"]
    assert transfer["source_retention_boundary_no_write_archive_proof_closeout_id"] == source_closeout["retention_boundary_no_write_archive_proof_closeout_id"]
    assert transfer["source_archive_retention_sealed_handoff_proof_id"] == handoff["archive_retention_sealed_handoff_proof_id"]
    assert len(transfer["sealed_handoff_manifest_hash"]) == 64
    assert len(transfer["verifier_transfer_manifest_hash"]) == 64
    assert transfer["verifier_transfer_status"] == "sealed_handoff_verifier_transfer_proof_preview_ready"
    assert transfer["verifier_transfer_mode"] == "sealed_handoff_verifier_transfer_proof_preview_only"
    assert transfer["verifier_transfer_write_locked"] is True
    assert transfer["verifier_transfer_write_allowed"] is False
    assert transfer["verifier_transfer_written"] is False
    assert transfer["sealed_handoff_write_allowed"] is False
    assert transfer["sealed_handoff_written"] is False
    assert transfer["verifier_invocation_allowed"] is False
    assert transfer["verifier_invoked"] is False
    assert transfer["persists_verifier_receipt"] is False
    assert transfer["endpoint_executed"] is False
    assert transfer["sql_executed"] is False
    assert transfer["database_written"] is False
    assert transfer["ready_for_database_apply_now"] is False
    assert transfer["ready_for_verifier_transfer_write_now"] is False
    assert transfer["ready_for_verifier_invocation_now"] is False
    assert transfer["database_apply_authorized"] is False
    assert transfer["stdout_included"] is False
    assert transfer["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof"
        ]
        is True
    )
    assert contract["verifier_transfer_write_allowed"] is False
    assert contract["verifier_invocation_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert "archive_retention_sealed_handoff_proof_ready" in check_keys
    assert "sealed_handoff_manifest_hash_locked" in check_keys
    assert "sealed_handoff_verifier_transfer_proof_bound" in check_keys
    assert "sealed_handoff_verifier_transfer_blocks_verifier_invocation" in check_keys
    assert "sealed_handoff_verifier_transfer_has_nonsecret_machine_readable_manifest" in check_keys
    assert "preview_has_no_side_effects_no_handoff_no_verifier_no_receipt_no_execution_no_signing" in check_keys
    assert closeout["safety"]["persists_verifier_receipt"] is False
    assert closeout["safety"]["executes_endpoint"] is False
    assert closeout["safety"]["executes_sql"] is False
    assert closeout["safety"]["writes_database"] is False
    assert closeout["safety"]["executes_database_apply"] is False


def test_build_report_keeps_production_report_policy(monkeypatch):
    monkeypatch.setattr(report, "fetch_json", lambda url, timeout: _payload())
    monkeypatch.setattr(
        report.version_guard,
        "build_report",
        lambda health_url, timeout: {
            "production": {"status": "healthy", "version": "V10.725"},
            "local": {"config_version": "V10.725", "head_config_version": "V10.725"},
            "origin_main": {"matches_local_head": True},
        },
    )
    monkeypatch.setattr(report.version_guard, "evaluate", lambda guard_report, allow_local_version_drift: (True, []))

    payload = report.build_report(
        api_url="https://example.test/path",
        limit=20,
        timeout=1,
        health_url="https://example.test/health",
        skip_version_truth=False,
    )

    assert payload["policy"] == "read_only_production_pchome_mapping_backlog"
    assert payload["result"] == "NEEDS_MAPPING"


def test_main_json_uses_build_report(monkeypatch, capsys):
    monkeypatch.setattr(
        report,
        "build_report",
        lambda **kwargs: {
            "policy": "read_only_production_pchome_mapping_backlog",
            "result": "PASS",
            "api_url": "https://example.test/path?limit=20",
            "stats": {"mapping_rate": 100.0},
            "backlog": {},
            "errors": [],
        },
    )

    exit_code = report.main(["--json"])
    payload = json.loads(capsys.readouterr().out)

    assert exit_code == 0
    assert payload["policy"] == "read_only_production_pchome_mapping_backlog"
    assert payload["stats"]["mapping_rate"] == 100.0


def test_blocked_report_exits_nonzero(monkeypatch, capsys):
    monkeypatch.setattr(
        report,
        "build_report",
        lambda **kwargs: {
            "policy": "read_only_production_pchome_mapping_backlog",
            "result": "BLOCKED",
            "api_url": "https://example.test/path?limit=20",
            "errors": ["version drift"],
        },
    )

    exit_code = report.main([])

    assert exit_code == 1
    assert "version drift" in capsys.readouterr().out


def test_mapping_backlog_route_uses_cached_growth_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached mapping backlog should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog?limit=20"):
        response = routes.api_pchome_growth_mapping_backlog.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_mapping_backlog"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/opportunities"
    assert payload["backlog"]["direct_mapping_count"] == 2
    assert payload["backlog"]["review_candidate_count"] == 1


def test_operator_preview_route_uses_cached_growth_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached operator preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/operator-preview?batch_size=1"):
        response = routes.api_pchome_growth_mapping_operator_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_mapping_operator_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog"
    assert payload["operator_batch"]["selected_direct_mapping_count"] == 1
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_auto_search_package_route_defaults_to_no_search_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached direct mapping auto search package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-auto-search-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_auto_search_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_auto_search_package"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/operator-preview"
    assert payload["summary"]["selected_direct_mapping_count"] == 1
    assert payload["summary"]["search_ready_target_count"] == 1
    assert payload["summary"]["execute_search_count"] == 0
    assert payload["search_execution"]["executed"] is False
    assert payload["search_execution"]["writes_database"] is False
    assert payload["search_package"]["targets"][0]["pchome_product_id"] == "PCH-2"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_candidate_decision_package_route_defaults_to_no_search_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached direct mapping candidate decision package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-candidate-decision-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_candidate_decision_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_candidate_decision_package"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/direct-mapping-auto-search-package"
    assert payload["result"] == "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"
    assert payload["summary"]["selected_direct_mapping_count"] == 1
    assert payload["summary"]["candidate_decision_count"] == 0
    assert payload["decision_package"]["manual_review_mode"] == "exception_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_candidate_exception_auto_resolution_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached exception auto-resolution package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-candidate-exception-auto-resolution-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_candidate_exception_auto_resolution_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_candidate_exception_auto_resolution"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-candidate-decision-package"
    )
    assert payload["result"] == "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"
    assert payload["summary"]["exception_auto_resolution_artifact_count"] == 0
    assert payload["auto_resolution_package"]["resolution_mode"] == "ai_controlled_read_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_candidate_exception_resolution_closeout_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached exception resolution closeout package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-candidate-exception-resolution-closeout-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_candidate_exception_resolution_closeout_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_candidate_exception_resolution_closeout"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-candidate-exception-auto-resolution-package"
    )
    assert payload["result"] == "WAITING_FOR_DIRECT_MAPPING_CANDIDATES"
    assert payload["summary"]["exception_resolution_closeout_receipt_count"] == 0
    assert payload["closeout_package"]["resolution_mode"] == "ai_controlled_read_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_retry_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_decision_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry candidate decision package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-decision-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_decision_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_decision_package"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-candidate-exception-resolution-closeout-package"
    )
    assert payload["result"] == "WAITING_FOR_EXCEPTION_RESOLUTION_CLOSEOUT"
    assert payload["summary"]["retry_candidate_decision_count"] == 0
    assert payload["retry_candidate_decision_package"]["manual_review_mode"] == "exception_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_retry_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_auto_resolution_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry candidate exception auto-resolution package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-auto-resolution-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-decision-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_CANDIDATE_DECISIONS"
    assert payload["summary"]["retry_exception_auto_resolution_artifact_count"] == 0
    assert payload["retry_exception_auto_resolution_package"]["resolution_mode"] == "ai_controlled_read_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_retry_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_resolution_closeout_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry candidate exception resolution closeout package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-resolution-closeout-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-auto-resolution-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_CANDIDATE_EXCEPTIONS"
    assert payload["summary"]["retry_exception_resolution_closeout_receipt_count"] == 0
    assert payload["retry_exception_resolution_closeout_package"]["resolution_mode"] == "ai_controlled_read_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_retry_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_closeout_verifier_input_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry exception closeout verifier input package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-input-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_input_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_input"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-resolution-closeout-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_RECEIPTS"
    assert payload["summary"]["closeout_no_write_verifier_input_count"] == 0
    assert payload["retry_exception_closeout_verifier_input_package"]["verifier_mode"] == "machine_verifiable_no_write"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_retry_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry exception closeout verifier artifact preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-artifact-preview-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preview"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-input-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_INPUTS"
    assert payload["summary"]["artifact_schema_count"] == 3
    assert payload["retry_exception_closeout_verifier_artifact_preview"]["ready_to_write_artifacts_now"] is False
    assert payload["safety"]["writes_artifact_in_preview"] is False
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_retry_search"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry exception closeout verifier artifact materialization should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-artifact-materialization-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_materialization"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-artifact-preview-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_EXCEPTION_CLOSEOUT_VERIFIER_ARTIFACT_PREVIEW"
    assert payload["summary"]["artifact_payload_count"] == 3
    assert payload["summary"]["artifact_materialized_count"] == 0
    assert payload["artifact_materialization_package"]["materialize_artifacts"] is False
    assert payload["safety"]["writes_artifact_count"] == 0
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["materialize_artifacts"] is False


def test_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry exception artifact preflight verifier should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-artifact-preflight-verifier-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_closeout_verifier_artifact_preflight_verifier"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-artifact-materialization-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_EXCEPTION_VERIFIER_ARTIFACT_MATERIALIZATION"
    assert payload["summary"]["artifact_payload_count"] == 3
    assert payload["summary"]["artifact_readback_count"] == 3
    assert payload["summary"]["artifact_preflight_verifier_ready_count"] == 0
    assert payload["artifact_preflight_verifier"]["ready_for_controlled_apply_preflight"] is False
    assert payload["controlled_apply_preflight_contract"]["allows_database_write_now"] is False
    assert payload["safety"]["materialize_artifacts"] is False
    assert payload["safety"]["reads_artifact_files"] is True
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_controlled_apply_preflight_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry exception controlled apply preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-controlled-apply-preflight-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_preflight_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_preflight"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-closeout-verifier-artifact-preflight-verifier-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_EXCEPTION_ARTIFACT_PREFLIGHT_VERIFIER"
    assert payload["summary"]["controlled_apply_preflight_ready_count"] == 0
    assert payload["summary"]["target_selector_count"] == 0
    assert payload["summary"]["executes_database_write_count"] == 0
    assert payload["controlled_apply_preflight"]["ready_for_controlled_apply_executor"] is False
    assert payload["controlled_apply_preflight"]["ready_for_database_apply_now"] is False
    assert payload["executor_guard"]["allows_database_write_now"] is False
    assert payload["safety"]["executes_database_write_in_preflight"] is False
    assert payload["safety"]["writes_database"] is False


def test_direct_mapping_retry_candidate_exception_controlled_apply_executor_route_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached retry exception controlled apply executor should not open a DB engine without execute_apply")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-controlled-apply-executor-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_executor_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "ai_controlled_pchome_growth_direct_mapping_retry_candidate_exception_controlled_apply_executor"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-controlled-apply-preflight-package"
    )
    assert payload["result"] == "WAITING_FOR_RETRY_EXCEPTION_CONTROLLED_APPLY_PREFLIGHT"
    assert payload["summary"]["execute_apply_requested_count"] == 0
    assert payload["summary"]["applied_record_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["controlled_apply_executor"]["execute_apply"] is False
    assert payload["controlled_apply_executor"]["write_attempted"] is False
    assert payload["safety"]["execute_apply"] is False
    assert payload["safety"]["writes_database"] is False


def test_ai_automation_readiness_route_defaults_to_no_search_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached AI automation readiness should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/ai-automation-readiness?batch_size=1&include_receipt_replay=false&include_drift_verifier=false"
    ):
        response = routes.api_pchome_growth_ai_automation_readiness.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_ai_automation_readiness"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/opportunities"
    assert payload["summary"]["primary_human_gate_count"] == 0
    assert payload["automation_policy"]["primary_flow"] == "ai_controlled"
    assert payload["ai_exception_auto_resolution"]["mode"] == "machine_verifiable_auto_resolution"
    assert payload["summary"]["manual_required_as_primary_flow_count"] == 0
    assert payload["manual_policy"]["manual_review_mode"] == "exception_only"
    assert payload["safety"]["executes_search"] is False
    assert payload["safety"]["executes_fetch"] is False
    assert payload["safety"]["writes_database"] is False


def test_evidence_enrichment_route_uses_cached_growth_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached evidence enrichment preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/evidence-enrichment-preview?batch_size=1"):
        response = routes.api_pchome_growth_evidence_enrichment_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_evidence_enrichment_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/operator-preview"
    assert payload["summary"]["missing_field_counts"]["image"] == 2
    assert payload["safety"]["fetches_external_sites"] is False


def test_evidence_source_preview_route_uses_cached_growth_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached evidence source preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/evidence-source-preview?batch_size=1"):
        response = routes.api_pchome_growth_evidence_source_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_evidence_source_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/evidence-enrichment-preview"
    assert payload["summary"]["field_counts"]["image"]["missing_count"] == 2
    assert payload["safety"]["fetches_external_sites"] is False


def test_evidence_fetch_gate_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached evidence fetch gate should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/evidence-fetch-gate?batch_size=1"):
        response = routes.api_pchome_growth_evidence_fetch_gate.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "controlled_read_only_pchome_product_page_evidence_fetch_gate"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/evidence-source-preview"
    assert payload["fetch_config"]["execute_fetch"] is False
    assert payload["summary"]["executed_fetch_count"] == 0
    assert payload["safety"]["writes_database"] is False


def test_evidence_merge_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached evidence merge preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/evidence-merge-preview?batch_size=1"):
        response = routes.api_pchome_growth_evidence_merge_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_evidence_merge_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/evidence-fetch-gate"
    assert payload["summary"]["executed_fetch_count"] == 0
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_receipt_gate_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy receipt gate should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/auto-policy-receipt-gate?batch_size=1"):
        response = routes.api_pchome_growth_auto_policy_receipt_gate.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_receipt_gate"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/evidence-merge-preview"
    assert payload["summary"]["persists_receipt_count"] == 0
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["persists_receipt"] is False


def test_auto_policy_persistence_gate_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy persistence gate should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context("/api/ai/pchome-growth/mapping-backlog/auto-policy-persistence-gate?batch_size=1"):
        response = routes.api_pchome_growth_auto_policy_persistence_gate.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_persistence_gate"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-receipt-gate"
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["summary"]["persists_receipt_count"] == 0
    assert payload["apply_gate"]["mode"] == "dry_run_only"
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["persists_receipt"] is False


def test_auto_policy_schema_migration_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy schema migration preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-schema-migration-preview?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_schema_migration_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_schema_migration_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-persistence-gate"
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["future_apply_gate"]["current_preview_apply_allowed"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_migration_file_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy migration file preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-file-preview?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_migration_file_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_migration_file_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-schema-migration-preview"
    assert payload["summary"]["writes_file_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["migration_file_preview"]["writes_file"] is False
    assert payload["future_apply_endpoint_verifier"]["executes_endpoint"] is False
    assert payload["safety"]["writes_file"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_apply_readiness_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy apply readiness closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-apply-readiness-closeout?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_apply_readiness_closeout.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_apply_readiness_closeout"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-file-preview"
    assert payload["summary"]["readiness_check_count"] == 9
    assert payload["closeout"]["ready_for_database_apply"] is False
    assert payload["summary"]["writes_file_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["writes_file"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_migration_file_generation_request_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy migration file generation request should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-file-generation-request?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_migration_file_generation_request.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_migration_file_generation_request"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-apply-readiness-closeout"
    assert payload["summary"]["required_artifact_count"] == 4
    assert payload["file_generation_request"]["ready_for_database_apply"] is False
    assert payload["summary"]["writes_file_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["writes_file"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_migration_apply_gate_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy migration apply gate preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-apply-gate-preview?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_migration_apply_gate_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_migration_apply_gate_preview"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-file-generation-request"
    )
    assert payload["summary"]["generated_file_exists_count"] == 1
    assert payload["summary"]["generated_file_hash_matches_count"] == 1
    assert payload["apply_gate"]["ready_for_database_apply_now"] is False
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_request_gate_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply request gate preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-request-gate-preview?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_request_gate_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_request_gate_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-migration-apply-gate-preview"
    assert payload["summary"]["required_artifact_count"] == 5
    assert payload["db_apply_request_gate"]["ready_for_database_apply_now"] is False
    assert payload["db_apply_request_gate"]["command_preview"]["reads_secret_in_preview"] is False
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_execution_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply execution preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-execution-preflight?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_execution_preflight.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_execution_preflight"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-request-gate-preview"
    assert payload["summary"]["required_artifact_count"] == 6
    assert payload["summary"]["snapshot_plan_count"] == 5
    assert payload["summary"]["readback_plan_count"] == 6
    assert payload["execution_preflight"]["ready_for_database_apply_now"] is False
    assert payload["execution_preflight"]["reads_secret_in_preview"] is False
    assert payload["prewrite_snapshot_plan"]["writes_database"] is False
    assert payload["post_apply_readback_plan"]["executes_sql_in_preview"] is False
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_package_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_package"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-execution-preflight"
    assert payload["summary"]["authorization_check_count"] == 11
    assert payload["summary"]["freshness_requirement_count"] == 5
    assert payload["summary"]["manifest_step_count"] == 6
    assert payload["authorization_package"]["ready_for_database_apply_now"] is False
    assert payload["authorization_package"]["reads_secret_in_preview"] is False
    assert payload["machine_apply_manifest"]["writes_database"] is False
    assert payload["verifier_bundle"]["executes_in_preview"] is False
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_verifier_artifact_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply verifier artifact preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_verifier_artifact_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_verifier_artifact_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-package"
    assert payload["summary"]["artifact_schema_count"] == 3
    assert payload["summary"]["artifact_generation_step_count"] == 5
    assert payload["summary"]["verifier_check_count"] == 15
    assert payload["artifact_preview"]["ready_for_database_apply_now"] is False
    assert payload["artifact_preview"]["writes_artifact_in_preview"] is False
    assert payload["artifact_generation_plan"]["writes_database"] is False
    assert payload["verifier_manifest"]["writes_artifact_in_preview"] is False
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_final_handoff_package_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply final handoff package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-final-handoff-package?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_final_handoff_package.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_final_handoff_package"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-verifier-artifact-preview"
    assert payload["summary"]["handoff_section_count"] == 6
    assert payload["summary"]["final_runbook_step_count"] == 7
    assert payload["summary"]["command_preview_count"] == 3
    assert payload["summary"]["abort_gate_count"] == 10
    assert payload["final_handoff_package"]["ready_for_database_apply_now"] is False
    assert payload["final_handoff_package"]["reads_secret_in_preview"] is False
    assert payload["final_runbook_manifest"]["writes_database"] is False
    assert payload["command_previews"][1]["executes_in_preview"] is False
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_shell_preview_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run shell preview should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-shell-preview?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_controlled_dry_run_shell_preview.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_shell_preview"
    assert payload["source_endpoint"] == "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-final-handoff-package"
    assert payload["summary"]["shell_phase_count"] == 9
    assert payload["summary"]["shell_script_line_count"] == 10
    assert payload["summary"]["check_mode_required_check_count"] == 6
    assert payload["summary"]["rollback_hook_count"] == 3
    assert payload["controlled_dry_run_shell_preview"]["ready_for_database_apply_now"] is False
    assert payload["controlled_dry_run_shell_preview"]["reads_secret_in_preview"] is False
    assert payload["shell_script_preview"]["executes_script_in_preview"] is False
    assert payload["check_mode_contract"]["writes_database"] is False
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_shell_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run shell closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-shell-closeout?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_controlled_dry_run_shell_closeout.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_shell_closeout"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-shell-preview"
    )
    assert payload["summary"]["closeout_check_count"] == 13
    assert payload["summary"]["future_apply_boundary_count"] == 6
    assert payload["explicit_authorization_boundary"]["ready_for_database_apply_now"] is False
    assert payload["explicit_authorization_boundary"]["reads_secret_in_preview"] is False
    assert payload["explicit_authorization_boundary"]["executes_shell_in_preview"] is False
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_request_intake_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization request intake should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-intake?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_request_intake.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_request_intake"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-shell-closeout"
    )
    assert payload["summary"]["required_request_evidence_count"] == 7
    assert payload["summary"]["request_payload_required_field_count"] == 10
    assert payload["summary"]["authorization_acceptance_gate_count"] == 11
    assert payload["authorization_request_intake"]["ready_for_database_apply_now"] is False
    assert payload["authorization_request_intake"]["reads_secret_in_preview"] is False
    assert payload["authorization_request_intake"]["executes_shell_in_preview"] is False
    assert payload["authorization_envelope"]["issues_database_apply_authorization"] is False
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_request_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization request closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-closeout?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_request_closeout.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_request_closeout"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-intake"
    )
    assert payload["summary"]["closeout_check_count"] == 12
    assert payload["summary"]["exact_request_payload_field_count"] == 10
    assert payload["summary"]["machine_request_manifest_step_count"] == 6
    assert payload["final_exact_request_package"]["ready_for_database_apply_now"] is False
    assert payload["final_exact_request_package"]["issues_database_apply_authorization"] is False
    assert payload["final_exact_request_package"]["reads_secret_in_preview"] is False
    assert payload["machine_request_manifest"]["writes_database"] is False
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_lane_guard_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization lane guard should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-lane-guard?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_lane_guard.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_lane_guard"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-request-closeout"
    )
    assert payload["summary"]["lane_guard_check_count"] == 12
    assert payload["summary"]["lane_entry_requirement_count"] == 6
    assert payload["summary"]["exact_request_payload_field_count"] == 10
    assert payload["summary"]["machine_request_manifest_step_count"] == 6
    assert payload["future_authorization_lane_guard"]["ready_for_database_apply_now"] is False
    assert payload["future_authorization_lane_guard"]["issues_database_apply_authorization"] is False
    assert payload["future_authorization_lane_guard"]["reads_secret_in_preview"] is False
    assert payload["lane_transfer_contract"]["writes_database"] is False
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_decision_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization decision preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-preflight?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_decision_preflight.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_preflight"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-lane-guard"
    )
    assert payload["summary"]["decision_preflight_check_count"] == 12
    assert payload["summary"]["decision_input_requirement_count"] == 8
    assert payload["summary"]["decision_rejection_reason_count"] == 10
    assert payload["future_authorization_decision_preflight"]["ready_for_database_apply_now"] is False
    assert payload["future_authorization_decision_preflight"]["issues_database_apply_authorization"] is False
    assert payload["future_authorization_decision_preflight"]["reads_secret_in_preview"] is False
    assert payload["decision_preflight_envelope"]["requires_post_apply_verifier"] is True
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_decision_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization decision closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-closeout?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_decision_closeout.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_decision_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-preflight"
    )
    assert payload["summary"]["decision_closeout_check_count"] == 12
    assert payload["summary"]["decision_input_requirement_count"] == 8
    assert payload["summary"]["decision_rejection_reason_count"] == 10
    assert payload["future_authorization_decision_closeout"]["ready_for_database_apply_now"] is False
    assert payload["future_authorization_decision_closeout"]["issues_database_apply_authorization"] is False
    assert payload["future_authorization_decision_package"]["requires_post_apply_verifier"] is True
    assert payload["future_authorization_decision_package"]["reads_secret_in_preview"] is False
    assert payload["future_authorization_decision_package"]["writes_database_in_preview"] is False
    assert payload["decision_closeout_contract"]["issues_database_apply_authorization"] is False
    assert payload["decision_closeout_contract"]["ready_for_database_apply_now"] is False
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_issuer_gate_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization issuer gate should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-issuer-gate?batch_size=1"
    ):
        response = routes.api_pchome_growth_auto_policy_db_apply_authorization_issuer_gate.__wrapped__()

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == "read_only_pchome_growth_auto_policy_db_apply_authorization_issuer_gate"
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-decision-closeout"
    )
    assert payload["summary"]["issuer_gate_check_count"] == 12
    assert payload["summary"]["required_issuer_evidence_count"] == 9
    assert payload["summary"]["nonsecret_authorization_claim_count"] == 8
    assert payload["future_authorization_issuer_gate"]["ready_for_database_apply_now"] is False
    assert payload["future_authorization_issuer_gate"]["issues_database_apply_authorization"] is False
    assert payload["future_authorization_issuer_gate"]["signs_database_apply_authorization"] is False
    assert payload["final_nonsecret_authorization_envelope"]["secret_material_included"] is False
    assert payload["final_nonsecret_authorization_envelope"]["reads_secret_in_preview"] is False
    assert payload["final_nonsecret_authorization_envelope"]["writes_database_in_preview"] is False
    assert payload["issuer_gate_contract"]["issues_database_apply_authorization"] is False
    assert payload["issuer_gate_contract"]["ready_for_database_apply_now"] is False
    assert payload["issuer_gate_contract"]["signs_database_apply_authorization"] is False
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_decision_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signing decision preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-preflight?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signing_decision_preflight
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_decision_preflight"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-issuer-gate"
    )
    assert payload["summary"]["signing_decision_preflight_check_count"] == 12
    assert payload["summary"]["signing_decision_input_requirement_count"] == 10
    assert payload["summary"]["signing_decision_rejection_reason_count"] == 11
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signing_decision_preflight"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["future_authorization_signing_decision_preflight"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_decision_preflight"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["signing_decision_preflight_envelope"]["ready_for_database_apply_now"] is False
    assert (
        payload["signing_decision_preflight_envelope"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["signing_decision_preflight_envelope"]["secret_material_required_in_preview"] is False
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_issuer_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signing issuer closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signing_issuer_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_issuer_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-guard"
    )
    assert payload["summary"]["signing_issuer_closeout_check_count"] == 12
    assert payload["summary"]["signing_issuer_guard_check_count"] == 12
    assert payload["summary"]["signing_decision_input_requirement_count"] == 10
    assert payload["summary"]["signing_decision_rejection_reason_count"] == 11
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signing_issuer_closeout"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_issuer_closeout"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_issuer_closeout"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["final_signable_request_package"]["ready_for_database_apply_now"] is False
    assert (
        payload["final_signable_request_package"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["final_signable_request_package"]["secret_material_included"] is False
    assert (
        payload["final_signable_request_package"]["secret_material_required_in_preview"]
        is False
    )
    assert (
        payload["signing_issuer_closeout_contract"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["signing_issuer_closeout_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_execution_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signing execution preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-preflight?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signing_execution_preflight
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_execution_preflight"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-closeout"
    )
    assert payload["summary"]["signing_execution_preflight_check_count"] == 12
    assert payload["summary"]["signing_issuer_closeout_check_count"] == 12
    assert payload["summary"]["operator_held_secret_boundary_count"] == 1
    assert payload["summary"]["signing_execution_input_requirement_count"] == 10
    assert payload["summary"]["signing_execution_abort_condition_count"] == 8
    assert payload["summary"]["rollback_boundary_count"] == 4
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signing_execution_preflight"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_execution_preflight"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_execution_preflight"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["signing_execution_preflight_package"]["ready_for_database_apply_now"] is False
    assert (
        payload["signing_execution_preflight_package"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["signing_execution_preflight_package"]["secret_material_included"] is False
    assert (
        payload["signing_execution_preflight_package"]["secret_material_required_in_preview"]
        is False
    )
    assert (
        payload["operator_held_secret_boundary_contract"]["secret_reference_mode"]
        == "external_runtime_reference_only"
    )
    assert payload["operator_held_secret_boundary_contract"]["reads_secret_in_preview"] is False
    assert (
        payload["operator_held_secret_boundary_contract"]["accepts_plaintext_secret"]
        is False
    )
    assert (
        payload["signing_execution_preflight_contract"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["signing_execution_preflight_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_execution_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signing execution closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signing_execution_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_execution_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-preflight"
    )
    assert payload["summary"]["signing_execution_closeout_check_count"] == 12
    assert payload["summary"]["signing_execution_preflight_check_count"] == 12
    assert payload["summary"]["unsigned_signed_authorization_receipt_boundary_count"] == 1
    assert payload["summary"]["operator_held_secret_boundary_count"] == 1
    assert payload["summary"]["signing_execution_input_requirement_count"] == 10
    assert payload["summary"]["signing_execution_abort_condition_count"] == 8
    assert payload["summary"]["rollback_boundary_count"] == 4
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signing_execution_closeout"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_execution_closeout"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_execution_closeout"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["unsigned_signed_authorization_receipt_boundary"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["unsigned_signed_authorization_receipt_boundary"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["unsigned_signed_authorization_receipt_boundary"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["unsigned_signed_authorization_receipt_boundary"][
            "signature_material_included"
        ]
        is False
    )
    assert (
        payload["unsigned_signed_authorization_receipt_boundary"][
            "secret_material_included"
        ]
        is False
    )
    assert (
        payload["signing_execution_closeout_contract"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["signing_execution_closeout_contract"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signed receipt preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-preflight?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_preflight
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_preflight"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-execution-closeout"
    )
    assert payload["summary"]["signed_receipt_preflight_check_count"] == 12
    assert payload["summary"]["signing_execution_closeout_check_count"] == 12
    assert payload["summary"]["external_signing_receipt_evidence_boundary_count"] == 1
    assert payload["summary"]["required_external_receipt_evidence_count"] == 10
    assert payload["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert payload["summary"]["operator_held_secret_boundary_count"] == 1
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signed_receipt_preflight"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_authorization_signed_receipt_preflight"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signed_receipt_preflight"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signed_receipt_preflight"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["external_signing_receipt_evidence_boundary"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["external_signing_receipt_evidence_boundary"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["external_signing_receipt_evidence_boundary"]["signature_material_included"]
        is False
    )
    assert (
        payload["external_signing_receipt_evidence_boundary"]["secret_material_included"]
        is False
    )
    assert (
        payload["external_signing_receipt_evidence_boundary"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["signed_receipt_preflight_contract"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["signed_receipt_preflight_contract"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signed receipt closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-preflight"
    )
    assert payload["summary"]["signed_receipt_closeout_check_count"] == 12
    assert payload["summary"]["signed_receipt_preflight_check_count"] == 12
    assert payload["summary"]["detached_receipt_verification_boundary_count"] == 1
    assert payload["summary"]["required_external_receipt_evidence_count"] == 10
    assert payload["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert payload["summary"]["detached_receipt_verification_check_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signed_receipt_closeout"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_authorization_signed_receipt_closeout"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signed_receipt_closeout"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signed_receipt_closeout"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["detached_receipt_verification_boundary"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["detached_receipt_verification_boundary"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["detached_receipt_verification_boundary"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["detached_receipt_verification_boundary"]["signature_material_included"]
        is False
    )
    assert payload["detached_receipt_verification_boundary"]["secret_material_included"] is False
    assert payload["detached_receipt_verification_boundary"]["ready_for_database_apply_now"] is False
    assert payload["signed_receipt_closeout_contract"]["ready_for_database_apply_now"] is False
    assert (
        payload["signed_receipt_closeout_contract"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signed_receipt_evidence_intake_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signed receipt evidence intake should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-evidence-intake?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_evidence_intake
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signed_receipt_evidence_intake"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-closeout"
    )
    assert payload["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert payload["summary"]["signed_receipt_closeout_check_count"] == 12
    assert payload["summary"]["detached_receipt_verification_boundary_count"] == 1
    assert payload["summary"]["detached_verification_evidence_schema_count"] == 1
    assert payload["summary"]["required_external_receipt_evidence_count"] == 10
    assert payload["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert payload["summary"]["detached_receipt_verification_check_count"] == 10
    assert payload["summary"]["detached_verification_evidence_field_count"] == 12
    assert payload["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_signed_authorization_receipt_evidence_intake"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_signed_authorization_receipt_evidence_intake"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_signed_authorization_receipt_evidence_intake"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_signed_authorization_receipt_evidence_intake"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["future_signed_authorization_receipt_evidence_intake"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["detached_verification_evidence_schema"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["detached_verification_evidence_schema"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["detached_verification_evidence_schema"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["detached_verification_evidence_schema"]["signature_material_included"]
        is False
    )
    assert payload["detached_verification_evidence_schema"]["secret_material_included"] is False
    assert payload["detached_verification_evidence_schema"]["accepts_plaintext_secret"] is False
    assert payload["detached_verification_evidence_schema"]["ready_for_database_apply_now"] is False
    assert payload["signed_receipt_evidence_intake_contract"]["ready_for_database_apply_now"] is False
    assert (
        payload["signed_receipt_evidence_intake_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["performs_detached_signature_verification"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_detached_verification_evidence_validation_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization detached verification evidence validation should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-detached-verification-evidence-validation?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_detached_verification_evidence_validation
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_detached_verification_evidence_validation"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signed-receipt-evidence-intake"
    )
    assert payload["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert payload["summary"]["signed_receipt_evidence_intake_check_count"] == 12
    assert payload["summary"]["detached_verification_evidence_schema_count"] == 1
    assert payload["summary"]["verifier_receipt_closeout_boundary_count"] == 1
    assert payload["summary"]["required_external_receipt_evidence_count"] == 10
    assert payload["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert payload["summary"]["detached_receipt_verification_check_count"] == 10
    assert payload["summary"]["detached_verification_evidence_field_count"] == 12
    assert payload["summary"]["detached_verification_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_field_count"] == 12
    assert payload["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_detached_verification_evidence_validation"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_detached_verification_evidence_validation"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_detached_verification_evidence_validation"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_detached_verification_evidence_validation"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["future_detached_verification_evidence_validation"][
            "verifier_receipt_persisted"
        ]
        is False
    )
    assert (
        payload["future_detached_verification_evidence_validation"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["verifier_receipt_closeout_boundary"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["verifier_receipt_closeout_boundary"]["verifier_receipt_persisted"]
        is False
    )
    assert (
        payload["verifier_receipt_closeout_boundary"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["verifier_receipt_closeout_boundary"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["verifier_receipt_closeout_boundary"]["signature_material_included"]
        is False
    )
    assert payload["verifier_receipt_closeout_boundary"]["secret_material_included"] is False
    assert payload["verifier_receipt_closeout_boundary"]["accepts_plaintext_secret"] is False
    assert payload["verifier_receipt_closeout_boundary"]["ready_for_database_apply_now"] is False
    assert (
        payload["detached_verification_evidence_validation_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["detached_verification_evidence_validation_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["performs_detached_signature_verification"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_verifier_receipt_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization verifier receipt closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-verifier-receipt-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_verifier_receipt_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_verifier_receipt_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-detached-verification-evidence-validation"
    )
    assert payload["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert payload["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert payload["summary"]["verifier_receipt_closeout_boundary_count"] == 1
    assert payload["summary"]["verifier_receipt_evidence_handoff_count"] == 1
    assert payload["summary"]["required_external_receipt_evidence_count"] == 10
    assert payload["summary"]["external_receipt_acceptance_gate_count"] == 8
    assert payload["summary"]["verifier_receipt_field_count"] == 12
    assert payload["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert payload["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_verifier_receipt_closeout"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["future_verifier_receipt_closeout"]["issues_database_apply_authorization"]
        is False
    )
    assert (
        payload["future_verifier_receipt_closeout"]["signs_database_apply_authorization"]
        is False
    )
    assert (
        payload["future_verifier_receipt_closeout"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert payload["future_verifier_receipt_closeout"]["verifier_receipt_persisted"] is False
    assert (
        payload["future_verifier_receipt_closeout"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["verifier_receipt_evidence_handoff"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert payload["verifier_receipt_evidence_handoff"]["verifier_receipt_persisted"] is False
    assert (
        payload["verifier_receipt_evidence_handoff"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["verifier_receipt_evidence_handoff"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert payload["verifier_receipt_evidence_handoff"]["signature_material_included"] is False
    assert payload["verifier_receipt_evidence_handoff"]["secret_material_included"] is False
    assert payload["verifier_receipt_evidence_handoff"]["accepts_plaintext_secret"] is False
    assert payload["verifier_receipt_evidence_handoff"]["ready_for_database_apply_now"] is False
    assert payload["verifier_receipt_closeout_contract"]["ready_for_database_apply_now"] is False
    assert (
        payload["verifier_receipt_closeout_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["performs_detached_signature_verification"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_evidence_execution_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization evidence execution preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-evidence-execution-preflight?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_evidence_execution_preflight
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_evidence_execution_preflight"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-verifier-receipt-closeout"
    )
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert payload["summary"]["detached_verification_evidence_validation_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_count"] == 1
    assert payload["summary"]["authorization_evidence_execution_field_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_field_count"] == 12
    assert payload["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert payload["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "verifier_receipt_persisted"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_verifier_handoff"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "verifier_receipt_persisted"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "signature_material_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"]["secret_material_included"]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"]["accepts_plaintext_secret"]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight_contract"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_preflight_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["performs_detached_signature_verification"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_authorization_evidence"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_evidence_execution_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization evidence execution closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-evidence-execution-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_evidence_execution_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_evidence_execution_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-evidence-execution-preflight"
    )
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["verifier_receipt_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_count"] == 1
    assert payload["summary"]["database_apply_final_verifier_gate_count"] == 1
    assert payload["summary"]["authorization_evidence_execution_closeout_field_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["authorization_evidence_execution_field_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_field_count"] == 12
    assert payload["summary"]["verifier_receipt_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_evidence_handoff_field_count"] == 12
    assert payload["summary"]["verifier_receipt_handoff_acceptance_gate_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "database_apply_authorized"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "verifier_receipt_persisted"
        ]
        is False
    )
    assert (
        payload["future_database_apply_authorization_final_verifier_gate"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout"][
            "detached_signature_verification_performed"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout"][
            "verifier_receipt_persisted"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout"][
            "external_signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout"][
            "signed_authorization_receipt_included"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout"]["signature_material_included"]
        is False
    )
    assert payload["authorization_evidence_execution_closeout"]["secret_material_included"] is False
    assert payload["authorization_evidence_execution_closeout"]["accepts_plaintext_secret"] is False
    assert payload["authorization_evidence_execution_closeout"]["executes_authorization_evidence"] is False
    assert payload["authorization_evidence_execution_closeout"]["executes_database_apply"] is False
    assert payload["authorization_evidence_execution_closeout"]["ready_for_database_apply_now"] is False
    assert payload["authorization_evidence_execution_closeout"]["database_apply_authorized"] is False
    assert (
        payload["authorization_evidence_execution_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout_contract"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert (
        payload["authorization_evidence_execution_closeout_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["performs_detached_signature_verification"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_authorization_evidence"] is False
    assert payload["safety"]["executes_database_apply"] is False
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_apply_final_preflight_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled apply final preflight should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-apply-final-preflight?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_apply_final_preflight
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_apply_final_preflight"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-evidence-execution-closeout"
    )
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_count"] == 1
    assert payload["summary"]["controlled_apply_final_preflight_field_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_acceptance_gate_count"] == 10
    assert payload["summary"]["rollback_binding_count"] == 1
    assert payload["summary"]["rollback_binding_field_count"] == 8
    assert payload["summary"]["post_apply_verifier_binding_count"] == 1
    assert payload["summary"]["post_apply_verifier_binding_field_count"] == 8
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "database_apply_authorized"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "executes_authorization_evidence"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["future_database_apply_controlled_apply_final_preflight"][
            "writes_database"
        ]
        is False
    )
    assert payload["controlled_apply_final_preflight"]["dry_run_only"] is True
    assert payload["controlled_apply_final_preflight"]["check_mode_only"] is True
    assert payload["controlled_apply_final_preflight"]["accepts_plaintext_secret"] is False
    assert payload["controlled_apply_final_preflight"]["reads_secret_in_preview"] is False
    assert payload["controlled_apply_final_preflight"]["signature_material_included"] is False
    assert payload["controlled_apply_final_preflight"]["secret_material_included"] is False
    assert (
        payload["controlled_apply_final_preflight"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["controlled_apply_final_preflight"]["executes_authorization_evidence"] is False
    assert payload["controlled_apply_final_preflight"]["executes_database_apply"] is False
    assert payload["controlled_apply_final_preflight"]["executes_endpoint_in_preview"] is False
    assert payload["controlled_apply_final_preflight"]["executes_sql_in_preview"] is False
    assert payload["controlled_apply_final_preflight"]["writes_database_in_preview"] is False
    assert payload["controlled_apply_final_preflight"]["ready_for_database_apply_now"] is False
    assert payload["controlled_apply_final_preflight"]["database_apply_authorized"] is False
    assert (
        payload["controlled_apply_final_preflight"]["rollback_binding"][
            "rollback_execution_authorized"
        ]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight"]["rollback_binding"][
            "rollback_executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight"]["post_apply_verifier_binding"][
            "verifier_execution_authorized_in_preview"
        ]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight"]["post_apply_verifier_binding"][
            "database_apply_authorized"
        ]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight_contract"]["executes_endpoint"]
        is False
    )
    assert payload["controlled_apply_final_preflight_contract"]["executes_sql"] is False
    assert (
        payload["controlled_apply_final_preflight_contract"]["database_apply_authorized"]
        is False
    )
    assert (
        payload["controlled_apply_final_preflight_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run post-receipt parser closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-post-receipt-parser-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_no_apply_enforcement_verification"
    ]
    parser_closeout = payload[
        "controlled_dry_run_post_receipt_parser_closeout"
    ]
    enforcement = parser_closeout["no_apply_enforcement_verification"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_post_receipt_parser_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-runner-execution-receipt-closeout"
    )
    assert payload["summary"]["controlled_dry_run_post_receipt_parser_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_execution_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_command_artifact_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_post_receipt_parser_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_post_receipt_parser_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_post_receipt_parser_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["no_apply_enforcement_verification_count"] == 1
    assert payload["summary"]["no_apply_enforcement_verification_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert parser_closeout["post_receipt_parser_closeout_only"] is True
    assert parser_closeout["no_apply_enforcement_verification_only"] is True
    assert parser_closeout["dry_run_only"] is True
    assert parser_closeout["check_mode_only"] is True
    assert parser_closeout["accepts_plaintext_secret"] is False
    assert parser_closeout["reads_secret_in_preview"] is False
    assert parser_closeout["signature_material_included"] is False
    assert parser_closeout["secret_material_included"] is False
    assert parser_closeout["signs_database_apply_authorization"] is False
    assert parser_closeout["executes_authorization_evidence"] is False
    assert parser_closeout["executes_database_apply"] is False
    assert parser_closeout["executes_endpoint_in_preview"] is False
    assert parser_closeout["executes_sql_in_preview"] is False
    assert parser_closeout["writes_database_in_preview"] is False
    assert enforcement["endpoint_execution_allowed"] is False
    assert enforcement["sql_execution_allowed"] is False
    assert enforcement["database_write_allowed"] is False
    assert enforcement["database_apply_authorized"] is False
    assert enforcement["executes_database_apply"] is False
    assert enforcement["executes_endpoint"] is False
    assert enforcement["executes_sql"] is False
    assert enforcement["writes_database"] is False
    assert (
        payload["controlled_dry_run_post_receipt_parser_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_post_receipt_parser_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_post_receipt_parser_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_post_receipt_parser_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_post_receipt_parser_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run no-apply enforcement closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-apply-enforcement-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_final_dry_run_executor_guard"
    ]
    enforcement_closeout = payload[
        "controlled_dry_run_no_apply_enforcement_closeout"
    ]
    final_guard = enforcement_closeout["final_dry_run_executor_guard"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_apply_enforcement_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-post-receipt-parser-closeout"
    )
    assert payload["summary"]["controlled_dry_run_no_apply_enforcement_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_post_receipt_parser_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_execution_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_apply_enforcement_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_no_apply_enforcement_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_apply_enforcement_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["final_dry_run_executor_guard_count"] == 1
    assert payload["summary"]["final_dry_run_executor_guard_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert enforcement_closeout["no_apply_enforcement_closeout_only"] is True
    assert enforcement_closeout["final_dry_run_executor_guard_only"] is True
    assert enforcement_closeout["dry_run_only"] is True
    assert enforcement_closeout["check_mode_only"] is True
    assert enforcement_closeout["accepts_plaintext_secret"] is False
    assert enforcement_closeout["reads_secret_in_preview"] is False
    assert enforcement_closeout["signature_material_included"] is False
    assert enforcement_closeout["secret_material_included"] is False
    assert enforcement_closeout["signs_database_apply_authorization"] is False
    assert enforcement_closeout["executes_authorization_evidence"] is False
    assert enforcement_closeout["executes_database_apply"] is False
    assert enforcement_closeout["executes_endpoint_in_preview"] is False
    assert enforcement_closeout["executes_sql_in_preview"] is False
    assert enforcement_closeout["writes_database_in_preview"] is False
    assert final_guard["dry_run_executor_invocation_allowed"] is False
    assert final_guard["endpoint_execution_allowed"] is False
    assert final_guard["sql_execution_allowed"] is False
    assert final_guard["database_write_allowed"] is False
    assert final_guard["database_apply_authorized"] is False
    assert final_guard["executes_database_apply"] is False
    assert final_guard["executes_endpoint"] is False
    assert final_guard["executes_sql"] is False
    assert final_guard["writes_database"] is False
    assert (
        payload["controlled_dry_run_no_apply_enforcement_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_no_apply_enforcement_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_no_apply_enforcement_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_no_apply_enforcement_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_no_apply_enforcement_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run final executor guard closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-final-executor-guard-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_pre_apply_replay_verifier"
    ]
    guard_closeout = payload[
        "controlled_dry_run_final_executor_guard_closeout"
    ]
    replay = guard_closeout["pre_apply_replay_verifier"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_final_executor_guard_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-apply-enforcement-closeout"
    )
    assert payload["summary"]["controlled_dry_run_final_executor_guard_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_apply_enforcement_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_post_receipt_parser_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_executor_guard_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_final_executor_guard_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_executor_guard_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["pre_apply_replay_verifier_count"] == 1
    assert payload["summary"]["pre_apply_replay_verifier_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert guard_closeout["final_executor_guard_closeout_only"] is True
    assert guard_closeout["pre_apply_replay_verifier_only"] is True
    assert guard_closeout["dry_run_only"] is True
    assert guard_closeout["check_mode_only"] is True
    assert guard_closeout["accepts_plaintext_secret"] is False
    assert guard_closeout["reads_secret_in_preview"] is False
    assert guard_closeout["signature_material_included"] is False
    assert guard_closeout["secret_material_included"] is False
    assert guard_closeout["signs_database_apply_authorization"] is False
    assert guard_closeout["executes_authorization_evidence"] is False
    assert guard_closeout["executes_database_apply"] is False
    assert guard_closeout["executes_endpoint_in_preview"] is False
    assert guard_closeout["executes_sql_in_preview"] is False
    assert guard_closeout["writes_database_in_preview"] is False
    assert replay["replay_mode"] == "pre_apply_replay_preview_only"
    assert replay["dry_run_executor_invocation_allowed"] is False
    assert replay["endpoint_execution_allowed"] is False
    assert replay["sql_execution_allowed"] is False
    assert replay["database_write_allowed"] is False
    assert replay["database_apply_authorized"] is False
    assert replay["executes_database_apply"] is False
    assert replay["executes_endpoint"] is False
    assert replay["executes_sql"] is False
    assert replay["writes_database"] is False
    assert (
        payload["controlled_dry_run_final_executor_guard_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_final_executor_guard_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_final_executor_guard_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_final_executor_guard_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_final_executor_guard_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run pre-apply replay closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-pre-apply-replay-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_apply_executor_readiness_contract"
    ]
    replay_closeout = payload[
        "controlled_dry_run_pre_apply_replay_closeout"
    ]
    readiness = replay_closeout["apply_executor_readiness_contract"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_pre_apply_replay_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-final-executor-guard-closeout"
    )
    assert payload["summary"]["controlled_dry_run_pre_apply_replay_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_executor_guard_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_apply_enforcement_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_pre_apply_replay_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_pre_apply_replay_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_pre_apply_replay_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["apply_executor_readiness_contract_count"] == 1
    assert payload["summary"]["apply_executor_readiness_contract_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert replay_closeout["pre_apply_replay_closeout_only"] is True
    assert replay_closeout["apply_executor_readiness_contract_only"] is True
    assert replay_closeout["dry_run_only"] is True
    assert replay_closeout["check_mode_only"] is True
    assert replay_closeout["accepts_plaintext_secret"] is False
    assert replay_closeout["reads_secret_in_preview"] is False
    assert replay_closeout["signature_material_included"] is False
    assert replay_closeout["secret_material_included"] is False
    assert replay_closeout["signs_database_apply_authorization"] is False
    assert replay_closeout["executes_authorization_evidence"] is False
    assert replay_closeout["executes_database_apply"] is False
    assert replay_closeout["executes_endpoint_in_preview"] is False
    assert replay_closeout["executes_sql_in_preview"] is False
    assert replay_closeout["writes_database_in_preview"] is False
    assert readiness["readiness_mode"] == "apply_executor_readiness_contract_preview_only"
    assert readiness["dry_run_executor_invocation_allowed"] is False
    assert readiness["endpoint_execution_allowed"] is False
    assert readiness["sql_execution_allowed"] is False
    assert readiness["database_write_allowed"] is False
    assert readiness["ready_for_database_apply_now"] is False
    assert readiness["database_apply_authorized"] is False
    assert readiness["executes_database_apply"] is False
    assert readiness["executes_endpoint"] is False
    assert readiness["executes_sql"] is False
    assert readiness["writes_database"] is False
    assert (
        payload["controlled_dry_run_pre_apply_replay_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_pre_apply_replay_closeout_contract"][
            "ready_for_dry_run_executor_invocation_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_pre_apply_replay_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_pre_apply_replay_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_pre_apply_replay_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_pre_apply_replay_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run apply executor readiness closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-apply-executor-readiness-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_invocation_readiness_receipt"
    ]
    readiness_closeout = payload[
        "controlled_dry_run_apply_executor_readiness_closeout"
    ]
    receipt = readiness_closeout["dry_run_invocation_readiness_receipt"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_apply_executor_readiness_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-pre-apply-replay-closeout"
    )
    assert payload["summary"]["controlled_dry_run_apply_executor_readiness_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_pre_apply_replay_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_executor_guard_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_apply_executor_readiness_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_apply_executor_readiness_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_apply_executor_readiness_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["dry_run_invocation_readiness_receipt_count"] == 1
    assert payload["summary"]["dry_run_invocation_readiness_receipt_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert readiness_closeout["apply_executor_readiness_closeout_only"] is True
    assert readiness_closeout["dry_run_invocation_readiness_receipt_only"] is True
    assert readiness_closeout["dry_run_only"] is True
    assert readiness_closeout["check_mode_only"] is True
    assert readiness_closeout["accepts_plaintext_secret"] is False
    assert readiness_closeout["reads_secret_in_preview"] is False
    assert readiness_closeout["signature_material_included"] is False
    assert readiness_closeout["secret_material_included"] is False
    assert readiness_closeout["signs_database_apply_authorization"] is False
    assert readiness_closeout["executes_authorization_evidence"] is False
    assert readiness_closeout["executes_database_apply"] is False
    assert readiness_closeout["executes_endpoint_in_preview"] is False
    assert readiness_closeout["executes_sql_in_preview"] is False
    assert readiness_closeout["writes_database_in_preview"] is False
    assert receipt["receipt_mode"] == "dry_run_invocation_readiness_preview_only"
    assert receipt["dry_run_executor_invocation_allowed"] is False
    assert receipt["ready_for_dry_run_executor_invocation_now"] is False
    assert receipt["endpoint_execution_allowed"] is False
    assert receipt["sql_execution_allowed"] is False
    assert receipt["database_write_allowed"] is False
    assert receipt["ready_for_database_apply_now"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "ready_for_dry_run_executor_invocation_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "ready_for_actual_dry_run_execution_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_apply_executor_readiness_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run invocation receipt closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-invocation-receipt-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_no_write_invocation_package"
    ]
    invocation_closeout = payload[
        "controlled_dry_run_invocation_receipt_closeout"
    ]
    package = invocation_closeout["no_write_invocation_package"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_invocation_receipt_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-apply-executor-readiness-closeout"
    )
    assert payload["summary"]["controlled_dry_run_invocation_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_apply_executor_readiness_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_pre_apply_replay_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_invocation_receipt_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_invocation_receipt_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_invocation_receipt_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["no_write_invocation_package_count"] == 1
    assert payload["summary"]["no_write_invocation_package_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert invocation_closeout["invocation_receipt_closeout_only"] is True
    assert invocation_closeout["no_write_invocation_package_only"] is True
    assert invocation_closeout["dry_run_only"] is True
    assert invocation_closeout["check_mode_only"] is True
    assert invocation_closeout["accepts_plaintext_secret"] is False
    assert invocation_closeout["reads_secret_in_preview"] is False
    assert invocation_closeout["signature_material_included"] is False
    assert invocation_closeout["secret_material_included"] is False
    assert invocation_closeout["signs_database_apply_authorization"] is False
    assert invocation_closeout["executes_authorization_evidence"] is False
    assert invocation_closeout["executes_database_apply"] is False
    assert invocation_closeout["executes_endpoint_in_preview"] is False
    assert invocation_closeout["executes_sql_in_preview"] is False
    assert invocation_closeout["writes_database_in_preview"] is False
    assert package["package_mode"] == "no_write_invocation_package_preview_only"
    assert package["dry_run_executor_invocation_allowed"] is False
    assert package["ready_for_no_write_dry_run_invocation_package_now"] is False
    assert package["ready_for_actual_dry_run_execution_now"] is False
    assert package["endpoint_execution_allowed"] is False
    assert package["sql_execution_allowed"] is False
    assert package["database_write_allowed"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert package["executes_database_apply"] is False
    assert package["executes_endpoint"] is False
    assert package["executes_sql"] is False
    assert package["writes_database"] is False
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "ready_for_dry_run_executor_invocation_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "ready_for_actual_dry_run_execution_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_invocation_receipt_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run no-write invocation package closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-write-invocation-package-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_execution_preflight_guard"
    ]
    package_closeout = payload[
        "controlled_dry_run_no_write_invocation_package_closeout"
    ]
    guard = package_closeout["execution_preflight_guard"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_write_invocation_package_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-invocation-receipt-closeout"
    )
    assert payload["summary"]["controlled_dry_run_no_write_invocation_package_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_invocation_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_apply_executor_readiness_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_write_invocation_package_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_no_write_invocation_package_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_write_invocation_package_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["execution_preflight_guard_count"] == 1
    assert payload["summary"]["execution_preflight_guard_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert package_closeout["no_write_invocation_package_closeout_only"] is True
    assert package_closeout["execution_preflight_guard_only"] is True
    assert package_closeout["dry_run_only"] is True
    assert package_closeout["check_mode_only"] is True
    assert package_closeout["accepts_plaintext_secret"] is False
    assert package_closeout["reads_secret_in_preview"] is False
    assert package_closeout["signature_material_included"] is False
    assert package_closeout["secret_material_included"] is False
    assert package_closeout["signs_database_apply_authorization"] is False
    assert package_closeout["executes_authorization_evidence"] is False
    assert package_closeout["executes_database_apply"] is False
    assert package_closeout["executes_endpoint_in_preview"] is False
    assert package_closeout["executes_sql_in_preview"] is False
    assert package_closeout["writes_database_in_preview"] is False
    assert guard["guard_mode"] == "execution_preflight_guard_preview_only"
    assert guard["dry_run_executor_invocation_allowed"] is False
    assert guard["ready_for_execution_preflight_guard_now"] is False
    assert guard["ready_for_dry_run_executor_invocation_now"] is False
    assert guard["ready_for_actual_dry_run_execution_now"] is False
    assert guard["endpoint_execution_allowed"] is False
    assert guard["sql_execution_allowed"] is False
    assert guard["database_write_allowed"] is False
    assert guard["ready_for_database_apply_now"] is False
    assert guard["database_apply_authorized"] is False
    assert guard["executes_database_apply"] is False
    assert guard["executes_endpoint"] is False
    assert guard["executes_sql"] is False
    assert guard["writes_database"] is False
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["ready_for_dry_run_executor_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["ready_for_actual_dry_run_execution_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["executes_endpoint"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["executes_sql"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_write_invocation_package_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run execution preflight guard closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-execution-preflight-guard-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_runner_invocation_boundary"
    ]
    guard_closeout = payload[
        "controlled_dry_run_execution_preflight_guard_closeout"
    ]
    boundary = guard_closeout["runner_invocation_boundary"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_preflight_guard_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-write-invocation-package-closeout"
    )
    assert payload["summary"]["controlled_dry_run_execution_preflight_guard_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_write_invocation_package_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_invocation_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_preflight_guard_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_execution_preflight_guard_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_preflight_guard_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["runner_invocation_boundary_count"] == 1
    assert payload["summary"]["runner_invocation_boundary_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert guard_closeout["execution_preflight_guard_closeout_only"] is True
    assert guard_closeout["runner_invocation_boundary_only"] is True
    assert guard_closeout["dry_run_only"] is True
    assert guard_closeout["check_mode_only"] is True
    assert guard_closeout["accepts_plaintext_secret"] is False
    assert guard_closeout["reads_secret_in_preview"] is False
    assert guard_closeout["signature_material_included"] is False
    assert guard_closeout["secret_material_included"] is False
    assert guard_closeout["signs_database_apply_authorization"] is False
    assert guard_closeout["executes_authorization_evidence"] is False
    assert guard_closeout["executes_database_apply"] is False
    assert guard_closeout["executes_endpoint_in_preview"] is False
    assert guard_closeout["executes_sql_in_preview"] is False
    assert guard_closeout["writes_database_in_preview"] is False
    assert boundary["boundary_mode"] == "runner_invocation_boundary_preview_only"
    assert boundary["dry_run_executor_invocation_allowed"] is False
    assert boundary["runner_invocation_allowed"] is False
    assert boundary["ready_for_runner_invocation_boundary_now"] is False
    assert boundary["ready_for_dry_run_executor_invocation_now"] is False
    assert boundary["ready_for_actual_dry_run_execution_now"] is False
    assert boundary["endpoint_execution_allowed"] is False
    assert boundary["sql_execution_allowed"] is False
    assert boundary["database_write_allowed"] is False
    assert boundary["ready_for_database_apply_now"] is False
    assert boundary["database_apply_authorized"] is False
    assert boundary["executes_database_apply"] is False
    assert boundary["executes_endpoint"] is False
    assert boundary["executes_sql"] is False
    assert boundary["writes_database"] is False
    assert boundary["captures_stdout"] is False
    assert boundary["captures_stderr"] is False
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["ready_for_dry_run_executor_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["ready_for_actual_dry_run_execution_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["executes_endpoint"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["executes_sql"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_preflight_guard_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run runner invocation boundary closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-runner-invocation-boundary-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_no_execution_receipt_handoff"
    ]
    boundary_closeout = payload[
        "controlled_dry_run_runner_invocation_boundary_closeout"
    ]
    handoff = boundary_closeout["no_execution_receipt_handoff"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_invocation_boundary_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-execution-preflight-guard-closeout"
    )
    assert payload["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_preflight_guard_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_write_invocation_package_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["no_execution_receipt_handoff_count"] == 1
    assert payload["summary"]["no_execution_receipt_handoff_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["execution_receipt_present"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert boundary_closeout["runner_invocation_boundary_closeout_only"] is True
    assert boundary_closeout["no_execution_receipt_handoff_only"] is True
    assert boundary_closeout["dry_run_only"] is True
    assert boundary_closeout["check_mode_only"] is True
    assert boundary_closeout["accepts_plaintext_secret"] is False
    assert boundary_closeout["reads_secret_in_preview"] is False
    assert boundary_closeout["signature_material_included"] is False
    assert boundary_closeout["secret_material_included"] is False
    assert boundary_closeout["signs_database_apply_authorization"] is False
    assert boundary_closeout["executes_authorization_evidence"] is False
    assert boundary_closeout["executes_database_apply"] is False
    assert boundary_closeout["executes_endpoint_in_preview"] is False
    assert boundary_closeout["executes_sql_in_preview"] is False
    assert boundary_closeout["writes_database_in_preview"] is False
    assert boundary_closeout["captures_stdout"] is False
    assert boundary_closeout["captures_stderr"] is False
    assert handoff["handoff_mode"] == "no_execution_receipt_handoff_preview_only"
    assert handoff["execution_receipt_present"] is False
    assert handoff["execution_receipt_required"] is False
    assert handoff["dry_run_executor_invocation_allowed"] is False
    assert handoff["runner_invocation_allowed"] is False
    assert handoff["ready_for_no_execution_receipt_handoff_now"] is False
    assert handoff["ready_for_dry_run_executor_invocation_now"] is False
    assert handoff["ready_for_actual_dry_run_execution_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["executes_database_apply"] is False
    assert handoff["executes_endpoint"] is False
    assert handoff["executes_sql"] is False
    assert handoff["writes_database"] is False
    assert handoff["stdout_included"] is False
    assert handoff["stderr_included"] is False
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["ready_for_dry_run_executor_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["ready_for_actual_dry_run_execution_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["executes_endpoint"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["executes_sql"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_runner_invocation_boundary_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run no-execution receipt handoff closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_final_no_runner_execution_proof"
    ]
    handoff_closeout = payload[
        "controlled_dry_run_no_execution_receipt_handoff_closeout"
    ]
    proof = handoff_closeout["final_no_runner_execution_proof"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_execution_receipt_handoff_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-runner-invocation-boundary-closeout"
    )
    assert payload["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_preflight_guard_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["final_no_runner_execution_proof_count"] == 1
    assert payload["summary"]["final_no_runner_execution_proof_field_count"] == 12
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert handoff_closeout["no_execution_receipt_handoff_closeout_only"] is True
    assert handoff_closeout["final_no_runner_execution_proof_only"] is True
    assert handoff_closeout["dry_run_only"] is True
    assert handoff_closeout["check_mode_only"] is True
    assert handoff_closeout["accepts_plaintext_secret"] is False
    assert handoff_closeout["reads_secret_in_preview"] is False
    assert handoff_closeout["signature_material_included"] is False
    assert handoff_closeout["secret_material_included"] is False
    assert handoff_closeout["signs_database_apply_authorization"] is False
    assert handoff_closeout["executes_authorization_evidence"] is False
    assert handoff_closeout["executes_database_apply"] is False
    assert handoff_closeout["executes_endpoint_in_preview"] is False
    assert handoff_closeout["executes_sql_in_preview"] is False
    assert handoff_closeout["writes_database_in_preview"] is False
    assert handoff_closeout["stdout_included"] is False
    assert handoff_closeout["stderr_included"] is False
    assert proof["proof_mode"] == "final_no_runner_execution_proof_preview_only"
    assert proof["execution_receipt_present"] is False
    assert proof["execution_receipt_required"] is False
    assert proof["dry_run_executor_invoked"] is False
    assert proof["runner_invocation_performed"] is False
    assert proof["endpoint_executed"] is False
    assert proof["sql_executed"] is False
    assert proof["database_written"] is False
    assert proof["dry_run_executor_invocation_allowed"] is False
    assert proof["runner_invocation_allowed"] is False
    assert proof["ready_for_final_no_runner_execution_proof_now"] is False
    assert proof["ready_for_dry_run_executor_invocation_now"] is False
    assert proof["ready_for_actual_dry_run_execution_now"] is False
    assert proof["endpoint_execution_allowed"] is False
    assert proof["sql_execution_allowed"] is False
    assert proof["database_write_allowed"] is False
    assert proof["ready_for_database_apply_now"] is False
    assert proof["database_apply_authorized"] is False
    assert proof["executes_database_apply"] is False
    assert proof["executes_endpoint"] is False
    assert proof["executes_sql"] is False
    assert proof["writes_database"] is False
    assert proof["stdout_included"] is False
    assert proof["stderr_included"] is False
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["ready_for_dry_run_executor_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["ready_for_actual_dry_run_execution_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["executes_endpoint"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["executes_sql"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_no_execution_receipt_handoff_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run final no-runner proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_controlled_executor_quarantine_proof"
    ]
    proof_closeout = payload[
        "controlled_dry_run_final_no_runner_execution_proof_closeout"
    ]
    quarantine = proof_closeout["controlled_executor_quarantine_proof"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_final_no_runner_execution_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-execution-receipt-handoff-closeout"
    )
    assert payload["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_invocation_boundary_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["controlled_executor_quarantine_proof_count"] == 1
    assert payload["summary"]["controlled_executor_quarantine_proof_field_count"] == 12
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["controlled_executor_quarantine_bound"] is True
    assert future["executor_quarantine_enforced"] is True
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert proof_closeout["final_no_runner_execution_proof_closeout_only"] is True
    assert proof_closeout["controlled_executor_quarantine_proof_only"] is True
    assert proof_closeout["dry_run_only"] is True
    assert proof_closeout["check_mode_only"] is True
    assert proof_closeout["accepts_plaintext_secret"] is False
    assert proof_closeout["reads_secret_in_preview"] is False
    assert proof_closeout["signature_material_included"] is False
    assert proof_closeout["secret_material_included"] is False
    assert proof_closeout["signs_database_apply_authorization"] is False
    assert proof_closeout["executes_authorization_evidence"] is False
    assert proof_closeout["executes_database_apply"] is False
    assert proof_closeout["executes_endpoint_in_preview"] is False
    assert proof_closeout["executes_sql_in_preview"] is False
    assert proof_closeout["writes_database_in_preview"] is False
    assert proof_closeout["stdout_included"] is False
    assert proof_closeout["stderr_included"] is False
    assert quarantine["quarantine_mode"] == "controlled_executor_quarantine_proof_preview_only"
    assert quarantine["controlled_executor_quarantine_bound"] is True
    assert quarantine["executor_quarantine_enforced"] is True
    assert quarantine["execution_receipt_present"] is False
    assert quarantine["execution_receipt_required"] is False
    assert quarantine["dry_run_executor_invoked"] is False
    assert quarantine["runner_invocation_performed"] is False
    assert quarantine["endpoint_executed"] is False
    assert quarantine["sql_executed"] is False
    assert quarantine["database_written"] is False
    assert quarantine["dry_run_executor_invocation_allowed"] is False
    assert quarantine["runner_invocation_allowed"] is False
    assert quarantine["ready_for_controlled_executor_quarantine_now"] is False
    assert quarantine["ready_for_dry_run_executor_invocation_now"] is False
    assert quarantine["ready_for_actual_dry_run_execution_now"] is False
    assert quarantine["endpoint_execution_allowed"] is False
    assert quarantine["sql_execution_allowed"] is False
    assert quarantine["database_write_allowed"] is False
    assert quarantine["ready_for_database_apply_now"] is False
    assert quarantine["database_apply_authorized"] is False
    assert quarantine["executes_database_apply"] is False
    assert quarantine["executes_endpoint"] is False
    assert quarantine["executes_sql"] is False
    assert quarantine["writes_database"] is False
    assert quarantine["stdout_included"] is False
    assert quarantine["stderr_included"] is False
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["ready_for_dry_run_executor_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["ready_for_actual_dry_run_execution_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["executes_endpoint"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["executes_sql"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_final_no_runner_execution_proof_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run controlled executor quarantine proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-controlled-executor-quarantine-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_execution_envelope_freeze_proof"
    ]
    quarantine_closeout = payload[
        "controlled_dry_run_controlled_executor_quarantine_proof_closeout"
    ]
    freeze = quarantine_closeout["dry_run_execution_envelope_freeze_proof"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_controlled_executor_quarantine_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-final-no-runner-execution-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_final_no_runner_execution_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_execution_receipt_handoff_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["dry_run_execution_envelope_freeze_proof_count"] == 1
    assert payload["summary"]["dry_run_execution_envelope_freeze_proof_field_count"] == 12
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["controlled_executor_quarantine_bound"] is True
    assert future["executor_quarantine_enforced"] is True
    assert future["execution_envelope_frozen"] is True
    assert future["execution_envelope_mutation_allowed"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["execution_receipt_present"] is False
    assert future["dry_run_executor_invocation_allowed"] is False
    assert future["runner_invocation_allowed"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert quarantine_closeout["controlled_executor_quarantine_proof_closeout_only"] is True
    assert quarantine_closeout["dry_run_execution_envelope_freeze_proof_only"] is True
    assert quarantine_closeout["dry_run_only"] is True
    assert quarantine_closeout["check_mode_only"] is True
    assert quarantine_closeout["execution_envelope_frozen"] is True
    assert quarantine_closeout["execution_envelope_mutation_allowed"] is False
    assert quarantine_closeout["accepts_plaintext_secret"] is False
    assert quarantine_closeout["reads_secret_in_preview"] is False
    assert quarantine_closeout["signature_material_included"] is False
    assert quarantine_closeout["secret_material_included"] is False
    assert quarantine_closeout["signs_database_apply_authorization"] is False
    assert quarantine_closeout["executes_authorization_evidence"] is False
    assert quarantine_closeout["executes_database_apply"] is False
    assert quarantine_closeout["executes_endpoint_in_preview"] is False
    assert quarantine_closeout["executes_sql_in_preview"] is False
    assert quarantine_closeout["writes_database_in_preview"] is False
    assert quarantine_closeout["stdout_included"] is False
    assert quarantine_closeout["stderr_included"] is False
    assert freeze["freeze_mode"] == "dry_run_execution_envelope_freeze_proof_preview_only"
    assert freeze["execution_envelope_frozen"] is True
    assert freeze["execution_envelope_mutation_allowed"] is False
    assert freeze["execution_receipt_present"] is False
    assert freeze["execution_receipt_required"] is False
    assert freeze["dry_run_executor_invoked"] is False
    assert freeze["runner_invocation_performed"] is False
    assert freeze["endpoint_executed"] is False
    assert freeze["sql_executed"] is False
    assert freeze["database_written"] is False
    assert freeze["dry_run_executor_invocation_allowed"] is False
    assert freeze["runner_invocation_allowed"] is False
    assert freeze["ready_for_dry_run_executor_invocation_now"] is False
    assert freeze["ready_for_actual_dry_run_execution_now"] is False
    assert freeze["endpoint_execution_allowed"] is False
    assert freeze["sql_execution_allowed"] is False
    assert freeze["database_write_allowed"] is False
    assert freeze["ready_for_database_apply_now"] is False
    assert freeze["database_apply_authorized"] is False
    assert freeze["executes_database_apply"] is False
    assert freeze["executes_endpoint"] is False
    assert freeze["executes_sql"] is False
    assert freeze["writes_database"] is False
    assert freeze["stdout_included"] is False
    assert freeze["stderr_included"] is False
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["ready_for_dry_run_executor_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["ready_for_actual_dry_run_execution_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["executes_endpoint"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["executes_sql"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_controlled_executor_quarantine_proof_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run execution envelope freeze proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-execution-envelope-freeze-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_frozen_envelope_verifier_handoff"
    ]
    freeze_closeout = payload[
        "controlled_dry_run_execution_envelope_freeze_proof_closeout"
    ]
    handoff = freeze_closeout["frozen_envelope_verifier_handoff"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_envelope_freeze_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-controlled-executor-quarantine-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_controlled_executor_quarantine_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["frozen_envelope_verifier_handoff_count"] == 1
    assert payload["summary"]["frozen_envelope_verifier_handoff_field_count"] == 12
    assert payload["summary"]["verifier_invoked_count"] == 0
    assert payload["summary"]["verifier_receipt_present_count"] == 0
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["execution_envelope_frozen"] is True
    assert future["execution_envelope_mutation_allowed"] is False
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["ready_for_dry_run_executor_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert freeze_closeout["execution_envelope_freeze_proof_closeout_only"] is True
    assert freeze_closeout["frozen_envelope_verifier_handoff_only"] is True
    assert freeze_closeout["dry_run_only"] is True
    assert freeze_closeout["check_mode_only"] is True
    assert freeze_closeout["execution_envelope_frozen"] is True
    assert freeze_closeout["execution_envelope_mutation_allowed"] is False
    assert freeze_closeout["verifier_invocation_allowed"] is False
    assert freeze_closeout["verifier_invoked"] is False
    assert freeze_closeout["verifier_receipt_present"] is False
    assert freeze_closeout["accepts_plaintext_secret"] is False
    assert freeze_closeout["reads_secret_in_preview"] is False
    assert freeze_closeout["signature_material_included"] is False
    assert freeze_closeout["secret_material_included"] is False
    assert freeze_closeout["signs_database_apply_authorization"] is False
    assert freeze_closeout["executes_authorization_evidence"] is False
    assert freeze_closeout["executes_database_apply"] is False
    assert freeze_closeout["executes_endpoint_in_preview"] is False
    assert freeze_closeout["executes_sql_in_preview"] is False
    assert freeze_closeout["writes_database_in_preview"] is False
    assert handoff["verifier_handoff_mode"] == "frozen_envelope_verifier_handoff_preview_only"
    assert handoff["execution_envelope_frozen"] is True
    assert handoff["execution_envelope_mutation_allowed"] is False
    assert handoff["verifier_invocation_allowed"] is False
    assert handoff["verifier_invoked"] is False
    assert handoff["verifier_receipt_present"] is False
    assert handoff["dry_run_executor_invoked"] is False
    assert handoff["runner_invocation_performed"] is False
    assert handoff["endpoint_executed"] is False
    assert handoff["sql_executed"] is False
    assert handoff["database_written"] is False
    assert handoff["ready_for_verifier_invocation_now"] is False
    assert handoff["ready_for_dry_run_executor_invocation_now"] is False
    assert handoff["endpoint_execution_allowed"] is False
    assert handoff["sql_execution_allowed"] is False
    assert handoff["database_write_allowed"] is False
    assert handoff["ready_for_database_apply_now"] is False
    assert handoff["database_apply_authorized"] is False
    assert handoff["executes_database_apply"] is False
    assert handoff["executes_endpoint"] is False
    assert handoff["executes_sql"] is False
    assert handoff["writes_database"] is False
    assert (
        payload[
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
        ]["ready_for_verifier_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_execution_envelope_freeze_proof_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run frozen envelope verifier handoff closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-frozen-envelope-verifier-handoff-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_verifier_invocation_lock_proof"
    ]
    handoff_closeout = payload[
        "controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
    ]
    lock = handoff_closeout["verifier_invocation_lock_proof"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_frozen_envelope_verifier_handoff_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-execution-envelope-freeze-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_envelope_freeze_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_invocation_lock_proof_count"] == 1
    assert payload["summary"]["verifier_invocation_lock_proof_field_count"] == 12
    assert payload["summary"]["verifier_invocation_locked_count"] == 1
    assert payload["summary"]["verifier_invoked_count"] == 0
    assert payload["summary"]["verifier_receipt_present_count"] == 0
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["verifier_invocation_locked"] is True
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert future["stdout_included"] is False
    assert future["stderr_included"] is False
    assert handoff_closeout["frozen_envelope_verifier_handoff_closeout_only"] is True
    assert handoff_closeout["verifier_invocation_lock_proof_only"] is True
    assert handoff_closeout["dry_run_only"] is True
    assert handoff_closeout["check_mode_only"] is True
    assert handoff_closeout["verifier_invocation_locked"] is True
    assert handoff_closeout["verifier_invocation_allowed"] is False
    assert handoff_closeout["verifier_invoked"] is False
    assert handoff_closeout["verifier_receipt_present"] is False
    assert handoff_closeout["accepts_plaintext_secret"] is False
    assert handoff_closeout["reads_secret_in_preview"] is False
    assert handoff_closeout["signature_material_included"] is False
    assert handoff_closeout["secret_material_included"] is False
    assert handoff_closeout["signs_database_apply_authorization"] is False
    assert handoff_closeout["executes_authorization_evidence"] is False
    assert handoff_closeout["executes_database_apply"] is False
    assert handoff_closeout["executes_endpoint_in_preview"] is False
    assert handoff_closeout["executes_sql_in_preview"] is False
    assert handoff_closeout["writes_database_in_preview"] is False
    assert lock["lock_mode"] == "verifier_invocation_lock_proof_preview_only"
    assert lock["verifier_invocation_locked"] is True
    assert lock["verifier_invocation_allowed"] is False
    assert lock["verifier_invoked"] is False
    assert lock["verifier_receipt_present"] is False
    assert lock["dry_run_executor_invoked"] is False
    assert lock["runner_invocation_performed"] is False
    assert lock["endpoint_executed"] is False
    assert lock["sql_executed"] is False
    assert lock["database_written"] is False
    assert lock["ready_for_verifier_invocation_now"] is False
    assert lock["endpoint_execution_allowed"] is False
    assert lock["sql_execution_allowed"] is False
    assert lock["database_write_allowed"] is False
    assert lock["ready_for_database_apply_now"] is False
    assert lock["database_apply_authorized"] is False
    assert lock["executes_database_apply"] is False
    assert lock["executes_endpoint"] is False
    assert lock["executes_sql"] is False
    assert lock["writes_database"] is False
    assert (
        payload[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
        ]["verifier_invocation_locked"]
        is True
    )
    assert (
        payload[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
        ]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
        ]["ready_for_verifier_invocation_now"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
        ]["executes_database_apply"]
        is False
    )
    assert (
        payload[
            "controlled_dry_run_frozen_envelope_verifier_handoff_closeout_contract"
        ]["database_apply_authorized"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run verifier invocation lock proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-verifier-invocation-lock-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
    ]
    lock_closeout = payload[
        "controlled_dry_run_verifier_invocation_lock_proof_closeout"
    ]
    receipt = lock_closeout["verifier_no_execution_receipt_proof"]
    contract = payload[
        "controlled_dry_run_verifier_invocation_lock_proof_closeout_contract"
    ]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_invocation_lock_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-frozen-envelope-verifier-handoff-closeout"
    )
    assert payload["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_frozen_envelope_verifier_handoff_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_no_execution_receipt_proof_count"] == 1
    assert payload["summary"]["verifier_no_execution_receipt_proof_field_count"] == 12
    assert payload["summary"]["verifier_invocation_locked_count"] == 1
    assert payload["summary"]["verifier_invoked_count"] == 0
    assert payload["summary"]["verifier_receipt_present_count"] == 0
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["verifier_invocation_locked"] is True
    assert future["verifier_invocation_allowed"] is False
    assert future["verifier_invoked"] is False
    assert future["verifier_receipt_present"] is False
    assert future["dry_run_executor_invoked"] is False
    assert future["runner_invocation_performed"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_invocation_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert lock_closeout["verifier_invocation_lock_proof_closeout_only"] is True
    assert lock_closeout["verifier_no_execution_receipt_proof_only"] is True
    assert lock_closeout["verifier_invocation_locked"] is True
    assert lock_closeout["verifier_invocation_allowed"] is False
    assert lock_closeout["verifier_invoked"] is False
    assert lock_closeout["verifier_receipt_present"] is False
    assert lock_closeout["dry_run_executor_invoked"] is False
    assert lock_closeout["runner_invocation_performed"] is False
    assert lock_closeout["endpoint_executed"] is False
    assert lock_closeout["sql_executed"] is False
    assert lock_closeout["database_written"] is False
    assert receipt["receipt_mode"] == "verifier_no_execution_receipt_proof_preview_only"
    assert receipt["verifier_invocation_locked"] is True
    assert receipt["verifier_invocation_allowed"] is False
    assert receipt["verifier_invoked"] is False
    assert receipt["verifier_receipt_present"] is False
    assert receipt["dry_run_executor_invoked"] is False
    assert receipt["runner_invocation_performed"] is False
    assert receipt["endpoint_executed"] is False
    assert receipt["sql_executed"] is False
    assert receipt["database_written"] is False
    assert receipt["endpoint_execution_allowed"] is False
    assert receipt["sql_execution_allowed"] is False
    assert receipt["database_write_allowed"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert receipt["stdout_included"] is False
    assert receipt["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_no_execution_receipt_proof"
        ]
        is False
    )
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_invocation_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run verifier no-execution receipt proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-verifier-no-execution-receipt-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
    ]
    receipt_closeout = payload[
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
    ]
    guard = receipt_closeout["verifier_receipt_persistence_guard_proof"]
    contract = payload[
        "controlled_dry_run_verifier_no_execution_receipt_proof_closeout_contract"
    ]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_no_execution_receipt_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-verifier-invocation-lock-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_invocation_lock_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["verifier_receipt_persistence_guard_proof_count"] == 1
    assert payload["summary"]["verifier_receipt_persistence_guard_proof_field_count"] == 12
    assert payload["summary"]["verifier_receipt_persistence_locked_count"] == 1
    assert payload["summary"]["verifier_receipt_persistence_allowed_count"] == 0
    assert payload["summary"]["verifier_receipt_persisted_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["verifier_invoked_count"] == 0
    assert payload["summary"]["verifier_receipt_present_count"] == 0
    assert payload["summary"]["dry_run_executor_invoked_count"] == 0
    assert payload["summary"]["runner_invocation_performed_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["verifier_receipt_persistence_locked"] is True
    assert future["verifier_receipt_persistence_allowed"] is False
    assert future["verifier_receipt_persisted"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["verifier_invoked"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_verifier_receipt_persistence_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert receipt_closeout["verifier_no_execution_receipt_proof_closeout_only"] is True
    assert receipt_closeout["verifier_receipt_persistence_guard_proof_only"] is True
    assert receipt_closeout["verifier_receipt_persistence_locked"] is True
    assert receipt_closeout["verifier_receipt_persistence_allowed"] is False
    assert receipt_closeout["verifier_receipt_persisted"] is False
    assert receipt_closeout["persists_verifier_receipt"] is False
    assert receipt_closeout["verifier_invoked"] is False
    assert receipt_closeout["endpoint_executed"] is False
    assert receipt_closeout["sql_executed"] is False
    assert receipt_closeout["database_written"] is False
    assert guard["guard_mode"] == "verifier_receipt_persistence_guard_proof_preview_only"
    assert guard["verifier_receipt_persistence_locked"] is True
    assert guard["verifier_receipt_persistence_allowed"] is False
    assert guard["verifier_receipt_persisted"] is False
    assert guard["persists_verifier_receipt"] is False
    assert guard["endpoint_execution_allowed"] is False
    assert guard["sql_execution_allowed"] is False
    assert guard["database_write_allowed"] is False
    assert guard["database_apply_authorized"] is False
    assert guard["stdout_included"] is False
    assert guard["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof"
        ]
        is False
    )
    assert contract["verifier_receipt_persistence_locked"] is True
    assert contract["verifier_receipt_persisted"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_verifier_receipt_persistence_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run verifier receipt persistence guard proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-verifier-receipt-persistence-guard-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
    ]
    storage_closeout = payload[
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
    ]
    storage = storage_closeout["receipt_persistence_storage_boundary_proof"]
    contract = payload[
        "controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_contract"
    ]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-verifier-no-execution-receipt-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_no_execution_receipt_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_verifier_receipt_persistence_guard_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["receipt_persistence_storage_boundary_proof_count"] == 1
    assert payload["summary"]["receipt_persistence_storage_boundary_proof_field_count"] == 12
    assert payload["summary"]["receipt_persistence_storage_boundary_locked_count"] == 1
    assert payload["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert payload["summary"]["receipt_persistence_storage_written_count"] == 0
    assert payload["summary"]["verifier_receipt_persistence_allowed_count"] == 0
    assert payload["summary"]["verifier_receipt_persisted_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["endpoint_executed_count"] == 0
    assert payload["summary"]["sql_executed_count"] == 0
    assert payload["summary"]["database_written_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["receipt_persistence_storage_boundary_locked"] is True
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["verifier_receipt_persistence_allowed"] is False
    assert future["verifier_receipt_persisted"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["ready_for_receipt_persistence_storage_now"] is False
    assert future["endpoint_execution_allowed"] is False
    assert future["sql_execution_allowed"] is False
    assert future["database_write_allowed"] is False
    assert future["database_apply_authorized"] is False
    assert storage_closeout["verifier_receipt_persistence_guard_proof_closeout_only"] is True
    assert storage_closeout["receipt_persistence_storage_boundary_proof_only"] is True
    assert storage_closeout["receipt_persistence_storage_boundary_locked"] is True
    assert storage_closeout["receipt_persistence_storage_write_allowed"] is False
    assert storage_closeout["receipt_persistence_storage_written"] is False
    assert storage_closeout["persists_verifier_receipt"] is False
    assert storage_closeout["endpoint_executed"] is False
    assert storage_closeout["sql_executed"] is False
    assert storage_closeout["database_written"] is False
    assert storage["storage_boundary_mode"] == "receipt_persistence_storage_boundary_proof_preview_only"
    assert storage["receipt_persistence_storage_boundary_locked"] is True
    assert storage["receipt_persistence_storage_write_allowed"] is False
    assert storage["receipt_persistence_storage_written"] is False
    assert storage["verifier_receipt_persistence_allowed"] is False
    assert storage["verifier_receipt_persisted"] is False
    assert storage["persists_verifier_receipt"] is False
    assert storage["endpoint_execution_allowed"] is False
    assert storage["sql_execution_allowed"] is False
    assert storage["database_write_allowed"] is False
    assert storage["database_apply_authorized"] is False
    assert storage["stdout_included"] is False
    assert storage["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof"
        ]
        is False
    )
    assert contract["receipt_persistence_storage_boundary_locked"] is True
    assert contract["receipt_persistence_storage_write_allowed"] is False
    assert contract["receipt_persistence_storage_written"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["ready_for_receipt_persistence_storage_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run receipt persistence storage boundary proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-receipt-persistence-storage-boundary-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
    ]
    storage_closeout = payload[
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
    ]
    ledger = storage_closeout["storage_boundary_no_write_ledger_proof"]
    contract = payload[
        "controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_contract"
    ]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-verifier-receipt-persistence-guard-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_persistence_storage_boundary_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["storage_boundary_no_write_ledger_proof_count"] == 1
    assert payload["summary"]["storage_boundary_no_write_ledger_proof_field_count"] == 12
    assert payload["summary"]["storage_boundary_write_locked_count"] == 1
    assert payload["summary"]["storage_boundary_write_allowed_count"] == 0
    assert payload["summary"]["storage_boundary_written_count"] == 0
    assert payload["summary"]["ledger_write_allowed_count"] == 0
    assert payload["summary"]["ledger_written_count"] == 0
    assert payload["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert payload["summary"]["receipt_persistence_storage_written_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert future["storage_boundary_write_locked"] is True
    assert future["storage_boundary_write_allowed"] is False
    assert future["storage_boundary_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["receipt_persistence_storage_write_allowed"] is False
    assert future["receipt_persistence_storage_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert storage_closeout["receipt_persistence_storage_boundary_proof_closeout_only"] is True
    assert storage_closeout["storage_boundary_no_write_ledger_proof_only"] is True
    assert storage_closeout["storage_boundary_write_locked"] is True
    assert storage_closeout["storage_boundary_write_allowed"] is False
    assert storage_closeout["storage_boundary_written"] is False
    assert storage_closeout["ledger_write_allowed"] is False
    assert storage_closeout["ledger_written"] is False
    assert storage_closeout["receipt_persistence_storage_write_allowed"] is False
    assert storage_closeout["receipt_persistence_storage_written"] is False
    assert storage_closeout["persists_verifier_receipt"] is False
    assert storage_closeout["endpoint_executed"] is False
    assert storage_closeout["sql_executed"] is False
    assert storage_closeout["database_written"] is False
    assert ledger["ledger_mode"] == "storage_boundary_no_write_ledger_proof_preview_only"
    assert ledger["storage_boundary_write_allowed"] is False
    assert ledger["storage_boundary_written"] is False
    assert ledger["ledger_write_allowed"] is False
    assert ledger["ledger_written"] is False
    assert ledger["receipt_persistence_storage_write_allowed"] is False
    assert ledger["receipt_persistence_storage_written"] is False
    assert ledger["persists_verifier_receipt"] is False
    assert ledger["endpoint_execution_allowed"] is False
    assert ledger["sql_execution_allowed"] is False
    assert ledger["database_write_allowed"] is False
    assert ledger["database_apply_authorized"] is False
    assert ledger["stdout_included"] is False
    assert ledger["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof"
        ]
        is False
    )
    assert contract["storage_boundary_write_allowed"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["receipt_persistence_storage_write_allowed"] is False
    assert contract["persists_verifier_receipt"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run storage boundary no-write ledger proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-storage-boundary-no-write-ledger-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
    ]
    ledger_closeout = payload[
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
    ]
    retention = ledger_closeout["no_write_ledger_retention_proof"]
    contract = payload[
        "controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_contract"
    ]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-receipt-persistence-storage-boundary-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_storage_boundary_no_write_ledger_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["no_write_ledger_retention_proof_count"] == 1
    assert payload["summary"]["no_write_ledger_retention_proof_field_count"] == 12
    assert payload["summary"]["ledger_retention_write_locked_count"] == 1
    assert payload["summary"]["ledger_retention_write_allowed_count"] == 0
    assert payload["summary"]["ledger_retention_written_count"] == 0
    assert payload["summary"]["ledger_write_allowed_count"] == 0
    assert payload["summary"]["ledger_written_count"] == 0
    assert payload["summary"]["receipt_persistence_storage_write_allowed_count"] == 0
    assert payload["summary"]["receipt_persistence_storage_written_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert future["ledger_retention_write_locked"] is True
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert ledger_closeout["storage_boundary_no_write_ledger_proof_closeout_only"] is True
    assert ledger_closeout["no_write_ledger_retention_proof_only"] is True
    assert ledger_closeout["ledger_retention_write_locked"] is True
    assert ledger_closeout["ledger_retention_write_allowed"] is False
    assert ledger_closeout["ledger_retention_written"] is False
    assert ledger_closeout["ledger_write_allowed"] is False
    assert ledger_closeout["ledger_written"] is False
    assert ledger_closeout["persists_verifier_receipt"] is False
    assert ledger_closeout["endpoint_executed"] is False
    assert ledger_closeout["sql_executed"] is False
    assert ledger_closeout["database_written"] is False
    assert retention["retention_mode"] == "no_write_ledger_retention_proof_preview_only"
    assert retention["ledger_retention_write_allowed"] is False
    assert retention["ledger_retention_written"] is False
    assert retention["ledger_write_allowed"] is False
    assert retention["ledger_written"] is False
    assert retention["receipt_persistence_storage_write_allowed"] is False
    assert retention["receipt_persistence_storage_written"] is False
    assert retention["persists_verifier_receipt"] is False
    assert retention["endpoint_execution_allowed"] is False
    assert retention["sql_execution_allowed"] is False
    assert retention["database_write_allowed"] is False
    assert retention["database_apply_authorized"] is False
    assert retention["stdout_included"] is False
    assert retention["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_no_write_ledger_retention_proof"
        ]
        is False
    )
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["ledger_retention_written"] is False
    assert contract["ledger_write_allowed"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run no-write ledger retention proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-write-ledger-retention-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
    ]
    archive_closeout = payload[
        "controlled_dry_run_no_write_ledger_retention_proof_closeout"
    ]
    archive = archive_closeout["retention_boundary_no_write_archive_proof"]
    contract = payload[
        "controlled_dry_run_no_write_ledger_retention_proof_closeout_contract"
    ]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_no_write_ledger_retention_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-storage-boundary-no-write-ledger-proof-closeout"
    )
    assert payload["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_no_write_ledger_retention_proof_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["retention_boundary_no_write_archive_proof_count"] == 1
    assert payload["summary"]["retention_boundary_no_write_archive_proof_field_count"] == 12
    assert payload["summary"]["retention_archive_write_locked_count"] == 1
    assert payload["summary"]["retention_archive_write_allowed_count"] == 0
    assert payload["summary"]["retention_archive_written_count"] == 0
    assert payload["summary"]["ledger_retention_write_allowed_count"] == 0
    assert payload["summary"]["ledger_retention_written_count"] == 0
    assert payload["summary"]["ledger_write_allowed_count"] == 0
    assert payload["summary"]["ledger_written_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert future["retention_archive_write_locked"] is True
    assert future["retention_archive_write_allowed"] is False
    assert future["retention_archive_written"] is False
    assert future["ledger_retention_write_allowed"] is False
    assert future["ledger_retention_written"] is False
    assert future["ledger_write_allowed"] is False
    assert future["ledger_written"] is False
    assert future["persists_verifier_receipt"] is False
    assert future["endpoint_executed"] is False
    assert future["sql_executed"] is False
    assert future["database_written"] is False
    assert future["database_apply_authorized"] is False
    assert archive_closeout["no_write_ledger_retention_proof_closeout_only"] is True
    assert archive_closeout["retention_boundary_no_write_archive_proof_only"] is True
    assert archive_closeout["retention_archive_write_locked"] is True
    assert archive_closeout["retention_archive_write_allowed"] is False
    assert archive_closeout["retention_archive_written"] is False
    assert archive_closeout["ledger_retention_write_allowed"] is False
    assert archive_closeout["ledger_retention_written"] is False
    assert archive_closeout["persists_verifier_receipt"] is False
    assert archive_closeout["endpoint_executed"] is False
    assert archive_closeout["sql_executed"] is False
    assert archive_closeout["database_written"] is False
    assert archive["archive_mode"] == "retention_boundary_no_write_archive_proof_preview_only"
    assert archive["retention_archive_write_allowed"] is False
    assert archive["retention_archive_written"] is False
    assert archive["ledger_retention_write_allowed"] is False
    assert archive["ledger_retention_written"] is False
    assert archive["ledger_write_allowed"] is False
    assert archive["ledger_written"] is False
    assert archive["persists_verifier_receipt"] is False
    assert archive["endpoint_execution_allowed"] is False
    assert archive["sql_execution_allowed"] is False
    assert archive["database_write_allowed"] is False
    assert archive["database_apply_authorized"] is False
    assert archive["stdout_included"] is False
    assert archive["stderr_included"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_retention_boundary_no_write_archive_proof"
        ]
        is False
    )
    assert contract["retention_archive_write_allowed"] is False
    assert contract["ledger_retention_write_allowed"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run retention boundary no-write archive proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-retention-boundary-no-write-archive-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload["future_readiness"]
    handoff = payload["sealed_handoff_proof"]
    contract = payload["contract"]
    assert payload["success"] is True
    assert payload["response_mode"] == "compact"
    assert payload["full_payload_hint"] == "append full=1 for the complete nested proof payload"
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-no-write-ledger-retention-proof-closeout"
    )
    assert "source_controlled_dry_run_no_write_ledger_retention_proof_closeout" not in payload
    assert (
        "future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        not in payload
    )
    assert (
        "controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
        not in payload
    )
    assert payload["summary"]["controlled_dry_run_retention_boundary_no_write_archive_proof_closeout_check_count"] == 12
    assert payload["summary"]["archive_retention_sealed_handoff_proof_count"] == 1
    assert payload["summary"]["archive_retention_sealed_handoff_proof_field_count"] == 12
    assert payload["summary"]["sealed_handoff_write_locked_count"] == 1
    assert payload["summary"]["sealed_handoff_write_allowed_count"] == 0
    assert payload["summary"]["sealed_handoff_written_count"] == 0
    assert payload["summary"]["retention_archive_write_allowed_count"] == 0
    assert payload["summary"]["retention_archive_written_count"] == 0
    assert payload["summary"]["ledger_retention_write_allowed_count"] == 0
    assert payload["summary"]["ledger_retention_written_count"] == 0
    assert payload["summary"]["ledger_write_allowed_count"] == 0
    assert payload["summary"]["ledger_written_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
        ]
        is False
    )
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert handoff["handoff_mode"] == "archive_retention_sealed_handoff_proof_preview_only"
    assert len(handoff["sealed_handoff_manifest_hash"]) == 64
    assert handoff["sealed_handoff_write_locked"] is True
    assert handoff["sealed_handoff_write_allowed"] is False
    assert handoff["sealed_handoff_written"] is False
    assert handoff["retention_archive_write_allowed"] is False
    assert handoff["retention_archive_written"] is False
    assert handoff["ledger_retention_write_allowed"] is False
    assert handoff["ledger_retention_written"] is False
    assert handoff["ledger_write_allowed"] is False
    assert handoff["ledger_written"] is False
    assert handoff["persists_verifier_receipt"] is False
    assert handoff["endpoint_executed"] is False
    assert handoff["sql_executed"] is False
    assert handoff["database_written"] is False
    assert handoff["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_archive_retention_sealed_handoff_proof"
        ]
        is False
    )
    assert contract["sealed_handoff_write_allowed"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert len(payload["checks"]) == 12
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_route_defaults_to_compact_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run archive retention sealed handoff proof closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-archive-retention-sealed-handoff-proof-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload["future_readiness"]
    transfer = payload["sealed_handoff_verifier_transfer_proof"]
    contract = payload["contract"]
    assert payload["success"] is True
    assert payload["response_mode"] == "compact"
    assert payload["full_payload_hint"] == "append full=1 for the complete nested proof payload"
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-retention-boundary-no-write-archive-proof-closeout"
    )
    assert (
        "source_controlled_dry_run_retention_boundary_no_write_archive_proof_closeout"
        not in payload
    )
    assert (
        "future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof"
        not in payload
    )
    assert (
        "controlled_dry_run_archive_retention_sealed_handoff_proof_closeout"
        not in payload
    )
    assert payload["summary"]["controlled_dry_run_archive_retention_sealed_handoff_proof_closeout_check_count"] == 12
    assert payload["summary"]["sealed_handoff_verifier_transfer_proof_count"] == 1
    assert payload["summary"]["sealed_handoff_verifier_transfer_proof_field_count"] == 12
    assert payload["summary"]["verifier_transfer_write_locked_count"] == 1
    assert payload["summary"]["verifier_transfer_write_allowed_count"] == 0
    assert payload["summary"]["verifier_transfer_written_count"] == 0
    assert payload["summary"]["persists_verifier_receipt_count"] == 0
    assert payload["summary"]["verifier_invoked_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["executes_sql_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert (
        future[
            "ready_for_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof"
        ]
        is False
    )
    assert (
        future[
            "can_enter_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof_closeout"
        ]
        is False
    )
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert transfer["verifier_transfer_mode"] == "sealed_handoff_verifier_transfer_proof_preview_only"
    assert len(transfer["verifier_transfer_manifest_hash"]) == 64
    assert transfer["verifier_transfer_write_locked"] is True
    assert transfer["verifier_transfer_write_allowed"] is False
    assert transfer["verifier_transfer_written"] is False
    assert transfer["verifier_invocation_allowed"] is False
    assert transfer["verifier_invoked"] is False
    assert transfer["persists_verifier_receipt"] is False
    assert transfer["endpoint_executed"] is False
    assert transfer["sql_executed"] is False
    assert transfer["database_written"] is False
    assert transfer["database_apply_authorized"] is False
    assert (
        contract[
            "permits_future_database_apply_controlled_dry_run_sealed_handoff_verifier_transfer_proof"
        ]
        is False
    )
    assert contract["verifier_transfer_write_allowed"] is False
    assert contract["verifier_invocation_allowed"] is False
    assert contract["ready_for_database_apply_now"] is False
    assert contract["executes_database_apply"] is False
    assert contract["database_apply_authorized"] is False
    assert len(payload["checks"]) == 12
    assert payload["safety"]["persists_verifier_receipt"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_controlled_dry_run_package_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run package should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-package?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_package
            .__wrapped__()
        )

    payload = response.get_json()
    receipt = payload[
        "future_database_apply_controlled_dry_run_execution_receipt"
    ]
    package = payload["controlled_dry_run_package"]
    command_shape = package["dry_run_command_shape"]
    receipt_preview = package["dry_run_execution_receipt_preview"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_package"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-apply-final-preflight"
    )
    assert payload["summary"]["controlled_dry_run_package_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_package_count"] == 1
    assert payload["summary"]["controlled_dry_run_package_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_acceptance_gate_count"] == 10
    assert payload["summary"]["dry_run_execution_receipt_preview_count"] == 1
    assert payload["summary"]["dry_run_execution_receipt_field_count"] == 8
    assert payload["summary"]["rollback_binding_count"] == 1
    assert payload["summary"]["post_apply_verifier_binding_count"] == 1
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert receipt["dry_run_execution_performed"] is False
    assert receipt["ready_for_database_apply_now"] is False
    assert receipt["database_apply_authorized"] is False
    assert receipt["issues_database_apply_authorization"] is False
    assert receipt["signs_database_apply_authorization"] is False
    assert receipt["executes_authorization_evidence"] is False
    assert receipt["executes_database_apply"] is False
    assert receipt["executes_endpoint"] is False
    assert receipt["executes_sql"] is False
    assert receipt["writes_database"] is False
    assert package["dry_run_only"] is True
    assert package["check_mode_only"] is True
    assert package["accepts_plaintext_secret"] is False
    assert package["reads_secret_in_preview"] is False
    assert package["signature_material_included"] is False
    assert package["secret_material_included"] is False
    assert package["signs_database_apply_authorization"] is False
    assert package["executes_authorization_evidence"] is False
    assert package["executes_database_apply"] is False
    assert package["executes_endpoint_in_preview"] is False
    assert package["executes_sql_in_preview"] is False
    assert package["writes_database_in_preview"] is False
    assert package["ready_for_database_apply_now"] is False
    assert package["database_apply_authorized"] is False
    assert command_shape["execution_allowed"] is False
    assert command_shape["shell_command_included"] is False
    assert command_shape["sql_included"] is False
    assert command_shape["endpoint_execution_included"] is False
    assert command_shape["database_write_included"] is False
    assert receipt_preview["execution_performed"] is False
    assert receipt_preview["stdout_included"] is False
    assert receipt_preview["stderr_included"] is False
    assert receipt_preview["database_apply_authorized"] is False
    assert receipt_preview["executes_shell"] is False
    assert receipt_preview["executes_endpoint"] is False
    assert receipt_preview["executes_sql"] is False
    assert receipt_preview["writes_database"] is False
    assert receipt_preview["reads_secret"] is False
    assert (
        payload["controlled_dry_run_package_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_package_contract"]["executes_database_apply"]
        is False
    )
    assert (
        payload["controlled_dry_run_package_contract"]["executes_endpoint"]
        is False
    )
    assert payload["controlled_dry_run_package_contract"]["executes_sql"] is False
    assert (
        payload["controlled_dry_run_package_contract"]["database_apply_authorized"]
        is False
    )
    assert (
        payload["controlled_dry_run_package_contract"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_receipt_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run receipt closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-receipt-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_receipt_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_result_parser_verification"
    ]
    closeout = payload["controlled_dry_run_receipt_closeout"]
    parser = closeout["dry_run_result_parser"]
    validation = closeout["receipt_validation_report"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_receipt_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-package"
    )
    assert payload["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_package_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_receipt_closeout_field_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_closeout_acceptance_gate_count"] == 10
    assert payload["summary"]["dry_run_result_parser_count"] == 1
    assert payload["summary"]["dry_run_result_parser_field_count"] == 10
    assert payload["summary"]["receipt_validation_report_count"] == 1
    assert payload["summary"]["receipt_validation_field_count"] == 8
    assert payload["summary"]["dry_run_execution_receipt_preview_count"] == 1
    assert payload["summary"]["dry_run_execution_receipt_field_count"] == 8
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_execution_performed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert parser["execution_required"] is False
    assert parser["stdout_allowed"] is False
    assert parser["stderr_allowed"] is False
    assert parser["database_apply_authorized"] is False
    assert parser["parser_field_count"] == 10
    assert validation["execution_performed"] is False
    assert validation["stdout_included"] is False
    assert validation["stderr_included"] is False
    assert validation["database_apply_authorized"] is False
    assert validation["executes_shell"] is False
    assert validation["executes_endpoint"] is False
    assert validation["executes_sql"] is False
    assert validation["writes_database"] is False
    assert validation["reads_secret"] is False
    assert closeout["receipt_preview_only"] is True
    assert closeout["dry_run_only"] is True
    assert closeout["check_mode_only"] is True
    assert closeout["accepts_plaintext_secret"] is False
    assert closeout["reads_secret_in_preview"] is False
    assert closeout["signature_material_included"] is False
    assert closeout["secret_material_included"] is False
    assert closeout["signs_database_apply_authorization"] is False
    assert closeout["executes_authorization_evidence"] is False
    assert closeout["executes_database_apply"] is False
    assert closeout["executes_endpoint_in_preview"] is False
    assert closeout["executes_sql_in_preview"] is False
    assert closeout["writes_database_in_preview"] is False
    assert closeout["ready_for_database_apply_now"] is False
    assert closeout["database_apply_authorized"] is False
    assert (
        payload["controlled_dry_run_receipt_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_receipt_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_receipt_closeout_contract"]["executes_endpoint"]
        is False
    )
    assert (
        payload["controlled_dry_run_receipt_closeout_contract"]["executes_sql"]
        is False
    )
    assert (
        payload["controlled_dry_run_receipt_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_readiness_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run runner readiness should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-runner-readiness?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_readiness
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_execution_plan_binding"
    ]
    runner = payload["controlled_dry_run_runner_readiness"]
    plan = runner["execution_plan_binding"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_readiness"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-receipt-closeout"
    )
    assert payload["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_package_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_readiness_count"] == 1
    assert payload["summary"]["controlled_dry_run_runner_readiness_field_count"] == 12
    assert (
        payload["summary"][
            "controlled_dry_run_runner_readiness_acceptance_gate_count"
        ]
        == 10
    )
    assert payload["summary"]["execution_plan_binding_count"] == 1
    assert payload["summary"]["execution_plan_binding_field_count"] == 12
    assert payload["summary"]["dry_run_result_parser_count"] == 1
    assert payload["summary"]["receipt_validation_report_count"] == 1
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["dry_run_execution_performed"] is False
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert runner["runner_readiness_only"] is True
    assert runner["execution_plan_preview_only"] is True
    assert runner["runner_execution_authorized"] is False
    assert runner["dry_run_execution_authorized"] is False
    assert runner["dry_run_only"] is True
    assert runner["check_mode_only"] is True
    assert runner["accepts_plaintext_secret"] is False
    assert runner["reads_secret_in_preview"] is False
    assert runner["signature_material_included"] is False
    assert runner["secret_material_included"] is False
    assert runner["signs_database_apply_authorization"] is False
    assert runner["executes_authorization_evidence"] is False
    assert runner["executes_database_apply"] is False
    assert runner["executes_endpoint_in_preview"] is False
    assert runner["executes_sql_in_preview"] is False
    assert runner["writes_database_in_preview"] is False
    assert runner["ready_for_database_apply_now"] is False
    assert runner["database_apply_authorized"] is False
    assert plan["execution_authorized"] is False
    assert plan["runner_execution_authorized"] is False
    assert plan["dry_run_execution_authorized"] is False
    assert plan["shell_execution_included"] is False
    assert plan["endpoint_execution_included"] is False
    assert plan["sql_execution_included"] is False
    assert plan["database_write_included"] is False
    assert plan["stdout_capture_allowed"] is False
    assert plan["stderr_capture_allowed"] is False
    assert plan["database_apply_authorized"] is False
    assert (
        payload["controlled_dry_run_runner_readiness_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_readiness_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_readiness_contract"]["executes_endpoint"]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_readiness_contract"]["executes_sql"]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_readiness_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run execution plan closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-execution-plan-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_command_artifact_verification"
    ]
    plan_closeout = payload["controlled_dry_run_execution_plan_closeout"]
    artifact = plan_closeout["non_executable_command_artifact"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_execution_plan_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-runner-readiness"
    )
    assert (
        payload["summary"][
            "controlled_dry_run_execution_plan_closeout_check_count"
        ]
        == 12
    )
    assert payload["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_package_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_plan_closeout_count"] == 1
    assert (
        payload["summary"][
            "controlled_dry_run_execution_plan_closeout_field_count"
        ]
        == 12
    )
    assert (
        payload["summary"][
            "controlled_dry_run_execution_plan_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert payload["summary"]["non_executable_command_artifact_count"] == 1
    assert payload["summary"]["non_executable_command_artifact_field_count"] == 10
    assert payload["summary"]["execution_plan_binding_count"] == 1
    assert payload["summary"]["execution_plan_binding_field_count"] == 12
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert plan_closeout["execution_plan_closeout_only"] is True
    assert plan_closeout["non_executable_command_artifact_only"] is True
    assert plan_closeout["runner_execution_authorized"] is False
    assert plan_closeout["dry_run_execution_authorized"] is False
    assert plan_closeout["execution_authorized"] is False
    assert plan_closeout["dry_run_only"] is True
    assert plan_closeout["check_mode_only"] is True
    assert plan_closeout["accepts_plaintext_secret"] is False
    assert plan_closeout["reads_secret_in_preview"] is False
    assert plan_closeout["signature_material_included"] is False
    assert plan_closeout["secret_material_included"] is False
    assert plan_closeout["signs_database_apply_authorization"] is False
    assert plan_closeout["executes_authorization_evidence"] is False
    assert plan_closeout["executes_database_apply"] is False
    assert plan_closeout["executes_endpoint_in_preview"] is False
    assert plan_closeout["executes_sql_in_preview"] is False
    assert plan_closeout["writes_database_in_preview"] is False
    assert plan_closeout["ready_for_database_apply_now"] is False
    assert plan_closeout["database_apply_authorized"] is False
    assert artifact["command_text_included"] is False
    assert artifact["argv_included"] is False
    assert artifact.get("command_text") is None
    assert artifact.get("argv") is None
    assert artifact["shell_command_included"] is False
    assert artifact["endpoint_execution_included"] is False
    assert artifact["sql_execution_included"] is False
    assert artifact["database_write_included"] is False
    assert artifact["execution_authorized"] is False
    assert artifact["database_apply_authorized"] is False
    assert len(artifact["non_executable_command_artifact_sha256"]) == 64
    assert (
        payload["controlled_dry_run_execution_plan_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_execution_plan_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_execution_plan_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_execution_plan_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_execution_plan_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run command artifact closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-command-artifact-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_runner_execution_receipt_preflight"
    ]
    command_closeout = payload["controlled_dry_run_command_artifact_closeout"]
    receipt_preflight = command_closeout["runner_execution_receipt_preflight"]
    artifact = command_closeout["non_executable_command_artifact"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_command_artifact_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-execution-plan-closeout"
    )
    assert (
        payload["summary"][
            "controlled_dry_run_command_artifact_closeout_check_count"
        ]
        == 12
    )
    assert payload["summary"]["controlled_dry_run_execution_plan_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_package_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_command_artifact_closeout_count"] == 1
    assert payload["summary"]["controlled_dry_run_command_artifact_closeout_field_count"] == 12
    assert (
        payload["summary"][
            "controlled_dry_run_command_artifact_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert payload["summary"]["runner_execution_receipt_preflight_count"] == 1
    assert payload["summary"]["runner_execution_receipt_preflight_field_count"] == 10
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["stdout_capture_allowed"] is False
    assert future["stderr_capture_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert command_closeout["command_artifact_closeout_only"] is True
    assert command_closeout["runner_execution_receipt_preflight_only"] is True
    assert command_closeout["runner_execution_authorized"] is False
    assert command_closeout["dry_run_execution_authorized"] is False
    assert command_closeout["execution_authorized"] is False
    assert command_closeout["dry_run_only"] is True
    assert command_closeout["check_mode_only"] is True
    assert command_closeout["accepts_plaintext_secret"] is False
    assert command_closeout["reads_secret_in_preview"] is False
    assert command_closeout["signature_material_included"] is False
    assert command_closeout["secret_material_included"] is False
    assert command_closeout["signs_database_apply_authorization"] is False
    assert command_closeout["executes_authorization_evidence"] is False
    assert command_closeout["executes_database_apply"] is False
    assert command_closeout["executes_endpoint_in_preview"] is False
    assert command_closeout["executes_sql_in_preview"] is False
    assert command_closeout["writes_database_in_preview"] is False
    assert command_closeout["ready_for_database_apply_now"] is False
    assert command_closeout["database_apply_authorized"] is False
    assert artifact["command_text_included"] is False
    assert artifact["argv_included"] is False
    assert artifact.get("command_text") is None
    assert artifact.get("argv") is None
    assert artifact["shell_command_included"] is False
    assert artifact["endpoint_execution_included"] is False
    assert artifact["sql_execution_included"] is False
    assert artifact["database_write_included"] is False
    assert receipt_preflight["preflight_status"] == "preflight_only_not_executed"
    assert receipt_preflight["execution_required"] is False
    assert receipt_preflight["execution_authorized"] is False
    assert receipt_preflight["runner_execution_authorized"] is False
    assert receipt_preflight["stdout_capture_allowed"] is False
    assert receipt_preflight["stderr_capture_allowed"] is False
    assert receipt_preflight["execution_performed"] is False
    assert receipt_preflight["writes_database"] is False
    assert (
        payload["controlled_dry_run_command_artifact_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_command_artifact_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_command_artifact_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_command_artifact_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_command_artifact_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply controlled dry-run runner execution receipt closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-runner-execution-receipt-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    future = payload[
        "future_database_apply_controlled_dry_run_post_receipt_parser_verification"
    ]
    receipt_closeout = payload[
        "controlled_dry_run_runner_execution_receipt_closeout"
    ]
    preview = receipt_closeout["receipt_closeout_preview"]
    parser = receipt_closeout["post_receipt_parser_verification"]
    preflight = receipt_closeout["runner_execution_receipt_preflight"]
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_controlled_dry_run_runner_execution_receipt_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-controlled-dry-run-command-artifact-closeout"
    )
    assert (
        payload["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_check_count"
        ]
        == 12
    )
    assert payload["summary"]["controlled_dry_run_command_artifact_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_execution_plan_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_readiness_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_receipt_closeout_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_package_check_count"] == 12
    assert payload["summary"]["controlled_apply_final_preflight_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_closeout_check_count"] == 12
    assert payload["summary"]["authorization_evidence_execution_preflight_check_count"] == 12
    assert payload["summary"]["controlled_dry_run_runner_execution_receipt_closeout_count"] == 1
    assert (
        payload["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_field_count"
        ]
        == 12
    )
    assert (
        payload["summary"][
            "controlled_dry_run_runner_execution_receipt_closeout_acceptance_gate_count"
        ]
        == 10
    )
    assert payload["summary"]["post_receipt_parser_verification_count"] == 1
    assert payload["summary"]["post_receipt_parser_verification_field_count"] == 10
    assert payload["summary"]["receipt_closeout_preview_count"] == 1
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert future["runner_execution_authorized"] is False
    assert future["dry_run_execution_authorized"] is False
    assert future["execution_authorized"] is False
    assert future["stdout_capture_allowed"] is False
    assert future["stderr_capture_allowed"] is False
    assert future["ready_for_database_apply_now"] is False
    assert future["database_apply_authorized"] is False
    assert future["issues_database_apply_authorization"] is False
    assert future["signs_database_apply_authorization"] is False
    assert future["executes_authorization_evidence"] is False
    assert future["executes_database_apply"] is False
    assert future["executes_endpoint"] is False
    assert future["executes_sql"] is False
    assert future["writes_database"] is False
    assert receipt_closeout["runner_execution_receipt_closeout_only"] is True
    assert receipt_closeout["post_receipt_parser_verification_only"] is True
    assert receipt_closeout["runner_execution_authorized"] is False
    assert receipt_closeout["dry_run_execution_authorized"] is False
    assert receipt_closeout["execution_authorized"] is False
    assert receipt_closeout["dry_run_only"] is True
    assert receipt_closeout["check_mode_only"] is True
    assert receipt_closeout["accepts_plaintext_secret"] is False
    assert receipt_closeout["reads_secret_in_preview"] is False
    assert receipt_closeout["signature_material_included"] is False
    assert receipt_closeout["secret_material_included"] is False
    assert receipt_closeout["signs_database_apply_authorization"] is False
    assert receipt_closeout["executes_authorization_evidence"] is False
    assert receipt_closeout["executes_database_apply"] is False
    assert receipt_closeout["executes_endpoint_in_preview"] is False
    assert receipt_closeout["executes_sql_in_preview"] is False
    assert receipt_closeout["writes_database_in_preview"] is False
    assert preflight["preflight_status"] == "preflight_only_not_executed"
    assert preflight["execution_required"] is False
    assert preflight["execution_performed"] is False
    assert preflight["stdout_capture_allowed"] is False
    assert preflight["stderr_capture_allowed"] is False
    assert preflight["writes_database"] is False
    assert preview["receipt_status"] == "receipt_closeout_preview_not_executed"
    assert preview["execution_required"] is False
    assert preview["execution_performed"] is False
    assert preview["stdout_included"] is False
    assert preview["stderr_included"] is False
    assert preview["writes_database"] is False
    assert parser["expected_preflight_status"] == "preflight_only_not_executed"
    assert parser["expected_receipt_status"] == "receipt_closeout_preview_not_executed"
    assert parser["execution_required"] is False
    assert parser["stdout_allowed"] is False
    assert parser["stderr_allowed"] is False
    assert parser["database_apply_authorized"] is False
    assert (
        payload["controlled_dry_run_runner_execution_receipt_closeout_contract"][
            "ready_for_database_apply_now"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_execution_receipt_closeout_contract"][
            "executes_database_apply"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_execution_receipt_closeout_contract"][
            "executes_endpoint"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_execution_receipt_closeout_contract"][
            "executes_sql"
        ]
        is False
    )
    assert (
        payload["controlled_dry_run_runner_execution_receipt_closeout_contract"][
            "database_apply_authorized"
        ]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["executes_endpoint_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["reads_secret_in_preview"] is False
    assert payload["safety"]["executes_endpoint"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
    assert payload["safety"]["executes_database_apply"] is False


def test_auto_policy_db_apply_authorization_signing_decision_closeout_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signing decision closeout should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-closeout?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signing_decision_closeout
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_decision_closeout"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-preflight"
    )
    assert payload["summary"]["signing_decision_closeout_check_count"] == 12
    assert payload["summary"]["signing_decision_input_requirement_count"] == 10
    assert payload["summary"]["signing_decision_rejection_reason_count"] == 11
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signing_decision_closeout"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["future_authorization_signing_decision_closeout"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_decision_closeout"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["unsigned_signing_decision_package"]["ready_for_database_apply_now"] is False
    assert payload["unsigned_signing_decision_package"]["signs_database_apply_authorization"] is False
    assert payload["unsigned_signing_decision_package"]["secret_material_included"] is False
    assert payload["unsigned_signing_decision_package"]["secret_material_required_in_preview"] is False
    assert payload["signing_decision_closeout_contract"]["ready_for_database_apply_now"] is False
    assert (
        payload["signing_decision_closeout_contract"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False


def test_auto_policy_db_apply_authorization_signing_issuer_guard_route_defaults_to_no_fetch_and_uses_cached_payload(monkeypatch):
    from flask import Flask
    from routes import ai_routes as routes

    monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())

    def fail_engine(database_path):
        raise AssertionError("cached auto-policy DB apply authorization signing issuer guard should not open a DB engine")

    monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)

    app = Flask(__name__)
    with app.test_request_context(
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-issuer-guard?batch_size=1"
    ):
        response = (
            routes
            .api_pchome_growth_auto_policy_db_apply_authorization_signing_issuer_guard
            .__wrapped__()
        )

    payload = response.get_json()
    assert payload["success"] is True
    assert payload["policy"] == (
        "read_only_pchome_growth_auto_policy_db_apply_authorization_signing_issuer_guard"
    )
    assert payload["source_endpoint"] == (
        "/api/ai/pchome-growth/mapping-backlog/auto-policy-db-apply-authorization-signing-decision-closeout"
    )
    assert payload["summary"]["signing_issuer_guard_check_count"] == 12
    assert payload["summary"]["signing_decision_closeout_check_count"] == 12
    assert payload["summary"]["signing_decision_input_requirement_count"] == 10
    assert payload["summary"]["signing_decision_rejection_reason_count"] == 11
    assert payload["summary"]["signs_database_apply_authorization_count"] == 0
    assert (
        payload["future_authorization_signing_issuer_guard"]["ready_for_database_apply_now"]
        is False
    )
    assert (
        payload["future_authorization_signing_issuer_guard"][
            "issues_database_apply_authorization"
        ]
        is False
    )
    assert (
        payload["future_authorization_signing_issuer_guard"][
            "signs_database_apply_authorization"
        ]
        is False
    )
    assert payload["signable_request_boundary"]["ready_for_database_apply_now"] is False
    assert payload["signable_request_boundary"]["signs_database_apply_authorization"] is False
    assert payload["signable_request_boundary"]["secret_material_included"] is False
    assert payload["signable_request_boundary"]["secret_material_required_in_preview"] is False
    assert payload["signing_issuer_guard_contract"]["ready_for_database_apply_now"] is False
    assert (
        payload["signing_issuer_guard_contract"]["signs_database_apply_authorization"]
        is False
    )
    assert payload["summary"]["reads_secret_count"] == 0
    assert payload["summary"]["executes_script_count"] == 0
    assert payload["summary"]["executes_migration_count"] == 0
    assert payload["summary"]["writes_database_count"] == 0
    assert payload["safety"]["signs_database_apply_authorization"] is False
    assert payload["safety"]["executes_sql"] is False
    assert payload["safety"]["writes_database"] is False
